title: Triangular code, triangular output

text:
# Question
Title: Triangular code, triangular output
For this challenge, submissions should be a program or function shaped like a right triangle, which produces a right triangle of the same size.

**What is a right triangle?**

For this challenge, a right triangle consists of 1 or more lines, each containing a number of characters (assume all non-newline characters are the same width) equal to that line number:

```
.
..
...
....

```

Trailing newlines are allowed.

**The challenge:**

Your code should form a right triangle, and output a right triangle with the same height made up of any non-newline characters.

As this is code golf, shortest answer in bytes per language wins.

# Answer
# , 34 bytes

```
#
d=
cat
d(9^
(1:7)
,sep="
")#####

```

Try it online!

Outputs \\$9^1\\$ to \\$9^7\\$:

```
9
81
729
6561
59049
531441
4782969

```
> 20 votes

# Answer
# C (gcc), 53 bytes

*Fixed error pointed out by @S.S. Anne*

```
\
m\
ain
(n){
9<pr\
intf(\
"%d\n",
n*=9)||\
main(n);}

```

Try it online!
> 14 votes

# Answer
# brainfuck, 1 byte

```
.

```

Outputs a single null byte.

Try it online!
> 11 votes

# Answer
# JavaScript (ES7),  ~~43~~  34 bytes

A triangle of 7 rows, filled with `0`'s.

```
f
=(
s=`
`)=>
s[7]?
'':0+s
+f(0+s)

```

Try it online!

### Commented

```
f   // f is a recursive function
=(   // taking
s=`   // a string s initialized to
`)=>   // a linefeed
s[7]?   // if s has more than 7 characters,
'':0+s   // stop recursion; otherwise append a 0, followed by s,
+f(0+s)   // followed by the result of a recursive call with 0 + s

```
> 11 votes

# Answer
# Perl 5, ~~66~~ ~~54~~ ~~53~~ 19 bytes

```
#
##
use
####
Quine

```

I am submitting this as a joke because I did not even bother trying to write some optimized code. Instead, I am using a module from CPAN that causes the program to print itself.

The `Quine.pm` module can be found on CPAN and was released in January 2001, long before this question was posted here. So I assume that it is acceptable, as it seems to be the tradition in other Code Golf questions.

Edit 1: Saved 12 bytes by removing the semicolon after the `use` statement.

Edit 2: Thanks to Arnauld for pointing out that I did not need the final newline character, saving one byte.

Edit 3: Thanks to petStorm who made a great improvement by putting the `use` statement and the module name on separate lines, reducing the program to only 19 bytes. This exercise that started as a joke is now a very competitive entry. It would be difficult to do better in a non-obscure language (insert joke about Perl's readability here).
> 9 votes

# Answer
# Bash, 26 bytes

The `dc` command turns out to be quite useful in code-golfing.

```
\
d\
c \
-e{\
5..1\
0}*p \

```

Try it online!
> 9 votes

# Answer
# Python 2, ~~53~~ 43 bytes

I think we are allowed to output different characters. Because of this, I simply printed \\$10^i\\$ at every iteration.

```
#
##
###
i=1;
exec\
"prin\
t i;i*\
=10;"*8\

```

Try it online!
> 8 votes

# Answer
# Haskell, ~~76~~ ~~64~~ 53 bytes

```
u
 =
 (9
 ^)
 <$>[
 1..9]
main=
 mapM_
 print u

```

Try it online!

This prints the first 9 powers of 9.
> 6 votes

# Answer
# Ruby, 34 bytes

```
(
##
1..
7)##
.map{
|x|p(#
9**x)}#

```

Try it online!
> 6 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~64~~ ~~53~~ 43 bytes

```
;
;;
int
s=1,
i;for
(;i++<
9;Print
(s*=9));

```

Simply prints the first several powers of 9.

Try it online!
> 5 votes

# Answer
# Befunge-98 (FBBI), 34 bytes

Outputs \\$ 9^k, 1 \leq k \leq 7 \\$.

```
v
8v
<v1
v< @
> 9*v
.^ >\:
a,:|>1-

```

Try it online!

The first three lines

```
v
8v
<v1

```

push 8 (loop counter) and 1 (\\$ 9^0 \\$). The main loop can be written in a single line as

```
9*\1-a,:!#@_\:.
9*               multiply by 9
  \              swap to loop counter
   1-            subtract 1
     a,          output newline
       :!        duplicate and invert loop counter
         #@_     quit if non-zero, continue east otherwise
            \    swap to 9^k
             :.  duplicate and output 9^k

```

Try it online!
> 5 votes

# Answer
# 05AB1E, 1 bytes

```
0

```

Try it online.

Not much to say I guess..

---

If this was instead, we could do something like this (can be made as arbitrary large as you'd want it to, as long as the last three bytes are `₄*»`):

```
1
11
111
1111
11111
111111
1111111
11111111
111111111
1111111₄*»

```

Try it online.

**Explanation:**

```
1\n11\n111\n...  # Push all these numbers one by one to the stack
111...111        # Push the number of the last line
₄*               # Multiply it by 1000 to increase its size by 3
»                # Join everything on the stack by newlines
                 # (after which it is output implicitly as result)

```
> 5 votes

# Answer
# C (gcc), 53 bytes

```
;
m\
ain
(n){
9/pr\
intf(\
"%d\n",
n)&&mai\
n(n*10);}

```

Prints powers of 10.

Try it online!
> 4 votes

# Answer
# PHP, 43 bytes

```
;
1;
for
(;$i
++<8;
)echo(
10**$i-
1)."\n";

```

Try it online!

Not that bad for PHP.. displays a triangle of "9"
> 4 votes

# Answer
# Java 10, 76 bytes (11 rows)

```
v
->
{//
 var
r="";
long i
=0,s=1;
for(;++i
<12;r+=(s
*=9)+"\n")
;return r;}

```

Inspired by all the other answers.

Try it online.
> 4 votes

# Answer
# SQL (Oracle) 88 76 Bytes

```
;
/*
ABC
DEFG
HIJ*/
SELECT
LPAD(1,
LEVEL,1)
FROM DUAL
CONNECT BY
LEVEL < 12;

```

Try it out

Output:

```
1
11
111
1111
11111
111111
1111111
11111111
111111111
1111111111
11111111111

```

Edit: Thanks @Math Junkie, by following the rules I actually cut off 12 bytes.
> 4 votes

# Answer
# SmileBASIC 4, 3 bytes

```
\
?0

```

---

```
0
OK

```
> 4 votes

# Answer
# Wolfram Language (Mathematica), 43 bytes

```
\
"\
"<\
>".\
"~Ta\
ble~#\
&/@Ran\
ge [8*1]

```

Try it online!
> 3 votes

# Answer
# Clojure, ~~103~~ ~~89~~ 76 bytes

```
(
;;
;;;
loop
[i 9]
(when(
* i;;;;
99999999
)(println
i)(recur(*
i 9))));;;;

```

Try it online!

Prints the first 11 powers of 9. Exits with an `ArithmeticException: integer overflow` when trying to multiply \\$9^{12}\\$ by \\$99999999\\$.
> 3 votes

# Answer
# Canvas, 1 byte

Boring solution, just like everyone else. :)

```
\

```

Try it here!

# Canvas, 4 bytes

Non-trivial attempt.

```
＼
２＼

```

Try it here!

# Explanation

```
＼    # Draw a diagonal, with nothing on the stack
      # Errors silently
      # Newline: A character not in the code page.
      # It basically does nothing.
２    # 2: Push 2 onto the stack
  ＼  # Draw a diagonal with a length of 2
      # Implicit output

```
> 3 votes

# Answer
# Bash \+ GNU utilities, 43 bytes

```
\
s\
eq\
 -f\
'seq\
 -s "\
" %f' \
$[+8]|sh

```

Try it online!

I couldn't quite get this down to 7 rows; I needed to pad it by 4 bytes to fill out the 8-row triangle (that's why I have `$[+8]` in the code instead of just `8`).

---

**BSD Challenge!**

If you take the same idea as the GNU solution above but use the BSD utility `jot` instead of `seq`, it's just one byte too long for a 7-row solution (which would be 34 bytes):

```
    \
    j\
    ot\
     -w\
    'jot\
     -s "\
    " ' 7|sh
# This is one byte too long for 7 rows :( .

```

**If someone can see how to shave just 1 byte** off this BSD version, that would get it down to a 7-row 34-byte solution.

Here's a TIO link to the BSD version if anybody wants to try their hand at eliminating that one last byte! This also works under OS X, if you have a Macintosh.

(Obviously this version, like the GNU version in my main answer above, can be padded to be another 8-row 43-byte solution, but that's not as interesting.)
> 3 votes

# Answer
# Bash, 64 bytes

```
\
d\
at\
e +\
d%n%\
m%n%j\
%n%Y%n\
%R%n%:z\
%n%7Y%n%\
T%n%N%n%F\

```

Try it online!

Not the shortest but kind of fancy. Displays current date in convinient format. Tried to do it locales intependent. Last byte for fancy too.
> 3 votes

# Answer
# C (gcc), 53 bytes

```
\
m\
ain
(n){
for(;
9/n;n=
printf(
"%0*d\n"
,n,0));;}

```

Try it online!

# C (gcc), 53 bytes

```
\
m\
ain
(n){
9/n&&
main(\
printf(
"%0*d\n"
,n,0));;}

```

Try it online!
> 3 votes

# Answer
# C Preprocessor, 65 bytes (10 lines)

```
.
..
...
....
.....
......
.......
........
.........
__TIME__//

```

Process with GCC/Clang with `-E` and `-P` options. (Thanks to Calculuswhiz for suggesting the `-P` option.)

All the dots are ignored. The predefined `__TIME__` macro expands to a string of the form `"HH:MM:SS"`, meaning the last line stays the same length.
> 3 votes

# Answer
# Husk, 13 bytes

```
₁
¶₂
ΘI₃
↑3İ⁰

```

Try it online!

No comment characters, so every element does something...

```
₁       # run function on line 1 (next line)
¶₂      # split output of function on line 2 (next line)
ΘI₃     # prepend zero to identity of function on line 3 (next line)
↑3İ⁰    # first 3 elements of powers of 10

```

---

# Husk, 1 byte

*Trivial (but included for completeness)*

```
1

```

Try it online!

(there are many more like this... all equally uninteresting...)
> 3 votes

# Answer
# PowerShell Core, 4 bytes

Trivial power (up to 19 lines)

```
1
10

```

Try it online!

---

# PowerShell Core, 4 bytes

p–n junction (90 variants)

```
1
-1

```

Try it online!

---

# PowerShell Core, 26 bytes

Twinkle, twinkle, little star

```
,
'*
*'*
6|%{
'*' *
++$ko}

```

Try it online!

---

# PowerShell Core, 26 bytes

The magic number in nuclear physics and the quark soup of 3 quarks `$_`

```
,
1+
2..
6|%{
"$_"*
$_};$_

```

Try it online!
> 3 votes

# Answer
# TeX, 188 bytes

Nothing out of the ordinary, but for completeness:

```
%
%%
%%%
%%%%
%%%%%
%%%%%%
%%%%%%%
%%%%%%%%
\countdef
~=1%%%%%%%
\countdef%%
\i=26\loop%%
\advance~1{%%
\loop\advance%
\i1.\ifnum\i<~%
\repeat\endgraf}
\ifnum~<18\repeat
\bye%%%%%%%%%%%%%%

```
> 3 votes

# Answer
# Factor, ~~34~~ 26 bytes (~~7~~ 6 lines)

*-8 bytes / 1 line* thanks to Bubbler!

```

10
  6
iota
  n^v
stack.

```

Try it online!

**Output:**

```
1
10
100
1000
10000
100000

```
> 3 votes

# Answer
# Pxem, Filename: 103 bytes + Content: 0 bytes = 103 bytes

Filename as follows (if your filesystem doesn't support LF, I'm sorry) (also requires to be ASCII-compatible):

```
x
.p
x.n
.o.n
.o04x
.-.t.z
.c.zxxx
.a.m.m.w
.sx.oab.-
.s.-.c.a.s
.c.o.c.$.mx
.s.s.+.tao.-
.s.m.a.dxxxxx

```

Content is empty.

Try it online, with rpxem!

## Output

```
x
10
120
xxxx
xxxxx
xxxxxx
xxxxxxx
xxxxxxxx
xxxxxxxxx
xxxxxxxxxx
xxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxxx

```

## With comments

Note that every LF is replaced with '?'.

```
x?.pXX.z # print'x', LF
.a?x.nXX.z # print LF.ord # two-digits
.a?.oXX.z # print LF
.a.n?.sXX.z
.a04x?.-.tXX.z # i = 4
.a.zXX.z # loop
  .a?.c.zxxx?.aXX.z # essentially nop
  .a.m.m.wXX.z # j = i; while j!=0
    .a?.sx.oXX.z # print'x'
    .aab.-?.s.-.cXX.z # j--
  .a.a.s?.c.oXX.z # end-while; print LF
  .a.c.$.mx?.s.s.+.tXX.z # i++
  .aao.-?.s.mXX.z # break if !(14>i)
.a.a.dxxxxx # end-loop; end program

```
> 3 votes

# Answer
# Knight, 26 bytes

```
;
=a
0W>
6aO*
'.'=a
+1aQQQ

```

Try It Online!
> 3 votes

# Answer
# dc, 4 bytes

```
B
1f

```

Try it online!

**Explanation:**

```
B   Push 11 on the stack.
1   Push 1 on the stack.
f   Print the items on the stack, starting at the top, each one with a terminal newline.

```
> 2 votes

# Answer
# Io, 43 bytes

A lot more "content" than my previous submissions.

```
\
 \
  \
for(
i,1,8
,(9**i
)     \
println)

```

Try it online!
> 2 votes

# Answer
# Erlang (escript), 76 bytes

```
f
()
->[
%%%%
%%%%%
string
:copies
("!", X)
++"\n"||X
<- lists :
seq(1,11)].

```

Try it online!
> 2 votes

# Answer
# Python 3, 53 bytes

```
#
##
###
for\
i in\
range(
9):####
 print(#
10**i)###

```

Try it online! Similar to dingledooper's submission. I was also going to submit:

## brainfuck, 1 byte!!

```
.

```

Try it online! But S.S.Anne beat me by a couple of hours :)
> 2 votes

