35
\$\begingroup\$

Sandbox, Codidact

A rewrite of this question with a simpler input format and guidelines.

Challenge

Deadfish uses a single accumulator, on which all commands are to be performed.

It has the following commands:

Command Description
i increment the accumulator
d decrement the accumulator
s square the value of the accumulator
o output the value of the accumulator as a number

The accumulator starts with a value of zero. If, after executing a command, the accumulator is equal to -1 or equal to 256, the accumulator must be reset to zero.

I/O

Input can be taken as a single string, list of codepoints, or any other reasonable format. It is guaranteed that the input will only consist of deadfish commands.

Output can be given as an array of numbers, or just the numbers printed with separators between them.

Testcases

(some are borrowed from the Esolangs wiki)

iissso -> 0
diissisdo -> 288
iissisdddddddddddddddddddddddddddddddddo -> 0
isssoisoisoisoiso -> 1,4,25,676,458329
ooooosioiiisooo -> 0,0,0,0,0,1,16,16,16
iiii -> nothing
iiiiiiiissdiiiiiiiiiiiiiiiiio -> 4112
o -> 0

Without Outputs

\$\endgroup\$
14
  • \$\begingroup\$ Can there be leading separators? \$\endgroup\$
    – att
    Commented Jan 30, 2021 at 22:41
  • \$\begingroup\$ What if the accumulator exceeds 256? For example, 29^2? \$\endgroup\$
    – Xcali
    Commented Jan 31, 2021 at 1:12
  • 4
    \$\begingroup\$ @Xcali the checks are only for -1 or 256, so nothing should happen in that case. \$\endgroup\$
    – Razetime
    Commented Jan 31, 2021 at 2:09
  • 3
    \$\begingroup\$ @tsh As long as it satisfies the testcases, it is fine. The accumulator will stay within the maximum integer range of your language. \$\endgroup\$
    – Razetime
    Commented Jan 31, 2021 at 3:44
  • 1
    \$\begingroup\$ diso tests every functionality of the code except for 256 \$\endgroup\$
    – Gotoro
    Commented Jan 31, 2021 at 14:52

60 Answers 60

1
2
2
\$\begingroup\$

Stax, 37 35 bytes