# Answer
# Jelly, 1 byte

```
0

```

Try it online!

---

The vast majority of atoms can be used for this, printing `0` or `1`. The few exceptions are listed as follows: (incomplete, didn't check past  in the Atoms page)

* `³⁴⁵⁹`: prints more than one digit
* `½°`: prints `0.0`
* `~`: prints `-1`
* : prints `\n`
* `⁸IRḶṬẈ`: prints nothing
* `MTZ`: errors
* `Ɠƈɠ`: interacts with STDIN

Borderline:
> 2 votes

# Answer
# HQ9+, 1 byte

```
Q

```

Try it online!
> 2 votes

# Answer
# dirt, 43 bytes

```
x
xx
xx|
|'a'
(a*'a
)**{1|
}.*|"11
11111"|x

```

run with with empty string as input:

```
>dirt triangle.dirt -i ""
a
aa
aaa
aaaa
aaaaa
aaaaaa
aaaaaaa
aaaaaaaa

```
> 2 votes

# Answer
# Stax, 4 bytes

```
2
mR

```

Run and debug it at staxlang.xyz!

Nontrivial solution. Prints "\x01\n\x01\x02", so you won't see any output, but it's there. One byte is easy but boring.

```
2     Push 2
mR    For n in [1,2], print [1..n] as a string

```

Another 4-byter that feels like cheating:

```
0     Do nothing
|?    Source of program, implicit print.

```
> 2 votes

# Answer
# x86 machine code (32-bit), 43 bytes

As symbols in codepage 437:

```
`
!Q
!j
!Y_j
Q░x≤¬
'YX¬A╢
Ç∙ëq∞Çε
ê7af║█¡├

```

Hexdump:

```
600a
21510a
216a010a
21595f6a0a
51b078f3aa0a
275958aa41b60a
80f98971ec80ee0a
88376166badbadc3

```

A `fastcall` function which receives the pointer to output buffer in `ecx`. It fills the buffer with a triangle containing the letter `x`:

```
x
xx
xxx
xxxx
xxxxx
xxxxxx
xxxxxxx
xxxxxxxx

```

Disassembly:

```
10013FF0 60                   pushad
10013FF1 0A 21                or          ah,byte ptr [ecx]
10013FF3 51                   push        ecx
10013FF4 0A 21                or          ah,byte ptr [ecx]
10013FF6 6A 01                push        1
10013FF8 0A 21                or          ah,byte ptr [ecx]
10013FFA 59                   pop         ecx
10013FFB 5F                   pop         edi
10013FFC 6A 0A                push        0Ah
10013FFE 51                   push        ecx
10013FFF B0 78                mov         al,78h
10014001 F3 AA                rep stos    byte ptr es:[edi]
10014003 0A 27                or          ah,byte ptr [edi]
10014005 59                   pop         ecx
10014006 58                   pop         eax
10014007 AA                   stos        byte ptr es:[edi]
10014008 41                   inc         ecx
10014009 B6 0A                mov         dh,0Ah
1001400B 80 F9 89             cmp         cl,89h
1001400E 71 EC                jno         again (10013FFCh)
10014010 80 EE 0A             sub         dh,0Ah
10014013 88 37                mov         byte ptr [edi],dh
10014015 61                   popad
10014016 66 BA DB AD          mov         dx,0ADDBh
1001401A C3                   ret

```

I used various instructions to insert a new-line byte `0A` into the machine code:

```
10013FF1 0A 21                or          ah,byte ptr [ecx]
10014009 B6 0A                mov         dh,0Ah
10014010 80 EE 0A             sub         dh,0Ah

```

At the end of the program, I needed to pad it with 4 bytes. I used a harmless `MOV` command instead of 4 `NOP`s so I could have hexadecimal `BADBAD` in code.
> 2 votes

# Answer
# Perl 5, 53 bytes

A triangular quine.

```
$
_=
q{$
_='$
_='."
q{$_}"
.";eva"
.l;print
###};eval

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 1 byte

Any one of `0123456789@NQXY_adg‹›¾ÊËåð` will work. They will output one of `0123456789101120000000011`  respectively.
> 2 votes

# Answer
# PowerShell Core, ~~103~~ ~~53~~ 34 bytes

```
#
##
$n`
=1;`
$n..`
7|%{(`
$n*=9)}

```

A Powershell port of the R solution by *Robin Ryder*, thanks!

Try it online!

Previous attempt 2

Previous attempt 1
> 2 votes

# Answer
# BRASCA, 1 byte

Yep, it's another one of these.

Pick any one of these:

```
0123456789oOnNlLeEdDhHK+-*^s}r&|_ABmM?!ST<>=Y

```

## Explanation

**TL;DR:** Most instructions work because an empty stack consists of infinite zeroes.

```
0-9       - Pushes the digit, implicit output.
oOnN      - Prints the top/bottom of the stack, which is 0x00 because the stack is empty.
lLeEdDhHK - Pushes 10, 13, 26, 32, 48, 65, 97, 100 and 1000 respectively, implicit output.
+-*^s}    - Operate on zeroes because of an empty stack. (ex. + on an empty stack is 0+0).
r         - Pushes a range between 0 and 0, which is just a single 0.
&|_       - Bitwise operators on zeroes because, once again, of an empty stack.
AB        - Registers are 0 by default.
mM        - Shifting an empty stack pushes a 0.
?         - Pushes a random number between 0 and 0.
!         - Pushes the stack length, which is 0.
S         - Concatenates 0 with 0, creating 0.
T         - Sets implicit output to only output the top of the stack, which is empty, so it's a 0.
<>=Y      - Compares 0 with 0 in a bunch of ways.

```
> 2 votes

# Answer
# Charcoal, 13 bytes

```
Ｆ
Ｅ⁺
.¦.
×⊕λ.

```

Try it online! Explanation: In Charcoal, newlines, which I will represent below with ¶, are simply parts of string literals.

```
Ｆ¶

```

Loop over the characters in the string literal .

```
Ｅ⁺¶.¦.¶

```

Concatenate the string literals `¶.` and , loop over the characters, and print each result on its own line.

```
×⊕λ.

```

Repeat `.` by one more than the character index (0-indexed).
> 1 votes

# Answer
# Keg, 1 byte

```
t

```

Try it online!

Sorry, it's a simple literal answer. But then again, all answers in Keg are going to be simple literal answers. Works because characters auto-push and auto-print.

Here's a script that will generate a triangular source code for any given `n`.
> 1 votes

# Answer
# Red, 53 bytes

```
;
t:
"*"
loop
( 9)[
print(
(( t)))
insert((
t))1 + 7]

```

Try it online!

# Red, ~~76~~ 64 bytes

```
;
s:
{t:
 "*"
 loop
(10)[p
rint(t)
insert(t
)"*"]}do
trim/all s

```

Try it online!
> 1 votes

# Answer
# Python 3, ~~64~~ 53 bytes

```
#
##
###
for\
i in\
range\
(1, 9):
 print(\
'.' *i )#

```

Try it online!

Removed a line by pushing two lines into one last one, saved 11 bytes
> 1 votes

# Answer
# Zsh, 34 bytes

```
:
r\
ep\
eat\
 7 {:
s+=A;:
<<<$s;}

```

Try it online!

After re-joining lines:

```
:           # ':' is a no-op, just to fill space more visibly than ' '
repeat 7 {
    :
    s+=A
    :
    <<< $s
}

```
> 1 votes

# Answer
# PowerShell, 1 byte

```
0

```

Try it online -\>
Very similar to other answers, shocked that no one posted this before.
> 1 votes

# Answer
# MAWP 0.1, 1 byte

```
:

```

Outputs top of stack, which is predefined as 1
> 1 votes

# Answer
# Google Sheets, 134

15 lines

```
=
T(
(--
CODE
("owo
(^_^;)
orz")))
&RIGHT(,
)&LEFT(,)
&MID(,1,)&
IF(LN(2),)&
ARRAYFORMULA
(JOIN(CHAR(10
),,REPT(0,ROW(
OFFSET(A1,,,15)

```

### How It Works

Stall until we have a long enough line for `ARRAYFORMULA`, then catch up by generating 15 rows of an increasing number of 0's using `REPT()` and `ROW(OFFSET())` and joining them together with `JOIN()`. Google Sheets will auto-close the missing parens.

### Notes

* Hey, look! No duplicate literals, no duplicate function calls, and no spaces. I could have strung together a bunch of `""&`s, but that would be less entertaining.
* The bottleneck here is `ArrayFormula`, so unless there's a way around that, I think we're stuck.
> 1 votes

# Answer
# Excel Online, 53

9 lines

```
=
T(
12*
34)&
REPT(
0,ROW(
OFFSET(
A1,,,9))
)&TEXT(,)

```

### How It Works

Kind of like my Google Sheets answer, but the bottleneck is the `REPT()` instead.

Sadly, I cannot break the function name from the open paren. Also, Excel Online does not auto-close, so we're stuck with an extra line. However, some nice things that did help were that Excel Online detects Array Formulas automatically, and it displays Array elements as separate rows, so I get a free line break.
> 1 votes

# Answer
# Java 8, 208 bytes

```
;
/*
who
they
are*/
public
class//
Main{//h
public //
static//14
void main//
(String[]ar)
{for(int i=0;
i<19;i++){for(
int j=0;j<i+1;j
++)  System.out.
//crucial comment
print('*');System.
out.println();}}}//

```

Try it online!

A triangular full program.
> 1 votes

# Answer
# Excel, 26 bytes

```
=
7^
(((
ROW(
1:6))
 ))&""

```

Spreadsheet

Below is 17 bytes but Excel removes the line feeds in the array after I hit enter and the output is right justified.

```
=
3^
{2;
4;6;
8;10}

```
> 1 votes

# Answer
# batch ~~63~~ 23 bytes

```
:
T^
YP^
E==^
;%~f0

```

Outputs the file content.

**Note:**

* TIO not available, run it from the command line after turning `echo off`
> 1 votes

# Answer
# Vyxal, 1 byte

```
0

```

Try it Online!

Any digit works.

More interestingly,

# Vyxal `j`, 4 bytes

```
2
ʁ↵

```

Try it Online!

```
2   # 2
 ʁ  # Range 0-1
  ↵ # 10 ** n (vectorised)
    # (j flag) joined by newlines

```

Using powers of 10.

And finally,

# Vyxal, 8 bytes

```
3
ɾ×
*⁋,

```

Try it Online!

```
3      # 3
 ɾ     # 1...3
  ×*   # That many asterisks, for each
    ⁋  # Joined by newlines
     , # Outputted.

```

Making an asterisk triangle.
> 1 votes

# Answer
# Japt, 1 byte

```
Q

```

Try it out here
> 0 votes

# Answer
# Pyth, 1 byte

```
Z

```

Try it online!

In Pyth, `Z` is initialized to 0. Output is implicit so 0 will be printed

---

### 4 bytes

```
Z
T;

```

Try it online!

`T` is initialized to 10 and implicitly printed. `;` is a no-op in this context.
> 0 votes

# Answer
# Retina, 1 byte

```
`

```

Try it online!

The backtick sets the configuration, which in this case is empty. By default, Retina outputs the number of matches of the regex on the input. In this case that regex is the empty string, so the output is `1`
> 0 votes

# Answer
# 33, 1 byte

```
o

```

Try it online!

`o` prints the value of the accumulator, which defaults to 0.

Bit boring, but what can you do about it.
> 0 votes

# Answer
# Deadfish~, 1 byte

```
o

```

Outputs

```
0

```

This is kind of cheating but I can't think of any other way to do it in Deadfish~.
> 0 votes

---
Tags: code-golf, ascii-art, restricted-source, self-referential
---


title: HappyCube Puzzle Solver

text:
# Question
Title: HappyCube Puzzle Solver
This challenge is inspired by a puzzle I played, consisting of foam pieces like these:

which have to be assembled into 3D cubes, like these:

The puzzle pieces can be viewed as grids of 5 * 5 squares, whose middle 3 * 3 squares are always solid, while the 16 squares on the edges can be solid or empty.

A piece will be described using a string of 16 characters (`0`s and `1`s), representing the configuration of its edges (`0`=empty, `1`=solid), in clockwise order, starting from the top left corner.

For example, the string:

```
0101001000101101

```

represents this piece:

```
 # #
####
 ####
####
# #

```

In order to fit the pieces together to form the cube, every piece can be rotated in any direction. For example, these are the valid rotations of the piece shown above:

```
 # #    # #     #    ## #
 ####  ####    ####   ####
####    ####  ####   ####
 ####  ####    ####   ####
  # #  # #    ## #     #

# #      # #   # ##    #
####    ####  ####   ####
 ####  ####    ####   ####
####    ####  ####   ####
 # #    # #     #     # ##

```

## Challenge

Write a program or function that takes as input 6 puzzle pieces and prints or returns a 2D representation of the solved cube.

### Input

The input will be a string of 6 rows, where each row consists of 16 `0` or `1` characters, representing a piece's edges (in the format described above).

It can be assumed that there is a solution for the input.

The trailing newline is optional.

### Output

The result will be an ASCII representation of the solved cube, unfolded in 2D, like this (the diagram uses Rubik's Cube notation for side names):

```
    +---+
    |BA |
    |CK |
    |   |
+---+---+---+---+
|LE |DO |RI |UP |
|FT |WN |GHT|   |
|   |   |   |   |
+---+---+---+---+
    |FR |
    |ONT|
    |   |
    +---+

```

To avoid the possibility of presenting the solution in multiple ways, the piece placed DOWN will always be the first piece present in the input, in the same rotation as it is specified there.

Every piece will be represented graphically as a 5 * 5 matrix, using spaces to denote empty squares. For solid squares you can use whatever non-space character you wish, as long as:

* any piece of the puzzle will have its solid squares represented using the same character
* any two adjacent pieces use different characters

Space padding to the right and the trailing newline are optional.

### Test Cases

1.

Input:

```
0010010101010101
0010001011011010
0101001001010010
0010110100101101
0010110110101101
0010001011010101

```

Output:

```
     @ @
     @@@
    @@@@@
     @@@
** **@#@** *# #
 ***#####***#####
*****###*****###
 ***#####***#####
  * @#@#** ** # #
    @@@@
     @@@@
    @@@@
     @ @

```

2.

Input:

```
0001110110101101
1010010111011101
0101010101010010
1010001000100011
1010001001010001
0110010100100010

```

Output:

```
      @
     @@@@
    @@@@
     @@@@
** **@@## * *# #
****#####****###
 ****###*****####
****#####***####
** *#@#@# * # #
     @@@@
    @@@@
     @@@@
     @ @

```

3.

Input:

```
0101001011011010
0010001000100010
0101001011010010
0101010101011010
0101101001011101
1010001001011101

```

Output:

```
     @ @@
    @@@@@
     @@@
    @@@@@
* * @#@#* *   #
*****###*****###
 ***#####***#####
*****###*****###
  * ##@##* *  #
    @@@@
     @@@@
    @@@@
    @@ @@

```

This is codegolf, so the shortest program in bytes wins.

# Answer
> 6 votes
# Haskell, ~~1007~~ ~~One Thousand and One Bytes~~ ~~923~~ ~~900~~ 830 bytes

I happened to have already made a happycube solver, now I just need to golf it. Taking a ten byte penalty for using fancy block elements:

```
import Data.List
r=reverse;z=zipWith;f=foldl1;t=take;g=t 4;d=drop;m=map
n x=t 5x:n(d 4x)
u v a b=init a++v max(last a)(b!!0):d 1b
a!b|k<- \x y->last$' ':[a|b!!x!!y>0]=(k 0<$>[0..4]):((\i->k 3(4-i):[a,a,a]++[k 1i])<$>[1..3])++[k 2<$>[4,3..0]]
p y|(e:v)<-m(g.n.cycle.m(read.pure))$"0":(lines$y),[j,k,l,x,y,r]<-x v=mapM putStrLn$f(u z)$f(z(u id))<$>z(z(!))[a,"▒█▒█",a][[e,k,e,e],[l,j,x,r],[e,y,e,e]];a=" ░  "
x(p:q)=[p:u|x<-permutations q,u@[e,g,y,k,l]<-sequence$(\c->nub$[c,r.m r$c]>>=g.m g.tails.cycle)<$>x,and$zipWith4(\a n b m->all(==1).init.d 1$z(+)(a!!n)$r$b!!m)([l,e,p,p,p,p,e]++u)[3,3,0,3,1,2,0,1,2,2,2,1](y:g:u++[y,k,k,l,g])[1,0,2,1,3,0,0,0,3,1,2,3]++z((((==1).sum.m(!!0)).).z(!!))[[p,e,g],[y,p,e],[k,p,g],[k,p,y],[l,y,e],[l,y,k],[l,g,e],[l,g,k]][[0,3,1],[0..2],[0,3,2],[1..3],[0,1,1],[3,2,2],[1,0,0],[2,3,3]]]!!0

```

That's a mouthful. Usage:

```
*Main> mapM_ (\s->p s>>putStrLn"")["0010010101010101\n0010001011011010\n0101001001010010\n0010110100101101\n0010110110101101\n0010001011010101","0001110110101101\n1010010111011101\n0101010101010010\n1010001000100011\n1010001001010001\n0110010100100010","0101001011011010\n0010001000100010\n0101001011010010\n0101010101011010\n0101101001011101\n1010001001011101"]
     ░ ░
     ░░░
    ░░░░░
     ░░░
▒▒ ▒▒░█░▒▒ ▒█ █
 ▒▒▒█████▒▒▒█████
▒▒▒▒▒███▒▒▒▒▒███
 ▒▒▒█████▒▒▒█████
  ▒ ░█░█▒▒ ▒▒ █ █
    ░░░░
     ░░░░
    ░░░░
     ░ ░

      ░
     ░░░░
    ░░░░
     ░░░░
▒▒ ▒▒░░██ ▒ ▒█ █
▒▒▒▒█████▒▒▒▒███
 ▒▒▒▒███▒▒▒▒▒████
▒▒▒▒█████▒▒▒████
▒▒ ▒█░█░█ ▒ █ █
     ░░░░
    ░░░░
     ░░░░
     ░ ░

    ░░ ░
    ░░░░░
     ░░░
    ░░░░░
  ▒ ▒█░█░ ▒ ▒ █
▒▒▒▒▒███▒▒▒▒▒███
 ▒▒▒█████▒▒▒█████
▒▒▒▒▒███▒▒▒▒▒███
 ▒ ▒██░██ ▒   █
     ░░░░
    ░░░░
     ░░░░
    ░░ ░░

```

Some of the examples have more than one solutions, that's why some of the outputs look different. Ungolfed:

```
import Data.List (nub, transpose, (\\))
import Control.Monad (guard)

newtype CubePiece = CubePiece [[Int]] deriving Eq
newtype Solution = Solution [CubePiece]

side :: Int -> CubePiece -> [Int]
side n (CubePiece c) = c!!n

corner :: Int -> CubePiece -> Int
corner n (CubePiece c) = head $ c!!n

strToCube str = CubePiece $ hs' . (\x@(a:_)->x++[a]) $ l
  where
    l = map (read.pure) str
    hs' [a] = []
    hs' x = take 5 x : hs' (drop 4 x)

orientations :: CubePiece -> [CubePiece]
orientations (CubePiece cube) = map CubePiece $ nub $ (take 4 . iterate rotate $ cube) ++
  (take 4 . iterate rotate . reverse . map reverse $ cube)
  where
  rotate (a:as) = as++[a]

sideFits ::  (CubePiece, Int) -> (CubePiece, Int) -> Bool
sideFits (c1,n1) (c2,n2) = case (zipWith (+) a b) of
  [_,1,1,1,_] -> True
  _ -> False
  where
  a = side n1 c1
  b = reverse $ side n2 c2

cornerFits :: (CubePiece, Int) -> (CubePiece, Int) -> (CubePiece, Int) -> Bool
cornerFits (c1,n1) (c2,n2) (c3,n3) = a + b + c == 1
  where
  a = corner n1 c1
  b = corner n2 c2
  c = corner n3 c3

printSolution str = putStrLn . specialUnlines . map rivi $
  [[empty,gshow '░' c2,empty,empty],[gshow '▒' c3,gshow '█'c1,gshow '▒'c4,gshow '█'c6],[empty,gshow '░'c5,empty,empty]]
  where
  Solution [c1,c2,c3,c4,c5,c6] = solve . map strToCube . lines $ str
  empty = replicate 5 "     "
  rivi = map (foldl1 specialConcat) . transpose
  specialUnlines = unlines . foldl1(\a b->init a++[zipWith max(last a)(head b)]++tail b)
  specialConcat a b
    | last a==' '=init a++b
    | otherwise = a++tail b

gshow char (CubePiece c) =
  [ map (k 0) [0..4]
  , (k 3 3) : m ++ [(k 1 1)]
  , (k 3 2) : m ++ [(k 1 2)]
  , (k 3 1) : m ++ [(k 1 3)]
  , map (k 2)[4,3..0]
  ]
  where
  k n1 n2 = if (c!!n1)!!n2 == 1 then char else ' '
  m=replicate 3 char

solve :: [CubePiece] -> Solution
solve pieces = Solution $ head $ do
  let c1' = pieces!!0
  let c1 = c1'

  c2'  <- pieces \\ [c1']
  c2   <- orientations c2'
  guard $ sideFits (c1,0) (c2,2)

  c3'  <- pieces \\ [c1',c2']
  c3   <- orientations c3'
  guard $ sideFits (c1,3) (c3,1)
  guard $ sideFits (c2,3) (c3,0)
  guard $ cornerFits (c1,0) (c2,3) (c3,1)

  c4'  <- pieces \\ [c1',c2',c3']
  c4   <- orientations c4'
  guard $ sideFits (c1,1) (c4,3)
  guard $ sideFits (c2,1) (c4,0)
  guard $ cornerFits (c1,1) (c2,2) (c4,0)
  c5' <- pieces \\ [c1',c2',c3',c4']
  c5 <- orientations c5'
  guard $ sideFits (c1,2) (c5,0)
  guard $ sideFits (c4,2) (c5,1)
  guard $ sideFits (c3,2) (c5,3)
  guard $ cornerFits (c5,0) (c1,3) (c3,2)
  guard $ cornerFits (c5,1) (c1,2) (c4,3)

  c6' <- pieces \\ [c1',c2',c3',c4',c5']
  c6 <- orientations c6'
  guard $ sideFits (c6,0) (c2,0)
  guard $ sideFits (c6,1) (c3,3)
  guard $ sideFits (c6,2) (c5,2)
  guard $ sideFits (c6,3) (c4,1)
  guard $ cornerFits (c6,0) (c4,1) (c2,1)
  guard $ cornerFits (c6,3) (c4,2) (c5,2)
  guard $ cornerFits (c6,1) (c3,0) (c2,0)
  guard $ cornerFits (c6,2) (c3,3) (c5,3)
  return $ [c1,c2,c3,c4,c5,c6]

main = mapM_ printSolution ["0010010101010101\n0010001011011010\n0101001001010010\n0010110100101101\n0010110110101101\n0010001011010101","0001110110101101\n1010010111011101\n0101010101010010\n1010001000100011\n1010001001010001\n0110010100100010","0101001011011010\n0010001000100010\n0101001011010010\n0101010101011010\n0101101001011101\n1010001001011101"]

```

# Answer
> 1 votes
# Python3, 1098 bytes:

```
E=enumerate
H=range
R=lambda x,n=4:set()if n==0 else{str(x),*R([i[::-1]for i in zip(*x)],n-1)}
def B(i):k=[[[' ','#'][int(j)]for j in i[t:t+4]]for t in H(0,16,4)];return[k[0]+[k[1][0]],*[[a,*('#'*3),b]for a,b in zip(k[3][::-1][:-1],k[1][1:])],[k[3][::-1][-1]]+k[2][::-1]]
V=lambda U,x,y,r,i,R,I:all((0<I<4 and A!=B)or(I in[0,4]and(A!=B or(A==' 'and B==' ')))for I,(A,B)in E(zip([U[x],[*zip(*U[x])]][r][i],[U[y],[*zip(*U[y])]][R][I])))
def L(M):
 b=[[' 'for _ in H(17)]for _ in H(13)]
 for P,(x,y),C in zip(M,[(4,4),(4,0),(0,4),(4,8),(8,4),(4,12)],'#@*&$%'):
  for X in H(5):
   for Y in H(5):b[x+X][y+Y]=[C,b[x+X][y+Y]][P[X][Y]==' ']
 return b
def f(p):
 s,*p=[B(i)for i in p.split('\n')]
 q=[([s],p)]
 while q:
  M,p=q.pop(0)
  if len(M)==6:
   for i in M:return L(M)
  for i,a in E(p):
   for P in{*R(a),*R([j[::-1]for j in a])}:
    U=M+[eval(P)]
    if all(V(U,*j)for j in[(1,0,1,4,1,0),(2,0,0,4,0,0),(3,0,1,0,1,4),(4,0,0,0,0,4),(5,3,1,0,1,4),(1,2,0,0,1,0),(2,3,1,4,0,0),(3,4,0,4,1,4),(1,4,0,4,1,0),(1,5,1,0,1,4),(2,5,0,0,0,0),(4,5,0,4,0,4)]if j[0]<len(U)and j[1]<len(U)):q+=[(U,p[:i]+p[i+1:])]

```

Try it online!

---
Tags: code-golf, ascii-art
---


# Question
Title: Help me golf this C program checking for string patterns in a sorted hand of cards
I could not think of a better title.

**This is a tips question. I'm asking for tips on golfing my code.**

I recently took part in a code golf competition in C. The competition ended and I lost. The problem is:

> Input a line with a number *n*.
>
> Then input *n* lines, each line contains only a set of cards in descending order, e. g. `X2AAKKKKQT9765433` or `DX22AKKQJTT884443`. Figure out if it contains `DX` **or** four of the same cards in a row.

Obviously, this is a chameleon challenge (finding `DX` is essentially the same as checking the second character if it is `X`, and to check for four of the same cards you only need to check the first and the last card of the quadruplet, because the cards are in descending order.)

In that competition, the input format is strict, and error-terminating is disallowed.

After the competition, we continued to improve on this problem. We've got this so far (98 bytes):

```
char*p,s[99];main(){for(gets(s);gets(p=s);puts(s[1]>87?"Yes":"No"))for(;*p;)s[1]|=*p^p++[3]?0:88;}

```

I'm looking for tips to golf this down further.

# Answer
> 7 votes
**94 bytes**

Instead of increasing `s[1]` when you find a quadruplet, setting it to zero is a bit cheaper. The conditional in `puts` stays the same length:

```
char*p,s[99];main(){for(gets(s);gets(p=s);puts(s[1]%88?"No":"Yes"))for(;*p;)s[1]*=*p!=p++[3];}

```

Try it online!

dingledooper suggested two more improvements:

**93 bytes**

If we can avoid to produce in the first iteration, The initial call to `gets` can be dropped. This is achieved by assuming the first argument to `main` (argc) is 1, which is the case if there are no command line arguments.

```
char*p,s[99];main(i){for(;gets(p=s);--i&&puts(s[1]%88?"No":"Yes"))for(;*p;)s[1]*=*p!=p++[3];}

```

Try it online!

**87 bytes**

If you stop the inner for loop as soon a quadruplet is found or the end of input is reached, `*p>0` indicates a quadruplet:

```
char*p,s[99];main(i){for(;gets(p=s);--i&&puts(s[1]>87|*p?"Yes":"No"))for(;*p++-p[2];);}

```

Try it online!

---
Tags: code-golf, tips, c
---


title: Two In One: Guess That Language - Cops

text:
# Question
Title: Two In One: Guess That Language - Cops
Robber's challenge

This challenge challenges the Cop to write a non-empty program that, when run, produces some non-empty output in language A, and, when reversed, produces some non-empty output in language B. The program may produce any output to STDERR when run in either language, but may not take input in any way.

The cop should provide the following information:

* The forwards program
* The output when run in language A
* The output when run backwards in language B

Robbers should attempt to find the two languages used

### Rules

* The criteria for a valid programming language are the same as those of The Programming Language Quiz, Mark II - Cops:

>
* Each answer must run in less than a minute on a reasonable PC.
* Different versions of a language count as the same language.
* Languages with different flags are valid. However, flags must be revealed to avoid obscure combinations.
* Cracking a submission consists of finding *any* pair of programming languages that work, not just the intended ones.

An answer is safe if it is not cracked until two months after the question is posted.

An answer can not compete one month after this challenge has been posted.

The shortest safe answer by byte count wins.

## Example cop post

# ??? and ???, 128 bytes

```
print(1)#.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
```

Language A expected output: `1`
Language B expected output: `v`

and, when cracked,

# Python 3 and brainfuck, 128 bytes, cracked by [<user>](<link to robbers post>)

```
print(1)#.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
```

Language A expected output: `1`
Language B expected output: `v`

<explanation>

# Answer
# Japt and Seriously, 5 Bytes - Cracked by math junkie.

```
STINK

```

Language A expected output: the current date and time on the machine, in its locale formatted like so `Sun Jun 05 2022 18:41:48 GMT+0100 (British Summer Time)`.

> this is just the trailing K getting a JavaScript `date()`

Language B expected output of `KNITS`:

```

                                                                                ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,......................................................................................................................................................................................................[encoded data, 8781 characters]

```

..that is, in order:

\\$298\\$ newline characters
\\$2278\\$ space characters
\\$198\\$ `,`s
\\$198\\$ `.`s
\\$27\\$ `0`s
\\$60\\$ `1`s
\\$60\\$ `2`s
\\$60\\$ `3`s
\\$60\\$ `4`s
\\$60\\$ `5`s
\\$60\\$ `6`s
\\$60\\$ `7`s
\\$60\\$ `8`s
\\$60\\$ `9`s
\\$1\\$ `G`
\\$98\\$ `T`s
\\$591\\$ `a`s
\\$595\\$ `b`s
\\$295\\$ `d`s
\\$1289\\$ `e`s
\\$297\\$ `f`s
\\$199\\$ `h`s
\\$98\\$ `i`s
\\$98\\$ `k`s
\\$693\\$ `l`s
\\$2\\$ `m`s
\\$591\\$ `n`s
\\$1091\\$ `o`s
\\$98\\$ `p`s
\\$397\\$ `r`s
\\$492\\$ `s`s
\\$893\\$ `t`s
\\$99\\$ `u`s
\\$296\\$ `w`s
\\$1\\$ `y`
\\$1\\$ newline character.

> The `N` gets us the text of "99 Bottles of Beer", `S` then sorts the characters.
> 8 votes

# Answer
# Gol\>\<\> and ;#+, 12 bytes, cracked by MathJunkie

```
push 72;ll-l

```

Language A expected output: `16`

Language B expected output: `-1`

You got half the intended language pair right. But not the other half.
> 7 votes

# Answer
# 05AB1E and Noether, 5 bytes, cracked by Jonathan Allan

```
PLACO

```

Language A (forwards): `2483027905`

Language B (backwards): `26`
> 5 votes

# Answer
## Befunge-96 and befunge-97, 8 bytes, Cracked by steffan

```
_2h2,@#>

```

Outputs `4` going forwards and `0x00 0x02` bytes going backwards.

Well, that lasted all of five minutes :P
> 4 votes

# Answer
# Burlesque and Marbelous, 11 bytes, Safe

```
23 45 67 ++

```

Forward:

```
4567
23

```

Note: It outputs exactly this in the official online interpreter. But it also outputs a few more trailing characters in other interpreters, presumably because of different command line arguments for the different ways handling standard input, which is not supported in the official online interpreter. But I think I don't need to reveal the flags, because this is the only way running the official online interpreter, which is linked from the official website linked from the Esolangs page.

Backward:

```
vT2

```

Should be easy because it's obvious how it works in both languages.
> 4 votes

# Answer
# StupidStackLanguage and Deadfish~, 12 bytes, cracked by math junkie

```
ioaddrsirmix

```

Language A (forwards): `-1`

Language B (backwards): `2`
> 3 votes

# Answer
# Pyth and Pip, 6 bytes, cracked by whqwert

```
h+hTCG

```

Language A expected output: `156490583352162063278528710879425690470022892627113539022649734`
Language B expected output: `98.29704308057353`
> 3 votes

# Answer
# BRASCA and Foo (or others), 2 bytes, cracked by jimmy23013

```
`"

```

Language A expected output: `"`
Language B expected output: ```

They both start a string with the first character and implicitly end it (no ending string character), and therefore the other character is printed.
> 3 votes

# Answer
# Perl 6 and x86-16 (MS-DOS COM), 41 bytes, Safe

```
say q@if-X	~h	$hL~hCF)o,AF)XD`hBZQ]P ,XQ@
```

The forward program prints:

```
if-X	~h	$hL~hCF)o,AF)XD`hBZQ]P ,XQ

```

Note the trailing newline.

The reverse program prints:

```
@QX, P]QZBh`DX)FA,o)FCh~Lh@QX, P]QZBh`DX)FA,o)FCh~Lh

```

One of these languages should be much easier than the other.

The forward program is fairly straightforward. `say` prints a string followed by a newline, and `q` is an operator that treats the next character as though it were a quote mark.

The reverse program is an x86-16 MS-DOS COM executable. MS-DOS programs are always loaded at 0x100, and if you disassemble it assuming that, you get the following:

```
0x100:  40          inc  ax
0x101:  51          push cx
0x102:  58          pop  ax
0x103:  2C 20       sub  al, 0x20
0x105:  50          push ax
0x106:  5D          pop  bp
0x107:  51          push cx
0x108:  5A          pop  dx
0x109:  42          inc  dx
0x10a:  68 60 44    push 0x4460
0x10d:  58          pop  ax
0x10e:  29 46 41    sub  word ptr [bp + 0x41], ax
0x111:  2C 6F       sub  al, 0x6f
0x113:  29 46 43    sub  word ptr [bp + 0x43], ax
0x116:  68 7E 4C    push 0x4c7e
0x119:  68 24 09    push 0x924
0x11c:  68 7E 09    push 0x97e
0x11f:  58          pop  ax
0x120:  2D 66 69    sub  ax, 0x6966
0x123:  40          inc  ax
0x124:  71 20       jno  0x146
0x126:  79 61       jns  0x189