ï☺C£q▒▒v¡ñ|≥íHQ3╤Ä╫Q,§╪c(>∙α._A↓ö≈/

Run and debug it

I only need one more byte to not blow up on a trailing newline in the input

saved two bytes thanks to Razetime

\$\endgroup\$
9
  • \$\begingroup\$ 0s can be Z \$\endgroup\$
    – Razetime
    Commented Feb 2, 2021 at 2:44
  • \$\begingroup\$ cP can be Q \$\endgroup\$
    – Razetime
    Commented Feb 2, 2021 at 2:47
  • \$\begingroup\$ {d0} can be replaced with 0 since we're not worried about filling up the stack \$\endgroup\$
    – Razetime
    Commented Feb 2, 2021 at 2:49
  • 1
    \$\begingroup\$ With those adjustments, it gets to 30(25 packed) \$\endgroup\$
    – Razetime
    Commented Feb 2, 2021 at 3:00
  • 1
    \$\begingroup\$ @Razetime: I'm not actually very good at golfing. I just know a subset of stax inside and out because I wrote a metacircular compiler for it but never got around to implementing the rest of the instructions. \$\endgroup\$
    – Joshua
    Commented Feb 2, 2021 at 3:59
2
\$\begingroup\$

PowerShell 7, 74 bytes

$args|%{switch($_){i{$x++}d{$x--}s{$x*=$x}o{+$x}}$x=1+$x-and$x-256?$x :0}

Link is to a slightly longer PS 6 solution, as TIO does not yet have PS 7. Try it online!

\$\endgroup\$
2
+50
\$\begingroup\$

APL (Dyalog Classic), 47 bytes

i←+∘1⋄d←-∘1⋄s←×⍨⋄o←⎕∘←⋄{}{0⌈a×256≠a←⍎⍕⍺,⍵}/⌽0,⍞

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Lua (LuaJIT), 153 151 bytes

t={}v=0;loadstring(s:gsub('.',{d='v=v-1;',i='v=v+1;',s='v=v*v;',o='t[#t+1]=v;'}):gsub(';',';v=(v==256 or v<0)and 0 or v;'))()print(table.concat(t,','))

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Yabasic, 119 115 bytes

a=0
for j=1 to len(i$)
c=instr("isdo",mid$(i$,j,1))
if c<4 a=a+2-c
if c=2 a=a*a
if c=4 ?a;
if a<0 or a=256 a=0
next

Try it online!

The actual input is done via reading DATA statements for each Deadfish program. For an interactive version I'd just replace that with an INPUT i$ statement, and calling RUN at the end should re-run the program, initializing variables to 0 and removing the need for the a=0 statement.

I feel this could be more compact, but everything else I try actually makes it bigger. The only really "golf-y" thing is the line:

if c<4 a=a+2-c

which for command 2=square has no effect, avoiding the need for one IF evaluation and saving 11 bytes vs the more straightforward implementation.

Even the XOR 256 trick works out identical in length to the more straightforward version above so I stuck with the simpler code.

edit - I did save 4 bytes because the BASIC interpreter I'm using puts a space as a seperator between numbers automatically, so no need to add it.

\$\endgroup\$
2
\$\begingroup\$

Julia, 70 bytes

s->(a=0;!c=a=[a*=a⊻256>0,a-1,a*a,a+1,c%5>0&&print(a,-)][c÷2%6];.!s)

Based on ovs's answer

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Vyxal DO, 25 bytes

0Ȯ(n«ƛ√J«`›‹²…`ĿĖ:₈u"=a[0

Try it Online!

Saved a byte thanks to Aaron Miller.

0                         # Push 0
 Ȯ(n                      # Iterating over the input
    «ƛ√J«`›‹²…`Ŀ          # Transliterate into appropriate Vyxal instruction
                Ė         # Evaluate
                 :₈u"=a[  # If 256 or negative
                        0 # Push 0
\$\endgroup\$
1
  • \$\begingroup\$ You should add the O flag. Also, 25 bytes. \$\endgroup\$ Commented Aug 27, 2021 at 14:47
2
\$\begingroup\$

Swift, 120 bytes

{(s:String)in var i=0
s.forEach{switch $0{case"i":i+=1 case"d":i-=1 case"s":i*=i default:print(i)}
if i==256||i<0{i=0}}}

Returns a closure that takes the input as an argument. If the input contains o multiple times, the numbers are separated by newlines.
Try it online (full program that uses hardcoded input)

Ungolfed:

{ (str: String) in
    var i = 0
    str.forEach { (char: Character) in
        switch char {
        case "i":
            i += 1
        case "d":
            i -= 1
        case "s":
            i *= i
        default: // "o"
            print(i)
        }
        
        if i == 256 || i < 0 {
            i = 0
        }
    }
}
\$\endgroup\$
2
\$\begingroup\$

Python 3.8 (pre-release), 117 bytes

def f(x,o=0):
	for c in x:
		if o>256or o<0:o=0
		if(v:=ord(c)&6)<1:o+=1
		if v<3:o**=2
		if v<5:o-=1
		else:print(o)

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ equal to 256 this does not allow numbers greater than 256, which the spec does \$\endgroup\$
    – emanresu A
    Commented Mar 30, 2022 at 3:32
  • \$\begingroup\$ @emanresuA fixed \$\endgroup\$ Commented Mar 30, 2022 at 11:54
  • \$\begingroup\$ ayo!, := doesn't have in python 3. guy \$\endgroup\$ Commented Apr 2, 2022 at 17:48
  • 1
    \$\begingroup\$ @patcharalimtrairat fixed \$\endgroup\$ Commented Apr 2, 2022 at 17:57
2
\$\begingroup\$

Piet with ascii-piet encoding, 140 bytes

Outputs numbers with a space as a separator. Goes into an infinite loop once it runs out of input. (If using npiet, the -q flag will suppress the "?" prompts, and -e will set a number of execution steps to kill the program after. 1300 steps is enough to run the longest test case.)

Piet code (codel size 4):

A Deadfish interpreter written in Piet, the abstract-art programming language.

ascii-piet version (with line breaks added):

vnmdeusausejbsvcldvufktdtqeC
eeeee     jjllllltln  tdt  A
e dde     jjrjc?????  dda  K
e dmn????c       mmiii  m  N
e ??narvfctisjicemmnaai??ctD

Try it online!

Explanation

After initialising the accumulator with 0, a character is read from standard input. Its value is then decremented by 100 (for "d"), by another 5 ("i"), and by another 6 ("o"), branching once it hits zero. If it still hasn't hit zero, it's assumed to be "s".

(Actually, I messed up and put the "s" code on the branch and the "o" code on the straight path, which runs all the way around the outside. This was convenient, since output takes more code than squaring, so I left it that way and just negated the relevant check.)

Coming back across the bottom, after some codel-chooser twiddling, the new accumulator value is compared to 256 and then (if that didn't branch) to -1. If either one compares equal, it branches again into code that resets the accumulator to 0.

And then it repeats from the character read.

\$\endgroup\$
2
\$\begingroup\$

Vyxal O, 19 bytes

0?(n`ḟ``ġ`ĿĖ:₈u"c[0

Try it Online!

This is really cheating, but whatever. Short dictionary abuse ftw

Vyxal OD, 20 bytes

0?(n½`›²‹…`iĖ:₈u"c[0

Try it Online!

Input as list of codepoints, no cheating.

\$\endgroup\$
2
\$\begingroup\$

*><>, 121 bytes

I didn't check before writing this, and now see that I was already long ago beat by ><> but oh well. I'm not going to not post this after all that effort.

r01[D63.
>:884**=  ?!\~0v
^v0~u!?=-10:<u <
^>  OD~l0=?!\;
^+1I/!?="i":/
^   \:"d"=?!\I1-
^*:I/!?="s":/
^   \:"o"=?!;I:aon

Explanation

The program works through 3 main sections, and one initialization section. It uses two stacks: one input stack, and one accumulator stack.

Breakdown

; Initialize
r01[D63.

; Bounds Check
>:884**=  ?!\~0v
^v0~u!?=-10:<u <

; End of input check
^>  OD~l0=?!\;

; Main look
^+1I/!?="i":/
^   \:"d"=?!\I1-
^*:I/!?="s":/
^   \:"o"=?!;I:aon

Initialization

r         Reverse the input
 0        Push the accumulator onto the stack
  1[      Move the accumulator to a new stack
    D     Return to the input stack
     63.  Move to [3,6] in the code block (pushing the length of the stack onto the stack in the input check)

Bounds check

>                 Set the IP direction rightward
 :                Duplicate the accumulator
  884**           Push 256 onto the stack
       =          Is the accumulator 256
          ?!\     If not, mirror the IP downward
                  Else
             ~      Remove the accumulator from the stack
              0     Push 0 onto the stack
               v    Change IP direction downward

               <    Change IP direction leftward
             u      Dive, and ignore any non-movement instructions until we rise
            <     Change IP direction leftward
           :      Duplicate the accumulator
        -10       Push -1 onto the stack
       =          Is the accumulator -1
    u!?           If not, dive
                  Else
   ~                Remove the accumulator from the stack
  0                 Push 0 onto the stack
 v                  Change IP direction downward
^                 Change IP direction upward (Used when returning to the top of the bounds check)

End of Input check

^                 Change IP direction upward (Used when returning to the top of the bounds check)
 >                Set the IP direction rightward
    O             Rise from any potential dive we may have done (ignored if there was none)
     D            Change to the input stack
      ~           Remove the an instruction from the top of the stack
       l          Push the length of the stack onto the stack
        0         Push 0 onto the stack
         =        Is the length of the stack 0
          ?!\     If not, mirror the IP downward
             ;    Else, halt execution

Main block

I've condensed the main block's explanation for the sake of brevity.

            /       Mirror IP to the left
       ="i":        Is our current instruction i
    /!?             If not, mirror IP downward
                    Else
^+1I                  Switch to accumulator stack, add 1, and set IP direction upward (returning to bounds check)

    \               Mirror IP to the right
     :"d"=          Is our current instruction d
          ?!\       If not, mirror IP downward
                    Else
^            I1-      Switch to accumulator stack, subtract 1, and set IP direction upward

            /       Mirror IP to the left
       ="s":        Is our current instruction s
    /!?             If not, mirror IP downward
                    Else
^*:I                  Switch to accumulator stack, duplicate the accumulator and multiply it against itself, set IP direction upward

    \               Mirror IP to the right
     :"o"=          Is our current instruction o
          ?!;       If not, halt execution
                    Else
             I:a      Switch to accumulator stack, duplicate the accumulator, push 10 onto the stack
^               on    Print the 10 (newline) and our accumulator value, and set IP direction upward

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Icon, 106 bytes

procedure f(s);a:=0
c:=!s&(if a:=[a+1,a-1,a*a][find(c,"ids")]then 1>ixor(a,256)&a:=0 else write(a))&\z
end

Try it online!

\$\endgroup\$
1
\$\begingroup\$

PowerShell, 118 bytes

$args[0]|% t*y|%{if($a-in@(-1,256)){$a=0}if($_-eq'i'){$a+=1}elseif($_-eq'd'){$a-=1}elseif($_-eq's'){$a=$a*$a}else{$a}}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Batch, 157 bytes

@set a=0
@for %%c in (%*) do @call:%%c
:s
@set/aa=a*a-1
:i
@set/aa+=2
:d
@set/aa-=1
@if %a%==-1 set a=0
@if %a%==256 set a=0
@exit/b
:o
@echo %a%

Takes each Deadfish command as a separate command-line argument. Explanation:

@set a=0

Initialise the accumulator.

@for %%c in (%*) do @call:%%c

Loop through all of the commands, executing each in turn, then fall through into performing an additional s command, whose effect is non-observable.

:s
@set/aa=a*a-1

For the s command, square the accumulator and decrement it, then fall through to the i command, which increments it again.

:i
@set/aa+=2

For the i command, add 2 to the accumulator, then fall through to the d command, which decrements it.

:d
@set/aa-=1

For the d command, decrement the accumulator.

@if %a%==-1 set a=0
@if %a%==256 set a=0
@exit/b

Adjust the accumulator if necessary, then return for the next command.

:o
@echo %a%

For the o command, output the accumulator, then implicitly return for the next command.

204 bytes taking input as a single string (probably actually not the best approach; the call-and-fall through approach above could probably save 10 bytes):

@set/ps=
@set a=0
:l
@if "%s%"=="" exit/b
@for %%a in (1+1.i 1-1.d a.s)do @if %%~xa==.%s:~,1% set/aa=a*%%~na
@if %s:~,1%==o echo %a%
@set s=%s:~1%
@if %a%==-1 set a=0
@if %a%==256 set a=0
@goto l

Takes input on STDIN. Explanation:

@set/ps=
@set a=0

Read the commands and clear the accumulator.

:l
@if "%s%"=="" exit/b

Loop until there are no commands left.

@for %%a in (1+1.i 1-1.d a.s)do @if %%~xa==.%s:~,1% set/aa=a*%%~na

If the command is an arithmetic operation then perform the calculation: a=a*1+1 for i, a=a*1-1 for d and a=a*a for s; it's not possible to use * in a for loop because it's always a wildcard and cannot be quoted (unlike =, which can be quoted).

@if %s:~,1%==o echo %a%

If the command is an o then output the accumulator.

@set s=%s:~1%

Remove the command from the input.

@if %a%==-1 set a=0
@if %a%==256 set a=0
@goto l

Adjust the accumulator if necessary and loop.

\$\endgroup\$
1
\$\begingroup\$

Racket, 178 bytes

(define(f s[a 0])(unless(null? s)(let([x(car s)][y(cdr s)][b(match a[-1 0][256 0][_ a])])(match x[105(f y(+ b 1))][100(f y(- b 1))][115(f y(* b b))][_(and(writeln b)(f y b))]))))

Try it online!

More readable:

(define (f s [a 0])
  (unless (empty? s)
    (let ([x (first s)]
          [y (rest s)]
          [b (match a
               [-1  0]
               [256 0]
               [_   a])])
      (match x
        [105 (f y (+ b 1))]
        [100 (f y (- b 1))]
        [115 (f y (* b b))]
        [_   (and (writeln b)
                  (f y b))]))))
\$\endgroup\$
1
\$\begingroup\$

R, 111 91 bytes

-20 bytes thanks to CriminallyVulgar

C=scan(,'');n=0;for(x in C){if(n%in%c(-1,256))n=0;n=switch(x,i=n+1,d=n-1,s=n^2,o=print(n))}

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 91 using a switch instead of the clever arithmetic: Try it online! \$\endgroup\$ Commented Feb 2, 2021 at 17:28
1
\$\begingroup\$

Vyxal, 28 bytes

❝,(\&`\⨥\⨪\²\₴`ni+ₑuγd‿¥c[0£

Try it Online!

Takes a list of numbers, where 0 represents i, 1 represents d, 2 represents s and 3 represents o

\$\endgroup\$
1
  • \$\begingroup\$ @2x-1 that's a result of the safe-evaluation regex I have in place \$\endgroup\$
    – lyxal
    Commented Mar 1, 2021 at 3:56
1
\$\begingroup\$

Pip, 39 bytes

Fca;V("U  i&D SQ:   P"^sAc)."i*:i!=256"

Takes the Deadfish program as a command-line argument. Try it here! Or, here's a 42-byte version in Pip Classic: Try it online!

Explanation

The variable i is preset to 0, so we'll use it for the accumulator.

Fca;V("U  i&D SQ:   P"^sAc)."i*:i!=256"
Fca;                                     For each c in command-line argument a:
      "U  i&D SQ:   P"                    Take this string
                      ^s                  Split on spaces into a list of 7 strings
     (                    )               Index (0-based, modular) into that list using
                        Ac                the ASCII code of c
                           .              Concatenate
                            "i*:i!=256"   this string
    V                                     Eval as Pip code

The code snippets for each command are:

i -> index 0 -> Ui*:i!=256
d -> index 2 -> i&Di*:i!=256
s -> index 3 -> SQ:i*:i!=256
o -> index 6 -> Pi*:i!=256

The first three expressions change the value of i and then multiply it by 0 if the new value equals 256:

Ui    Increment i
i&Di  If i is not 0, decrement i
SQ:i  Square i in place

The fourth expression parses a little differently: since P is lower precedence than assignment, it works out to "multiply i by 0 if it equals 256, and then print." Fortunately, since printing doesn't change the value of i, the order doesn't matter.

\$\endgroup\$
1
\$\begingroup\$

TI-Basic, 83 bytes

Input Str1
For(I,1,length(Str1
inString("ids",sub(Str1,I,1→J
If Ans:Then
{A+1,A-1,A²
Ans(J
max(0,Ans)(Ans≠256→A
Else
Disp A
End
End

Input is taken as a string and outputs are printed and separated with newlines.

\$\endgroup\$
1
\$\begingroup\$

PHP 7 (104 chars)

Given argv[1] as a command line argument :

for($r=0,$s=$argv[1];@$a=$s[$i++];$r*=$r-256&&~$r)@($a>i?$a>o?$r*=$r:print$s[$i]?"$r,":$r:$r+=$a>d?:-1);

Try it online

\$\endgroup\$
1
\$\begingroup\$

Desmos /w ticker, 269 bytes

try it online

Code in ticker:

\left\{I[n]=4:T,\ I[n]=3:v->\left\{v^2=256:-1,v^2\right\},I[n]=2:v->\left\{v-1=-1:0,v-1=256:0,v-1\right\},I[n]=1:v->\left\{v+1=-1:0,\ v+1=256:0,\ v+1\right\}\right\},\ n-> n+1

Code in list:

I=[]
O=[]
i=1
d=2
s=3
o=4
n=0
v=0
T=O->\operatorname{join}(O,\left\{v=-1:0,v=256:0,v\right\})
\$\endgroup\$
1
\$\begingroup\$

Kotlin, 113 bytes

{var o=listOf<Int>();var a=0;for(s in it){when(s){'i'->a++;'d'->a--;'s'->a*=a;'o'->o+=a};if(a==-1||a==256)a=0};o}

Type signature: String -> List<Int>

\$\endgroup\$
1
\$\begingroup\$

minigolf, 55 bytes

Had to do this because it's ridiculously easy to do in minigolf.

0i,nWT*+1,;,nB=,:_n0=,T+_n5=,1+_nF=,:*__::V=sT=+,0*__,_

Try it online!

(For the iiii case, though, it produces an index out of bounds error to STDERR, but nothing is outputted to STDOUT.)

Explanation

0               Push 0 as initial accumulator
i,              For each item in the (inputted) command sequence:
  n               Push current command
  WT*+            Subtract by 100
                  (since we have constants 0 thru 17
                  as convenient 1-byte builtins)
  1,;             Wrap it into a singleton list
                  (because we want to re-use it several times)
  ,               Fry sequence:
    nB=,          If current result is 11 (aka. `o`)
      :             Duplicate the current accumulator value.
                    (which effectively outputs the accumulator as it's not changed later)
    _             End if
    n0=,          If curr = 0 (aka. `d`):
      T+            Add acc by -1
    _             End if
    n5=,          If curr = 5 (aka. `i`)
      1+            Add acc by 1
    _             End if
    nF=,          If curr = 15 (aka. `s`)
      :*            Square the acc
    _             End if
  _               End fry sequence
  ::              Triplicate the acc
  V=              Is it equal to 256?
  sT=             Swap, is it equal to -1?
  +               Add them together
  ,               Repeat n times:
                  (we definitely only have one condition satisfied, so the value of + must be either 0 or 1)
    0*              Multiply acc by 0 (i.e. set it to 0)
  _               End repeat
_               End foreach loop
,_              Drop the last acc value (so that it's not outputted to STDOUT)

Implicit output stack
\$\endgroup\$
1
\$\begingroup\$

Scala, 144 bytes

Modified from @Gotoro's answer.


Golfed version. Attempt it online!

var n=0;for(x<-readLine()){if(n== -1||n==256)n=0;if(x=='o')println(n)else n=((x.toInt%4)^1)match{case 0=>n+1;case 1=>n-1;case 2=>n*n;case _=>n}}

Ungolfed version. Attempt it online!

import scala.io.StdIn.readLine

object Main {
  def main(args: Array[String]): Unit = {
    var n = 0
    for (x <- readLine()) {
      if (n == -1 || n == 256) n = 0
      if (x == 'o') println(n)
      else n = ((x.toInt % 4)^1) match {
        case 0 => n + 1
        case 1 => n - 1
        case 2 => n * n
        case _ => n
      }
    }
  }
}

\$\endgroup\$
1
\$\begingroup\$

><> (Fish), 49 bytes

05i8%.
1+v

:*v
1-v


:nv
0.\:01-=}:"Ā"={+0$?$~0

Try it

Beats the existing answer by about 30 bytes. Branchless -1 and 256 checking logic copied from this excellent answer

\$\endgroup\$
1
\$\begingroup\$

Easyfuck, 167 bytes

Ì¡n␅␏␖SHYÀ¡kæ␋^)VSHYòMWo␒>|NELâGÉAPCE³ù忸␔>VñM×É␖àPñâ¥2PU2>|§:NELwAPC^RPU1ãåPLD¯[¼ùbë×ZÙ]nSŸ␝«¶òëêl%!}yn␅␏APC>|ù^␅␏␕¾SSGCIâSTëp(|ùóå¸␔<ZùNe9ÖàPùòGÏDCS¼I5óä/␒>SCIPU1ãÇSS3_f|§:Ü␊␟>APCMPU2êyAPC>R®õØ␃täç¼␀␀␀␀

due to lack of unicode representations for c1 control characters, they have been replaced by their superscripted abbreviations

Decompressed:

f(-`(<--`(->0-<)++>)+<$>>!<$>&>EY~<[}`(>+<)]>$-`(<<*)J$>>)g(+^>^)$<>,.^[^>,.^]5Y.[J<-`;+[<]>S0J!>^-`(>>>>>+`(<+>)f<)g-`(>>>>-`(<->)f)g-`(>>$>>!<$M>>!<$>M$<<<=>f>)g-`(>>OS2.Sf>>)+^]@␍idso␀␀␀␀
\$\endgroup\$
1
\$\begingroup\$

Uiua 0.10.0, 39 bytes

◌∧(⍥⋅0∊,¯1_256⟨-1|+1|&p.|ⁿ2⟩):0⊗:"dios"

Explanation + See it in action

\$\endgroup\$
0
\$\begingroup\$

Batch 160 bytes

@Set v=0&@Set i=v+=1&@Set d=v-=1&@Set s=v*=v&2>nul (@For %%i in (%*)Do @Set/A"-1/(v+1)"||Set v=0&Set/A"256/(v-256)"||Set v=0&Call Set/A%%%%i%%||Call Echo(%%v%%)

How? :

  • & = concatenate commands
  • @Set v=0 = Zero accumulator value
  • Set i=v+=1 ; Set d=v-=1 ; Set s=v*=v = Defines operation to perform when command parameters parsed
  • For %%i in (%*)Do = Iterate over command parameters
  • @Set/A"-1/(v+1)"||Set v=0 = Conditional assesment of accumalator if value EQU -1 (Set /A opeations fails due to divide by zero error)
  • Set/A"256/(v-256)"||Set v=0 = Conditional assesment of accumalator if value EQU 256 (Set /A opeations fails due to divide by zero error)
  • Call Set/A%%%%i%%|| = expands to the defined command arg operation or FAILS for the undefined o command (Missing operator), triggering || execution of Call Echo(%%v%%
    • Call triggers additional parsing steps for the subsequent command, allowing a variable named with %%I's value to be expanded, without having to resort to using delayed expansion.
  • 2>nul (For ...) redirection used to suppress STDERR resulting from operations with missing operators or that divide by zero
\$\endgroup\$
0
\$\begingroup\$

Swift 5.9, 119 bytes

let f={var a=0,o=[Int]()
for i in""+$0{i=="o" ?(o+=[a]):i>"r" ?(a*=a):(a+=i>"d" ?1:-1)
if -1==a||a==256{a=0}}
return o}

TIO doesn't support Swift 5, so here's a JDoodle link instead, with test cases.

\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.