```

This looks like nonsense! How could it possibly output anything? I wrote the program using only printable characters, which leaves only a handful of instructions available, many of them not useful. In particular, it leaves no instructions that actually output anything. Loops aren't possible either, because loops are just jumps with negative offsets, and no negative numbers can be made from printable characters.

To get around this, the program is self-modifying: the instructions at 0x10e and 0x113 modify the instructions at 0x120 and 0x122 by subtracting off a constant. After these instructions, the modified program disassembles to:

```
0x100:  40          inc  ax
0x101:  51          push cx
0x102:  58          pop  ax
0x103:  2C 20       sub  al, 0x20
0x105:  50          push ax
0x106:  5D          pop  bp
0x107:  51          push cx
0x108:  5A          pop  dx
0x109:  42          inc  dx
0x10a:  68 60 44    push 0x4460
0x10d:  58          pop  ax
0x10e:  29 46 41    sub  word ptr [bp + 0x41], ax
0x111:  2C 6F       sub  al, 0x6f
0x113:  29 46 43    sub  word ptr [bp + 0x43], ax
0x116:  68 7E 4C    push 0x4c7e
0x119:  68 24 09    push 0x924
0x11c:  68 7E 09    push 0x97e
0x11f:  58          pop  ax
0x120:  CD 21       int  0x21
0x122:  78 FB       js   0x11f
0x124:  71 20       jno  0x146
0x126:  79 61       jns  0x189

```

The first ten bytes are setting up the registers to their needed values. `cx` is initially `0x00ff` on most versions of MS DOS (including DOSBox, the free interpreter I tested it on), which is used to set `bp` to `0x00df` for addressing purporses. `dx` is set to `0x100`, the start of the string to be output later.

The next twelve bytes modify the loop as described above, using the `sub r/m16,r16` form of subtraction. The value of `bp` is critical to address the memory in the program without using unprintable characters.

The next nine bytes set up the three interrupts to be called (in reverse order). The upper byte sets the command to be run (output to stdout for 0x09 and exit for 0x4c), the lower byte is not important.

The key here is the loop `pop ax, int 0x21, js 0x11f`, which pops a value of the stack and then makes a `0x21` interrupt. Specifically, it makes the `ah=0x09` interrupt (print a `$`-terminated string starting at `dx` to stdout) twice and then the `ah=0x4c` interrupt (exit program).

Finally, the last 5 bytes `q yas` are never reached and only matter for the forward version of the program.

I tested this program with DOSBox: simply copy the program as an executable (`.COM`) file into a DOSBox folder and run it. Be careful to preserve the horizontal tab.
> 3 votes

# Answer
# ??? and ???, 209 bytes

```
+++++++++++++++++.++
++++++++++++++++++++
++++++++++++++++++++
++++++++++++++++++++
++++++++++++++++++++
++++++++++++++++++++
++++++++++++++++++++
++++++++++++++++++++
++++++++++++++++++++
:+++++++++++++++++++

```

Forward: 9

Backward: \[
> 2 votes

# Answer
# MarioLANG and brainfuck, 520 bytes, cracked by jimmy23013

```
...:+
>.>.-
-.---
-.---
-<.--
-->.+
+++-+
<<<.+
->.>+
->.-+
-----
-<.++
+++<+
-.->+
->.++
+++++
+++<-
+.++-
+>.<-
+.---
>.+++
->.<+
-<<<+
-<.>+
->..+
-.+>+
-.>.-
-.---
-.---
-<.--
-->.+
+++<+
-<<.+
->.>+
->.--
----+
-<.++
+++<+
-.->+
->.++
+++++
+++<+
-.+++
->.<+
-.---
>.+++
->.<+
-<<<+
-<.++
>>..+
-.+>+
-.>.-
-.---
-.---
-<.--
-->.+
+++<+
-<<.+
>.>>+
-.---
---<+
-.+++
++<.+
->>.+
+++++
+++++
-<.++
>.<.+
+>.-+
->.--
>]-<+
-<<<+
-<<++
->+++
+++++
>++++
>++++
+++++
+++>+
+++++
+++++
+++>+
+++++
+++++
->[++
+++++
:-++

```

Forwards: `-25`

Backwards:

```
Nobody is Awesome!!!
Nobody is Awesome!!!
Nobody is Awesome!!!

```
> 2 votes

# Answer
# Javascript and Bash, 193 bytes, cracked by Komali

```
(![]+[/“¡Ḟọ@⁼ị»/])[!+[...([])]+!+[]]+(!!!!!!![/“¡Ḟọ@⁼ị»/]+[])[+!+[]]+(![]+[])[!+[/“¡Ḟọ@⁼ị»*/]+!+[]]+(![]+[])[+!![]]//# i /''»ị⁼@ọḞ¡“{/ h {"}"/}{/ c ..]][[+][-_;};5$""3$  o3$''1$e {)(..]][[+][-_

```

Language A expected output: `lala`

Langauge B expected output: `hi`
> 2 votes

# Answer
# TrumpScript and A Pear Tree, 4 bytes, cracked by whqwert

Forwards:

```
+:
:+
0O

```

Backwards:

```
O0
+:
:+

```

Forwards:

```
Parsing error:
What are you doing on line 3?

```

Backwards:

```
a partridge

```

Should be quite easy...
> 1 votes

# Answer
Forwards:

```
"""+!|>1bab@|!+"""1110111p exit;"1" tuO

```

Backwards:

```
Out "1";tixe p1110111"""+!|@bab1>|!+"""

```

Forwards output:

```
1110111

```

Backwards output:

```

1

```

Shouldn't be too bad.
> 1 votes

# Answer
# ??? and ???, 9 bytes

```
ps"x9O@"(

```

Forwards output: `9`

Backwards output: `@O9x`
> 0 votes

---
Tags: code-golf, source-layout, cops-and-robbers, polyglot
---


# Question
Title: Two In One: Guess That Language - Robbers
Cops' challenge

This challenge challenges the Cop to write a non-empty program that, when run, produces some non-empty output in language A, and, when reversed, produces some non-empty output in language B. The program may produce any output to STDERR when run in either language, but may not take input in any way.

The cop should provide the following information:

* The forwards program
* The output when run in language A
* The output when run backwards in language B

Robbers should attempt to find the two languages used

### Rules

* The criteria for a valid programming language are the same as those of The Programming Language Quiz, Mark II - Cops:

>
* Each answer must run in less than a minute on a reasonable PC.
* Different versions of a language count as the same language.
* Flags must be revealed to avoid obscure combinations.
* Cracking a submission consists of finding *any* pair of programming languages that work, not just the intended ones.

An answer is safe if it is not cracked until two months after the question is posted.

An answer can not compete one month after this challenge has been posted.

Most answers cracked wins

## Example robber post:

# Python 3 and brainfuck, 128 bytes, cracks [<user>'s answer](<link to cops post>)

```
print(1)#.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
```

Python's expected output: `1`
brainfuck's expected output: `v`

<explanation of crack>

# Answer
> 5 votes
# Cracks emanresu A

Forwards is in Befunge-96, backwards is Befunge-97.

Try it online!

Try it online!

# Answer
> 3 votes
# Cracks math junkie

Language A: Pyth

Language B: Pip

# Answer
> 3 votes
# Cracks whqwert's answer

```
ioaddrsirmix

```

Language A: StupidStackLanguage

Language B: Deadfish~

# Answer
> 3 votes
# Cracks Oliver F

Probably not intended.

Language A: BRASCA

Language B: Foo

# Answer
> 3 votes
# Cracks whqwert's `PLACO`

Forwards `PLACO`: O5AB1E \- Try it online!

* This is the lowercase alphabet converted from binary when treated as base 62 digits (i.e. \\$36 \times 2^{25} + 37 \times 2^{24} + \cdots + 61 \times 2^{0} = 2483027905\\$).

Backwards `OCALO`: Noether \- Try it online!

* This is the length of the lowercase alphabet, \\$26\\$.

---

Note: Both languages will produce the given outputs with just `PLAC`.

# Answer
> 3 votes
# Cracks Jonathan Allan

```
STINK

```

Language A: Japt

Language B: Seriously

# Answer
> 2 votes
# Cracks Nobody

Language A: TrumpScript (found by searching GitHub)

Language B: A Pear Tree

# Answer
> 1 votes
# Cracks Nobody

Language A: MarioLANG (It outputs `<nul>-25<space>` on TIO.)

Language B: brainfuck

# Answer
> 1 votes
# Cracks lyxal

```
push 72;ll-l

```

**Language A**: Gol\>\<\>

Produces the required output (**16**) with just `sh`. According to the docs, `s` adds 16 to the stack. `h` seems to be necessary to end the program.

**Language B**: ;#+

Produces the required output (**-1**) with just `-;p`.

# Answer
> 1 votes
# Cracks asdf3.14159

Forwards is Javascript, backwards is Bash
There were a lot of red herrings in this that threw me off at first but simplifying parts of it gave it away. Fun!
~~Am I too late to post an answer? :P~~

---
Tags: source-layout, cops-and-robbers, polyglot
---


# Question
Title: Python: can I shorten this code further for checking substrings
So the golf question was like this:

> You are given a number `T` and then a total of `T` number of 17-character strings. For each of the strings, output `yes` if it contains four consecutive identical characters or contains the substring `DX`, else output `no`.

The following constraints are promised for each of the 17-character strings:

1. The possible character set is `DX2AKQJT9876543`;
2. The input string is sorted in the above mentioned order, hence the number of times each character appears is exactly the size of the longest contiguous substring of the character;
3. No characters will appear more than 4 times;
4. `X` and `D` will appear no more than once each.

Test case:

```
3
X2AAKKKKQT9765433
DX22AKKQJTT884443
X2AAAKQQJT8554433

```

should have the output

```
yes
yes
no

```

---

Note:

* Output is not case sensitive, so `YeS` is also legal;
* You may assume an extra `\n` after the end of the input.

---

My attempt goes like this: Python, probably ~~84~~ 85 Bytes

```
import re
input()
while n:=input():print("yes"if re.search(r"(.)\1{3}|DX",n)else"no")

```

Also, I have the following alternatives for line 3, while are approximately the same length:

```
while n:=input():print("yneos"[not re.search(r"(.)\1{3}|DX",n)::2])
while n:=input():print(["yes","no"][not re.search(r"(.)\1{3}|DX",n)])
while n:=input():print((not re.search(r"(.)\1{3}|DX",n))*"no"or"yes")

```

Is there anything I can do to make this shorter? Thanks in advance!

Source: Question made by a friend, problem ID on Luogu is `P8466`

# Answer
# Python, 72 bytes

```
for n in[*open(0)][1:]:print("yneos"[all(map(str.__ne__,' X '+n,n))::2])

```

Try it online!

Knocks 5 more bytes off of Jonathan Allan's answer.
> 5 votes

# Answer
# 82 bytes

Can probably be golfed more, but here is a first golf:

-2 bytes by changing

```
"yes"if re.search(r"(.)\1{3}|DX",n)else"no"

```

To:

```
re.search(r"(.)\1{3}|DX",n)and"yes"or"no"

```

Try it online.

And another -1 by changing (not sure about this one, but both your 85 bytes version and this one gives an EOFError on TIO):

```
input()
while n:=input():...n

```

To:

```
n=input()
while n:...input()

```

Try it online.
> 3 votes

# Answer
# Python 3.8, 77 bytes

```
input()
while n:='X '+input():print("yneos"[all(map(str.__ne__,n,n[3:]))::2])

```

**Try it online!**

The check for four equal characters in a row can be achieved by checking for equality between a character and the character three positions to its right. This can be applied across a string with `any(map(str.__eq__,n,n[3:])` which will yield `True` if so or `False` otherwise.

This is inverted in the code by checking that all such pairs of characters are *not* equal with `all(map(str.__ne__,n,n[3:]))` to allow the result to be used in a slice of `"yneos"` that steps by two characters. That is, `"yneos"[False::2]` is equivalent to `"yneos"[0::2]` which is `"yes"`; while `"yneos"[True::2]` is equivalent to `"yneos"[1::2]` which is `"no"`.

To check for the presence of "DX" we only need to see if the string *starts with* "DX" due to the strict ordering and the rule that states each of "D" and "X" may only appear once. Moreover this means the string cannot have a second character of "X" unless it starts with "DX", so we actually only need to check if the second character is "X". Therefore prefixing the string with "X " allows a reuse of the check for equal characters being three apart for this too, hence `n:='X '+input()`.
> 3 votes

---
Tags: code-golf, string, tips, python, pattern-matching
---


title: Remove redundant parentheses

text:
# Question
Title: Remove redundant parentheses
Given a string containing some parentheses and some other ASCII printable characters, like this: `(abc((123))(k))` your task is to remove any sets of parentheses that are redundant.

A set of parentheses is redundant if:

1. It encloses another set of matching parentheses, like `ab((123))`, or
2. It encloses the entire string, like `(abc123)`

Parentheses are guaranteed to be matched in the input. Also there will never be an empty pair.

## Test cases

```
{
   "(alpha)":              "alpha",
   "(((([))))":            "[",
   " beta(gamma)":         " beta(gamma)",
   "@lpha((lambda))":      "@lpha(lambda)",
   "(phi((theta)pi))":     "phi((theta)pi)",
   "(sigma)(omega)":       "(sigma)(omega)",
   "(sig(ma)(om)e;a)":     "sig(ma)(om)e;a",
   "(((((a)))b))":         "(a)b",
   "((b(((a)))))":         "b(a)",
   "b((a$c)(def))":        "b((a$c)(def))",
   "x(((y)(z)))":          "x((y)(z))",
   "(foo(bar))baz":        "(foo(bar))baz",
   "foo((bar)baz)":        "foo((bar)baz)",
   "(((((a)(b)))c))":      "((a)(b))c",
   "((c(((b)(a)))))":      "c((b)(a))",
   "(((a))b)c":            "((a)b)c",
   "c(b((a)))":            "c(b(a))",
   "((\"))":               "\"",
   "(('))":                "'"
   "XYZ!\"#$%&\'(*)+,-./": "XYZ!\"#$%&\'(*)+,-./",
   ":;<=>?@[\\]^_`{|}~'" : ":;<=>?@[\\]^_`{|}~'",
   "a((foo(bar))baz)z":    "a((foo(bar))baz)z",
   "a(foo((bar)baz))z":    "a(foo((bar)baz))z",
}

```

# Answer
# Regex (Perl / PCRE / Boost / Python`regex`), ~~45~~ ~~44~~ ~~45~~ ~~44~~ 43 bytes

```
s/(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$)/$3/

```

Try it online! \- Perl v5.28.2 / Attempt This Online! \- Perl v5.36+
Try it online! \- PCRE1
Try it online! \- PCRE2 v10.33
Try it online! \- Boost
Try it online! \- Python `import regex`

This is a single regex substitution to be repeatedly applied until it has nothing to match. However in Boost, it is applied until there is no change (since its substitution interface apparently doesn't allow detecting whether any replacements were done).

This golf down from the 45 byte version is similar to Neil's .NET regex, in that it is flanked with `(?<=\(|^)` and `(?=\)|$)` (or equivalent). When initially writing a PCRE regex answer to this challenge, the thought occurred to me to do this, but I dismissed the idea, assuming that empty capture groups would need to be used to XNOR the flanking conditions (i.e. force them to only match if they agree on `^` and `$` or `\(` and `\)`), by doing `(?<=\(()|^)`...`(?=(?(1)\)|$))` or at least `(?<=\(()|^)`...`(?=\1\)|$)`.

Then later on, after Neil posted his answer, I tried porting that approach to mine anyway. I found it to indeed return some incorrect results unless forced to agree using an empty capture group, but at that point I'd already gone with the (as it turned out incorrect) golf of `[^)]` in my regex. As it turns out, with `[^()]`, the flanking approach is fully robust in recursive versions of the regex, without requiring any additional XNORing logic or atomic grouping.

```
s/                 # Begin substitution - match the following:
(\(|^)             # Assert either we're at the start of the string, or there
                   # is a (redundant) left-adjacent opening parenthesis.
\K                 # Keep everything matched up to this point out of the match.
                   # This is a more efficient way of doing the same thing as
                   # lookbehind in many situations.
(                  # Define recursive subroutine (?2)
    \(             # Match an opening parenthesis
    (              # At the outermost level, $3 = the following capture, i.e.
                   # with the parentheses matched outside it discarded.
        (
            (?2)   # Call (?2) recursively
        |          # or
            [^()]  # Match any character other than a parenthesis.
                   # It's not safe to reduce this to "[^)]" because if,
                   # after popping out to the top level and exiting this
                   # loop, the "\)" fails to match because there's more
                   # inside the top-level parentheses pair matched in this
                   # regex, it will backtrack and can incorrectly match an
                   # opening parenthesis here.
        )*         # Iterate the above as many times as possible, min 0
    )
    \)             # Match a closing parenthesis
)
(?=\)|$)           # Assert that either we're at the end of the string, or
                   # there is a redundant right-adjacent closing parenthesis.
/                  # Substitution - replace with the following:
$3
/                  # End substitution - no flags used

```

I also intend to write a single-use `s/`...`//g` substitution that will erase all the parentheses in one go, but that will be significantly more complicated and less efficient (as it will need to emulate variable-length lookbehind to erase the closing parentheses). As such, it would be demonstrable in regex101, which can only apply a substitution once. (I've done this for .NET, but intend to for PCRE2 as well.)

# Regex (PCRE / Ruby), ~~48~~ ~~49~~ ~~45~~ 44 bytes

```
s/(\(|^)\K(\(((\g<2>|[^()])*)\))(?=\)|$)/\3/

```

Try it online! \- PCRE1
Try it online! \- PCRE2
**Try it online! \- Ruby**

As of 45 bytes and smaller, this is an absolutely straight port of the regex above. Previously, it needed to work around the difference in Ruby subroutine capture group behavior.

## \\$\large\textit{Functions}\\$

# Ruby, ~~75~~ ~~76~~ ~~74~~ ~~72~~ ~~71~~ ~~66~~ 62 bytes

*-5 bytes thanks to Steffan*
*-4 bytes thanks to Dingus*

```
->s{0while s[/(\(|^)\K(\(((\g<2>|[^()])*)\))(?=\)|$)/]&&=$3;s}

```

Try it online!

# Julia v1.6.1+, ~~84~~ ~~85~~ ~~84~~ 83 bytes

Attempt This Online! (now the same as below)

# Julia v0.7+, ~~86~~ ~~87~~ ~~84~~ 83 bytes

```
f(s,p=0)=s==p ? s : f(replace(s,r"(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$)"=>s"\3"),s)

```

Try it online!

Julia's implementation of PCRE substitution appears to be deficient, not actually using `pcre2_substitute()` (the giveaway is that `$1` `$2` etc. capture group syntax is not supported). This is a shame, because PCRE2 has some advanced conditional replacement features (enabled by `PCRE2_SUBSTITUTE_EXTENDED` in its C interface). The explanation, though, is that it was originally integrated with PCRE1, which has no built-in substitution API – so presumably when they switched to PCRE2, they kept the substitution code they'd already written for use with PCRE1.

# v4.1.0+, ~~90~~ ~~91~~ ~~89~~ 88 bytes

```
f=\(s,p=0)if(p==s)s else f(sub(r'{(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$)}','\\3',s,,1),s)

```

Attempt This Online!

R is apparently also not using PCRE2's built-in substitution engine, otherwise `$2` would work as the replacement argument.

# Python (with `regex`), ~~123~~ ~~108~~ ~~107~~ ~~106~~ ~~107~~ ~~106~~ 105 bytes

*-15 bytes thanks to Steffan*

```
import regex
f=lambda s,p=0:s==p and s or f(regex.sub('(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$)',r'\3',s),s)

```

Try it online!

For golf reasons, this continues substituting until the string is unchanged, not until there are no matches (with this regex either of those two methods will work).

Alternative 105 bytes, using essentially the same technique as suggested by VisualMelon:

```
import regex
def f(s):
 for i in s:s=regex.sub('(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$)',r'\3',s)
 return s

```

Try it online!

# Python 3.8+ (with `regex`), ~~100~~ ~~101~~ ~~100~~ 99 bytes

```
lambda s:[s:=regex.sub('(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$)',r'\3',s)for i in s][-1]
import regex

```

Can't Try it online! \- Confirmed to work on my machine, but `regex` is not installed on TIO or ATO.

Uses essentially the same technique as suggested by VisualMelon.

# PHP, ~~108~~ ~~109~~ ~~108~~ ~~107~~ ~~106~~ 104 bytes

*-1 bytes (→ 106) thanks to Steffan with the added bonus of now being an anonymous function*
*-2 bytes (→ 104) with no "Undefined variable" warning*

```
function($s){while($p!=$s=preg_replace('/(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$)/','$3',$p=$s));return$s;}

```

Try it online!

## \\$\large\textit{Full programs}\\$

# Perl `-p`, ~~52~~ ~~51~~ ~~50~~ ~~51~~ ~~50~~ 49 bytes

*-1 byte thanks to dingledooper and Sisyphus*

```
1while s;(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$);$3

```

Attempt This Online!

# PHP `-F`, ~~103~~ ~~104~~ ~~103~~ ~~102~~ ~~100~~ 98 bytes

*-2 bytes (→ 100) thanks to Steffan*
*-2 bytes (→ 98) with the added bonus of getting rid of the "Undefined variable" warning*

```
<?for($s=$argn;$p!=$s=preg_replace('/(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$)/','$3',$p=$s););echo$s;

```

Try it online!
> 17 votes

# Answer
# sed 4.2.2, 98 bytes

```
:a
s/(\(([^()]*)\))/\1/
ta
s/\(.\)(\([^()]*\))\(.\)/\1\t\2\n\3/
ta
s/^(\([^()]*\))$/\1/
y/\t\n/()/

```

Try it online!

*-a handful of bytes thanks to Jiří for reminding me to use `y`.*

*+4 bytes thanks to Deadcode for noting that any printable ascii could be in the input string*

## how

```
:a
s/(\(([^()]*)\))/\1/  # remove a layer of any double parens
                      # not enclosing parens
ta                    # loop back to a if we changed anything
s/\(.\)(\([^()]*\))\(.\)/\1\t\2\n\3/
                      # convert (no-parens) to \tno-parens\n
                      # but only if they occur in the middle.
ta                    # loop back to a if we changed anything
s/^(\([^()]*\))$/\1/  # Remove global parens if they
                      # don't enclose any parens
y/<>/()/              # convert all our \t\n back to ()

```
> 8 votes

# Answer
# Jelly,  ~~33 30 29~~  27 bytes

```
Ø(jẹⱮØ(Œ!ż€¥/ṢƑ€ÞṪ_Ø-fƊF’œP

```

A full program that accepts a string and prints the result.

**Try it online!**

### How?

Partitions the input string at its redundant parentheses and prints the characters that remain.

The redundant parentheses are found by first finding the indices of all pairs of matching parentheses in a copy of the input string that has been wrapped in parentheses, and then filtering these to those which are bounded by any other (i.e. rule 1, but removing the inner pair).

For that, the list of indices of all pairs of matching parentheses are effectively found by pairing each closing index with the opening index that is closest to its left that has not been consumed by any previous closing index. This is actually achieved by constructing all lists of pairs of opening and closing indices and finding the one that (a) has no reversed pairs and (b) has the maximal list of opening indices when ordered by their respective closing indices.

```
Ø(jẹⱮØ(Œ!ż€¥/ṢƑ€ÞṪ_Ø-fƊF’œP - Link: list of characters, S
Ø(                          - "()"
  j                         - join with S -> parenthesised S
     Ø(                     - "()"
    Ɱ                       - map with:
   ẹ                        -   all indices -> [open_indices, close_indices]
            /               - reduce this pair of lists by:
           ¥                -   last two links as a dyad - f(open_indices, close_indices):
       Œ!                   -     all permutations of open_indices
         ż€                 -     zip each with close_indixes
                Þ           - sort by:
               €            -  for each pair:
              Ƒ             -    is invariant under?:
             Ṣ              -      sort
                 Ṫ          - tail -> X = list of open indices that pair ascending close indices
                      Ɗ     - last three links as a monad - f(X)
                   Ø-       -   [-1,1]
                  _         -   subtract [-1,1] from each index-pair
                     f      -   X filter keep those
                                    -> redundant parentheses index pairs
                       F    - flatten
                        ’   - decrement (from indices in parenthesised S to indices in S)
                         œP - partition S at those indices, discarding borders
                            - implicit, smashing print

```
> 6 votes

# Answer
# Retina, ~~53~~ ~~52~~ ~~51~~ 55 bytes

*-2 bytes by assuming balanced parentheses in the input*
*+4 bytes to fix a bug*

```
.+
($&)
+`\((\((?>(\(()|[^)]|(?<-3>.))*)\))\)
$1
^.|.$

```

Try it online!

**Step 1:**

```
.+
($&)

```

Surround the string with parentheses (in addition to whatever parentheses it may already have). An alternative way to do this for the same number of bytes would have been:

```
^
(
$
)

```

**Step 2:**

```
+`\((\((?>(\(()|[^)]|(?<-3>.))*)\))\)
$1

```

Remove redundant parentheses, assuming that all parentheses are balanced in the input string.

```
+                    # Loop substitution until its result is equal to the input
`                    # Delimiter between Retina flags and regex
\(                   # Opening parenthesis (redundant one)
(                    # $1 = the following:
    \(               # Opening parenthesis
    (?>              # Atomic group – once the following finishes matching, lock
                     # in the match and prevent backtracking into it.
        (
            \(       # Match an opening parenthesis
            ()       # Push a capture onto the \3 stack
        |       # or
            [^)]     # Match any character other than a closing parenthesis.
        |       # or
            (?<-3>.) # By process of elimination, this character must be a
                     # closing parenthesis, but only allow removing it if it
                     # corresponds to popping a capture from the \3 stack.
        )*           # Iterate the above as many times as possible, minimum zero.
    )
    \)               # Closing parenthesis
)
\)                   # Closing parenthesis (redundant one)
                     # (newline) - delimiter between regex and substitution
$1                   # Replace with $1

```

**Step 3:**

```
^.|.$

```

Remove the pair of parentheses that surround the entire string, which are guaranteed to still be there.

# PowerShell, ~~112~~ ~~101~~ ~~95~~ 99 bytes

*-6 bytes thanks to VisualMelon*

```
[char[]]($p="($args)")|%{$p=$p-replace'\((\((?>(\(()|[^)]|(?<-3>.))*)\))\)','$1'};$p-replace'^.|.$'

```

Try it online!

Uses the same regex and algorithm as my Retina answer, so I figured it'd make sense to group into the same post.

Ungolfed:

```
$p = "($args)"
$c = [char[]]$p  # $c = $p converted to an array of characters
$c | ForEach {   # Iterate the following the same number of times as $c's length
    $p = $p -replace'\((\((?>(\(()|[^)]|(?<-3>.))*)\))\)', '$1'
}
$p -replace '^.|.$', ''

```

# PowerShell, 94 bytes

Using Neil's regex, with a -1 byte golf from me:

```
[char[]]($p="$args")|%{$p=$p-replace'(^|\()\(((?>((\()|[^)]|(?<-4>.))*))\)(?=\)|$)','$1$2'};$p

```

Try it online!
> 6 votes

# Answer
# Python3, 275 bytes:

```
lambda x:P(f(x)[1])
P=lambda x,l=0:[]==x*0and'('*l+''.join(P(i,1)for i in x)+l*')'or x
def f(s):
 r,*t=0,''
 while s:
  h,*R=s
  if'('==h:s,T=f(R);t+=T,''
  elif')'==h:r=1;break
  else:t[-1]+=h;s=R
 return s[r:],(lambda x:len(x)<2and[]==x[0]*0and x[0]or x)([*filter(None,t)])

```

Try it online!
> 4 votes

# Answer
# Retina 0.8.2, ~~53~~ 52 bytes

```
+`(^|\()\(((?>((\()|[^)]|(?<-4>.))*))\)(\)|$)
$1$2$5

```

Try it online! Link includes test cases. Explanation: Works by removing all inner sets of balanced parentheses that are contained by parentheses or match the whole string. Uses the assumption that all parentheses are balanced meaning that the input can't be something like `(@))((@)`. Edit: Saved 1 byte thanks to @Deadcode pointing out that I didn't need to use lookarounds.
> 4 votes

# Answer
# Jelly, ~~31~~ 29 bytes

```
Ø(j
ẆṚẹⱮØ(>/SƊÐḟÇ€¹œṣÇ}jʋƒÇḊṖ

```

Try it online!

If Jelly had a builtin for "is a balanced string", this would have been much shorter. A "replace substring" builtin could also have helped, as would better chaining rules for dyads. (My recommendation for dyad chains is to start with the left argument, then mostly use the monad chaining rules with the right argument, keeping the special case for  but discarding the other dyad chaining rules. That would have saved two bytes in this program, compared to Jelly's current chaining rules, and would also be much more intuitive.) Larger-scale problems like this one can be good at exposing some of Jelly's shortcomings.

Thanks to @Unrelated String for pointing out that I'd missed a builtin – using  rather than implementing it manually saved two bytes.

## Explanation

### Helper function `1Ŀ`

The helper function encloses a string in parentheses, and is called using the shortcut `Ç` (which calls the other function, when only one function is available, thus there's no need to state its name explicitly).

```
Ø(j
Ø(     ["(", ")"]
  j    join this list by {the function argument}

```

### Main program

Outputs a string with redundant parentheses removed.

```
ẆṚẹⱮØ(>/SƊÐḟÇ€¹œṣÇ}jʋƒÇḊṖ

  ẹⱮØ(>/S                      check if a string is unbalanced
   Ɱ                           for each of
    Ø(                           ["(", ")"]
  ẹ                            find the indexes at which it occurs
       /                       compare these two lists with each other
      >                          by greater than of corresponding elements
        S                      sum (i.e. true if there are any nonzeros)
         Ɗ                     parse the entire check as a single group

Ẇ                              find each substring of {the input}
 Ṛ                               ordered from longest to shortest
          Ðḟ                   keep only those that are not
  ẹⱮØ(>/SƊ                       unbalanced
            Ç€                 call `1Ŀ` on each of them
                     ƒ         iterating over this list, using an accumulator
                      Ç          initialised to `1Ŀ` of {the input}
                    ʋ            do all of the following, parsed as a group:
               œṣ                  split {the accumulator} on
                 Ç                   `1Ŀ`
                  }                    of the current list element
                   j               and join on {the current list element}
                                 {to produce the new accumulator}
              ¹                (fix for parser ambiguity)
                       ḊṖ      delete the first and last elements

```

There's an interesting subtlety in the check for unbalanced strings. The main idea is to check the indexes of the opening parentheses and of the close parentheses, and try to find an *n* for which the *n*th opening parenthesis appears after the *n*th closing parenthesis (thus, we're comparing the two lists with an element-wise `>` that compares corresponding elements of the two lists). However, if the number of opening parentheses differs from the number of closing parentheses, the element-wise `>` will be trying to compare two lists of different lengths. In this case, it ends up just outputting the extra elements literally (so, e.g., comparing \[4,3,2\]\>\[1,2,3,4\] outputs \[true, true, false, 4\]). This doesn't make much sense mathematically, but means that (because Jelly uses 1-indexing) the result will contain a truthy element if the two lists are different lengths, so the string will be seen as unbalanced (which is correct – if the number of opening and closing parentheses differ, it can't be balanced). It took me a while to find a check for string balance that could handle both the equal-parenthesis-count and unequal-parenthesis-count cases without needing a separate check, but I'm happy with this one.

Once we have a list of all the balanced strings (say *`x`*), the algorithm is to replace `((*x*))` with `(*x*)`. As long as this is done in order from longest to shortest, all the internal redundant parentheses will be removed.

To remove redundant parentheses around the string as a whole, the idea is to enclose the string in parentheses to start with, and remove them at the end, so that the same redundant parenthesis removal algorithm works to remove both internal and external redundant parentheses. This fits in rather nicely with the `ƒÇ` construction, allowing the loop to start with a parenthesis-enclosed input without requiring any extra plumbing (if attempting to use the input directly rather than a function of it, it might well require spending another byte on parser ambiguity fixes).
> 4 votes

# Answer
# Regex (.NET), 200 bytes

`s/(?<=()^\(*|)(?=\(((\()|[^)]|(?<-3>.))*(?=\)+$()|)(\).*)).(?=\1\4|\(((\()|[^)]|(?<-7>.))*\)\5$)|\)(?=\)*$()|)(?<=(.*\()(?<=^\(+()|)((\))|[^(]|(?<-12>.))*.)(?<=\8\10|^\9\(((\))|[^(]|(?<-14>.))*\).)//g`

Try it on regex101!

This is a single regex substitution, to be applied once. It's one and done, erasing all the required parentheses in a single pass. This is the only kind of substitution that can be easily used on regex101; ones requiring multiple passes need to have their output manually fed back as input each time.

```
    (?<=
        ()             # \1 = set if to the left is a continuous stack of
                       #      opening parentheses
        ^\(*
    |
    )
    (?=
        \(             # Match an opening parenthesis.
        (
            (\()       # Push an opening parenthesis onto the \3 stack.
        |         # or
            [^)]       # Match any character other than a closing parenthesis.
        |         # or
            (?<-3>.)   # Match what must, by process of elimination (with the
                       # assumption that the input is balanced) be a closing
                       # parenthesis, while popping a capture off the \3 stack.
        )*
        (?=
            \)+$
            ()         # \4 = set if to the right is a continuous stack of
                       #      closing parentheses
        |
        )
        (\).*)         # \5 = mark spot by capturing everything to the right
    )
    .
    (?=
        # Assert \1 and \4 are both set
        \1\4
    |          # or
        # Assert that the next deeper set of parentheses is adjacent on both
        # sides to the pair we just processed.

        # First, match balanced parentheses the same way we did above, but one
        # level deeper, starting by asserting that the next opening parenthesis
        # is immediately adjacent.
        \(
        (
            (\()
        |
            [^)]
        |
            (?<-7>.)
        )*
        \)

        # Assert that this brings us exactly to the spot we marked with \5.
        \5$
    )
|
    # Do the same thing as above, but exactly in reverse. Note that lookbehinds
    # are tokenwise evaluated from right to left (bottom to top in this view
    # here). That means alternatives are still evaluated left to right within a
    # group, but the matching of groups/characters/backreferences is done from
    # right to left.
    \)
    (?=
        \)*$
        ()             # \8
    |
    )
    (?<=
        (.*\()         # \9
        (?<=
            ^\(+
            ()         # \10
        |
        )
        (
            (\))       # \12
        |
            [^(]
        |
            (?<-12>.)
        )*
        .
    )
    (?<=
        \8\10
    |
        ^\9
        \(
        (
            (\))       # \14
        |
            [^(]
        |
            (?<-14>.)
        )*
        \)
        .
    )

```
> 4 votes

# Answer
# 05AB1E, ~~50~~ ~~47~~ 46 bytes

```
®1‚„()ISkkƶ0KvyDdi‚ˆ]¯.Æʒ`αP}€¨¯ʒ®Ig‚Q}«˜Ä<õsǝ

```

Try it online or verify all test cases.

**Original (completely different) 50 bytes approach:**

```
ŒʒÁÁ4ôć„()©º{RQiJ®Ã®õ:õQ]vyD¦¨:}Ð'(Å?i¦¨‚¤®Ã®õ:õQè

```

Try it online or verify all test cases.

Both can most likely be golfed quite a bit more, but these kind of challenges aren't really 05AB1E's (nor my..) strong suit, especially with all these edge-cases.

**Explanation 1:**

Step 1: Get a list of all index-pairs for the balanced parenthesis:

```
®1,           # Push pair [-1,1]
   „()        # Push string "()"
      I       # Push the input-string
       Sk     # Get the index 0-based index of each character in string "()",
              # or -1 if it's neither
         k    # Use that to index into the [-1,1] (basically replacing -1s with 0s and
              # vice-versa, without changing the 1s)
          ƶ   # Multiply each value by its 1-based index
           0K # Remove all 0s
v             # Loop over each index:
 y            #  Push the current index to the stack
  Ddi         #  Duplicate it, and if it's a positive index:
     ‚        #   Pair it with the top negative index of the stack
      ˆ       #   Pop and add this pair to the global array
]             # Close the if-statement and loop
 ¯            # Push the global array

```

Try just step 1 online.

Step 2a: Keep all the pairs which has a neighboring pair available:

```
.Æ             # Get all unique pairs of this list of index-pairs
  ʒ            # Filter it by:
   `           #  Pop and push both pairs separated to the stack
    α          #  Get the absolute difference at the same positions
     P         #  Product to check if both differences are 1
  }€           # After the filter: map over each pair of pairs:
    ¨          #  Remove the last one

```

Try steps 1 and 2a online.

Step 2b: If the input is surrounded by a pair of parenthesis, add its index-pair as well:

```
¯              # Push the global array of pairs again
 ʒ             # Filter it by:
     ‚         #  Pair
  ®            #  -1
   Ig          #  with the length of the input-string
      Q        #  And check if the current pair is equal to this
 }«            # After the filter: merge the two lists of step 2a and 2b together

```

Try steps 1 and 2 online.

Step 3: Remove all characters at those indices, and output the result:

```
˜              # Flatten the list of index-pairs
 Ä             # Get their absolute values, to make the negative indices positive
  <            # Subtract 1, to make the 1-based indices 0-based
   õ           # Push an empty string ""
    s          # Swap so the list of indices as at the top
     ǝ         # Insert the empty string at those indices in the (implicit)
               # input-string, basically removing them
               # (after which the result is output implicitly)

```

**Explanation 2:**

Step 1: Get all substrings of the input, and filter it to only keep those with double leading/trailing parenthesis-pairs:

```
Œ                  # Get all substrings of the (implicit) input-string
 ʒ                 # Filter it by:
  ÁÁ               #  Rotate the substring twice to the right
    4ô             #  Split the string into parts of size 4
      ć            #  Extract the first item
       „()         #  Push string "()"
          ©        #  Store it in variable `®` (without popping)
           º       #  Mirror it to "()()"
            {      #  Sort it to "(())"
             R     #  Reverse it to "))(("
              Qi   #  If the extracted head is equal to this:
  J                #   Join the remainder-list together
   ®Ã              #   Only keep all "()"
     ®õ:õQ         #   Check if these parenthesis are well-balanced:
     ®õ:           #    Keep replacing all "()" with "" until it is no longer possible
        õQ         #    Check if the result is ""
 ]                 # Close both the if-statement and filter

```

Try just step 1 online.

Step 2: Replace all these filtered substrings with it's leading/trailing parenthesis removed in the input-string:

```
v                  # Loop over each of these filtered substrings:
 y                 #  Push the current substring
  D                #  Duplicate it
   ¦¨              #  Remove the first and last characters (the "(" and ")")
     :             #  Replace it in the (implicit) input-string
}                  # Close the loop

```

Try steps 1 and 2 online.

Step 3: Remove a potential leading/trailing parenthesis-pair, if everything else in the string is still well-balanced without it, and output the result:

```
Ð                  # Triplicate the current string
 '(Å?i            '# Pop one copy, and if it starts with a "(":
      ¦¨           #  Remove the first and last character from another copy
        ‚          #  Pair it with the string
         ¤         #  Push the string with first/last characters removed (without
                   #  popping the pair)
          ®Ã®õ:õQ  #  Same as in step 1 to check if its parenthesis are well-balanced,
                   #  resulting in 1 or 0 for truthy/falsey respectively
                 è #  Use that to index into the pair
                   # (after which the result is output implicitly)

```
> 4 votes

# Answer
# Python 3.8, ~~215~~ ~~204~~ ~~195~~ ~~214~~ 205 bytes

*-11 bytes thanks to Unrelated String*
*-9 bytes thanks to att*
*~~+19~~ +10 bytes to properly handle input containing single quotes and/or backslashes*

```
lambda x:P(Q(eval(repr('"\''+x)[3:].translate({40:"',['",41:"'],'"}))))[1:-1]
P=lambda x:[]==x*0and'(%s)'%''.join(map(P,x))or x
Q=lambda x:(x:=[Q(y)if[]==y*0else y for y in x if y])==[[*x[0]]]and Q(*x)or x

```

Try it online!

This was inspired by Ajax1234's **275 byte** answer, which had already had 48 bytes knocked off it (starting at 323 bytes) by okie, Unrelated String, and Steffan.

The `P()` lambda here is based directly on its `P()`. The rest is completely refactored to be functional rather than imperative, but follows a similar approach:

1. Convert the string into a ragged list.
2. Do the parentheses removal on the ragged list.
3. Convert it back into a string. This will be surrounded by outermost parentheses whether or not the original was.
4. Remove the outermost pair of parentheses.

In more detail:

`repr('"\''+x)[3:]` \- backslash-escape single quotes and backslashes, and surround with single quotes (forces `repr` to use single quotes even if they're in the input, by putting a double quote in it)

`.translate({40:"',['",41:"'],'"})` \- replace `(` with `',['` and `)` with `'],'`

At this point, e.g. `"(sig(ma)(om)ega)"` will have become `"'',['sig',['ma'],'',['om'],'ega'],''"`. When we then `eval()` it as Python code, it becomes a ragged list that is a `tuple` on the topmost level, containing lots of empty strings, `''`, mixed in with the strings/lists we want.

The job of `Q()` is to recursively remove the empty strings (which results in the original string converted to a ragged list), and unnest lists whose only element is another list.

`[]==y*0` is true iff `y` is a list – golfed down from `type(y)==list`.

`x:=[Q(y)if[]==y*0else y for y in x if y]` recursively applies `Q()` to `x`'s list elements, and removes its empty string elements.

`x==[[*x[0]]]` is true iff `x` is a list whose only element is another list – golfed down from `type(x)==list and len(x)<2`.

`Q(*x)` recursively applies `Q()` to the result of dropping one pair of surrounding brackets from `x` (unnesting it by one level).

`'(((((a)(b)))c))'` will have become `[[['a'], ['b']], 'c']`.
`' beta(gamma)'` will have become `[' beta', ['gamma']]`.
`'(alpha)'` will have become `['alpha']`.
`'epsilon'` will have become `['e', 'p', 's', 'i', 'l', 'o', 'n']`.

`P()` then converts the resulting ragged list back into a string, surrounding lists' contents with parentheses and joining the strings. `[1:-1]` removes the outermost pair of parentheses, which will be there even if the original input didn't have them.
> 4 votes

# Answer
# Python 3.10,~~194~~ ~~193~~ ~~183~~ ~~177~~ ~~174~~ ~~173~~ ~~165~~ 163 bytes

* -1 byte since one string didn't need to be raw
* -10 byes by using a recursive function to re-assemble the output rather than regex
* -6 bytes thanks to @deadcode by using `map()` instead of a comprehension
* -3 bytes by copying string comparison logic from dead code's answer
* -8 bytes thanks to @deadcode and @steffan
* -2 bytes by using old-style string formatting instead of modern f-strings

Since it's a slightly different approach than the other python answers I think this deserved it's own answer. Probably further golfable.

```
lambda x:u(eval(s('\)\(','),(',s('(?<![^(]),','',s('[^()]+',lambda i:",%r,"%i[0],x)))))[1:-1]
u=lambda g:g if''==g*0else"(%s)"%"".join(map(u,g))
import re;s=re.sub

```

Attempt This Online!

## Explanation

1. Extract all sequences that don't contain parenthesis and surround them by quotes and commas.

```
a = re.sub('[^()]+',lambda i:",%r,"%i[0],x)

```
2. Remove commas at the start of the string and right after opening parenthesis

```
b = re.sub('(?<![^(]),','',a)

```
3. Eval the string then repr it again, this part actualy does the parenthesis removing

```
c = eval(b)

```
4. Basically a custom repr function that ignores strings

```
u=lambda g:g if g*0==''else"(%s)"%"".join(map(u,g))
d=u(c)

```
5. Remove the first and last character

```
f=e[1:-1]

```
> 4 votes

# Answer
# JavaScript (Node.js), 112 bytes

```
a=>a.map((c,i)=>c=='('?a[a.push(!i|a[i-1]==c?[c]:c)-1]:c==')'&&(a[p=a.pop(),i+1]||c)==c?(p[0]='')+p&&c:c).join``

```

Try it online!
> 3 votes

# Answer
# Jelly, ~~32~~ ~~30~~ ~~28~~ 27 bytes

```
=þØ(_/µJṁ"Äo¹ṁɗ\ḟ"JċⱮ`HnAɓx

```

Try it online!

Removes every pair of parentheses which is the only thing contained by either an outer pair or the entire string.

```
=þØ(                           Table equality with "()"
    _/                         and subtract the close parens from the open parens.
          Ä                    Cumulative sum, to get depths,
      µJṁ"                     repeat each index by its depth,
               \               and scan by:
           o                   overlay the element on the accumulator
            ¹ ɗ                then
             ṁ                 trim the accumulator to the element's length.
                ḟ"J            For each result, filter out its index.

=þØ(_/µJṁ"Äo¹ṁɗ\ḟ"J            This results in a list of lists where each list
                               uniquely represents the deepest pair of parentheses
                               containing the corresponding element.

                   ċⱮ`         Count how many times each list appears.
                      H        Is each count halved
                       n       not equal to
=þØ(_/µ                 A      if the corresponding element is a paren?
                         ɓx    Replicate the input by that result.

```
> 3 votes

# Answer
# Python 3.8, 190 Bytes

```
def f(s,r="",o="("):
 while o in s:a,b=s.split(o,1);i=[b.count(o,0,i+1)-b.count(")",0,i+1) for i in range(len(b))].index(-1);s=b[i+1:];r=r+a+o+f(b[:i])+")" if r+a+s else f(b[:i])
 return r+s

```

No regex library!

This works by going through each open paren, finding the matching close paren, and recursing on the contents. If, at any recursion level, the parens identified enclose the whole string being considered, they are redundant and discarded (as they either enclose the whole string or enclose a substring that is immediately surrounded by another pair of parens).

Un-golfed Version:

```
def f(unparsed_string):
    ret = ""
    while "(" in unparsed_string:
        # Split on first open paren
        first, rest = unparsed_string.split("(", 1)
        # Find index of matching close paren; it's the first index in `rest`
        # where the number of close parens is one more than the
        # number of open parens.
        # This will error if the parens are unmatched
        close_paren_index = [
            rest[:i+1].count("(") - rest[:i+1].count(")")
            for i in range(len(rest))
        ].index(-1)
        unparsed_string = rest[close_paren_index+1:]
        if (ret + first) or unparsed_string:
            # Recurse on the contents of the identified parens
            ret += first + "(" + f(rest[:close_paren_index]) + ")"
        else:
            # If the identified parens are the beginning and end of
            # the string, they are redundant; return just the recursed payload
            ret = f(rest[:close_paren_index])
    return ret + unparsed_string

```
> 3 votes

# Answer
# JavaScript (Node.js), 206 bytes

```
s=>eval(`[${s[[].__proto__.toString=function(){return this[1]?this.map(e=>Array.isArray(e)?`(${e})`:e).join``:this[0]+''},r='replace'](/[^()]+/g,m=>JSON.stringify(m)+',')[r](/\(/g,'[')[r](/\)/g,'],')}]`)+''

```

Try it online!
> 2 votes

# Answer
# Rust, ~~408~~ 396 bytes

I made this problem way to hard for myself

```
let f=|b:&[u8]|->Vec<u8>{let v=(0..).zip(b).scan(vec![],|a,(b,c)|Some(match c{40=>{a.push(b);None}41=>{Some((a.pop()?,b))}_=>None})).flatten().collect::<Vec<_>>();for k in &v{if k.0==0&&k.1==b.len()-1{return b[1..b.len()-1].to_vec();}for l in &v{if l.0==k.0+1&&l.1==k.1-1{return [&b[..k.0],&b[l.0..k.1],&b[k.1+1..]].concat();}}}return b.to_vec();};let g=|mut b:Vec<u8>|{while f(&b)!=b{b=f(&b)}b};
```

Attempt This Online!

## Expanded version:

```
    // Single iteration
    let f = |b: &[u8]| -> Vec<u8> {
        // Find all pairs of parenthesis and store them in v
        let v = (0..)
            .zip(b)
            .scan(vec![], |a, (b, c)| {
                Some(match c {
                    40 => {
                        a.push(b);
                        None
                    }
                    41 => Some((a.pop()?, b)),
                    _ => None,
                })
            })
            .flatten()
            .collect::<Vec<_>>();
        // For ever pair
        for k in &v {
            // If it's the first and last, return everything except the first and last character
            if k.0 == 0 && k.1 == b.len() - 1 {
                return b[1..b.len() - 1].to_vec();
            }
            for l in &v {
                //else if a second pair touches it
                if l.0 == k.0 + 1 && l.1 == k.1 - 1 {
                    // combine 3 sections to crate the whole string again without 2 parenthesis
                    return [&b[..k.0], &b[l.0..k.1], &b[k.1 + 1..]].concat();
                }
            }
        }
        return b.to_vec();
    };
    let g = |mut b: Vec<u8>| {
        //while f(x) does something
        while f(&b) != b {
            b = f(&b)
        }
        b
    };

```
> 1 votes

---
Tags: code-golf, string, balanced-string
---


title: mini SPICE solver

text:
# Question
Title: mini SPICE solver
SPICE is an electrical circuit simulation program originating from UC Berkeley. Your goal is to implement a minimalistic version which can solve for the nodal voltages and branch currents of a circuit composed of resistors and DC current sources.

# Input Format

The input may come from a file, io stream, or the nearest equivalent in your language of choice. However, it cannot be a function input or hard-coded string. The format should be a subset of what the original SPICE used. A quick summary of what is required for the input format:

1. First line is a title line
2. Following the title is the description of circuit components and their connectivity. This may be in any order (i.e. you can't assume all resistors come before current sources/vice-versa). See **component descriptors** below for how component descriptions are formatted.
3. Following the circuit components is the command control block. The only solver you need to implement is the DC operating point solver (`.OP`)
4. Following the command control block are the values to output (nodal voltages/branch currents). See **output descriptors** below for how these should be formatted.
5. The last line is `.END` (you may choose whether an ending carriage return is required or optional)
6. Any line beginning with `*` denotes a comment and must be skipped by your parser.

## Component Descriptors

All component descriptors are in the form:

```
XN A B C

```

Where:

* `X` is `R` for resistor or `I` for a current source
* `XN` is the name of the component. `N` may be any alphanumeric sequence.
* `A` is a non-negative integer indicating which node the positive terminal for the component is connected.
* `B` is a non-negative integer indicating which node the negative terminal for the component is connected.
* `C` is a decimal value (for a resistor this is the resistance, and for a current source this is the current from this source)
* By convention, node `0` is considered *ground* and is at `0V`. All other nodal voltages are referenced from ground.
* By convention, positive current flows from the positive terminal to the negative terminal.

## Output descriptors

The only output format you need to support is `.PRINT`. This may output to a file, output stream, or the nearest equivalent in your language of choice. It may not be just a function return string.

**Format of .PRINT statements**:

```
.PRINT X(N)

```
* `X` is `V` for printing a nodal voltage or `I` for printing the current through a component.
* `N` is the name of the quantity being outputted. For a nodal voltage, this is any non-negative number. For a current, this is the component name.

For each print statement, you should output the argument and the appropriate value `v`:

```
X(N) v

```

You may print the output in any order so long as there's one output per line.

## Things you don't have to support

1. Subcircuits
2. "Line continuations" (i.e. any lines starting with a `+`)
3. "SI" suffixes (e.g. `1k` instead of 1000). However, your code should be able to handle decimal input (you may specify the format)
4. Error handling (i.e. you may assume the input is properly formatted and has a unique solution)
5. You may specify any case requirements (all upper case, all lower case, case insensitive, case sensitive, etc.)
6. You may choose to require that the nodes may be ordered sequentially without skipping any integers.
7. You may use any solver algorithm you want.

# Scoring and Misc.

* This is code golf, shortest code in bytes wins.
* You may use any libraries you wish provided it wasn't designed specifically for handling circuits. Ex.: Using BLAS/LAPACK for matrix math is ok, but you can't use Ngspice because it is a SPICE circuit simulator already.
* Any other standard loop holes are prohibited.
* For guidance on how to implement a solver, here's a quick guide on modified nodal analysis. Note that because there are no voltage sources you can implement only the basic nodal analysis part (I link this resource because it has some good insights on how to implement such a solver). Additional resources on MNA and another another approach, sparse tableau analysis, can be found here.

# Example inputs and expected outputs

## Ex. 1

```
Example 1
* this is a comment
R1 1 0 1
I1 0 1 1
.OP
.PRINT I(R1)
.PRINT V(1)
.END

```

**Output:**

```
I(R1) 1
V(1) 1

```

## Ex. 2

```
Example 2
I1 1 0 1
* this is a comment
R1 1 0 1
.OP
.PRINT V(0)
.PRINT I(R1)
.PRINT I(I1)
.PRINT V(1)
.END

```

**Output:**

```
V(0) 0
I(R1) -1
I(I1) 1
V(1) -1

```

## Ex. 3

```
Example 2
ISINK 1 0 1.0
ISOURCE 0 2 2
R1 1 0 10
R2 1 2 1
.OP
.PRINT V(1)
.PRINT V(2)
.PRINT I(R1)
.PRINT I(ISOURCE)
.PRINT I(R2)
.END

```

**Output:**

```
V(1) 10
V(2) 12
I(R1) 1
I(ISOURCE) 2
I(R2) -2

```

# Answer
> 3 votes
# Python \+ MiniZinc, ~~703~~ 642 bytes

*thanks to @Unrelated String for the input to golf more*

```
import sys
t=sys.stdin.readlines()[1:]
d=[[x.split()[i]for x in t if x[0]not in".*"]for i in range(4)]
a="array[1..m]of "
F=r"/\forall(j in "
print("output[",*(fr'"{x[7:-1]} \({x[7].lower()}[{x[7]=="I"and-~d[0].index(x[9:-2])or x[9:-2]}])\n",'for x in t if".P"==x[:2]),'""];',fr"int:m={len(d[0])};int:n={max(map(int,d[1]+d[2]))};"+fr"array[0..n]of var float:v;{a}var float:i;{a}int:s;{a+'int:e;enum T={R,I};'+a}T:t;{a}float:x;constraint v[0]=0{F}1..m)(t[j]=I/\x[j]=i[j]\/t[j]=R/\v[s[j]]-v[e[j]]=x[j]*i[j]){F}0..n)(sum([i[k]*((s[k]=j)-(e[k]=j))|k in 1..m])=0);")
d[0],_=zip(*d[0])
for i,n in enumerate("tsex"):print(f"{n}=[{','.join(d[i])}];")
```

Attempt This Online!

How to run: `python <script file> | minizinc -`. It may be necessary to explicitly select the solver to use, passing the arguments `--solver <solver id>` to `minizinc`.

## What is MiniZinc?

Minizinc is a constraint programming modelling language; the homonymous command line tool compiles the model, runs a solver, and outputs the solution in the desired format. It is not a proper programming language (since it is not Turing complete), but it can be considered a library since one could replace it by using its proper native python interface.

## How it works

The Python code just handles the input format, translating it into a MiniZinc model. The model imposes the following constraints:

Here's an ungolfed version of the MiniZinc model (without the actual parameters):

```
% n is the number of nodes (excluding the ground node)
% m is the number of edges (resistors and current sources)

array[0..n] of var float: voltage;
array[1..m] of var float: current;

array[1..m] of 0..n: start; % the first  node of each edge
array[1..m] of 0..n: end;   % the second node of each edge

enum T = {R, I}; % the two types of edge: resistors and current sources

array[1..m] of T: t; % the type of each edge
array[1..m] of float: x; % the value (resistance or current) associated with each edge

% 0 is ground
constraint volt[0]=0;

% source current is equal to current
constraint forall (i in 1..m where t[i]==I) (x[i] == current[i]);

% V = R * I
constraint forall (i in 1..m where t[i]==R) (voltage[start[i]] - voltage[end[i]] = x[i] * current[i]);

% sum of currents is zero
constraint forall (j in 0..n)
  ( sum([current[i] | i in 1..m where start[i]==j]) ==
    sum([current[i] | i in 1..m where end[i]==j]));

```

---
Tags: code-golf, parsing, electrical-engineering
---