title: Faux Source Code

text:
# Question
Title: Faux Source Code
Output one random character for each character of source code (as illustrated below). The probability of each character is its frequency in the original source code. Thus the output will be fake source code resembling a quine.

# Specification

* **Restrictions**
    + Standard constrains apply. No empty programs or functions. Also no reading your own source.
* **Output**
    + The number of characters output should be exactly the number of characters in the source code
    + *Each* output character should be randomly choosen
    + The probability of choosing any character is equal to `(occurrences in source) / (length of source)`
    + This means that even a unary solution needs to 'randomly' choose `1` with probability `1`. Which is to say that the output can't be hard coded.
* **Winning**
    + This is code golf, so fewest bytes wins

# Example

```
Program           Frequency           Probability           Possible Output
-------           ---------           -----------           ---------------
 a@!@              a - 1               a - 25%               @@a@
                   ! - 1               ! - 25%
                   @ - 2               @ - 50%

```

```
Program           Frequency           Probability           Possible Output
-------           ---------           -----------           ---------------
caBaDBcDaBDB       a - 3               a - 25%               aaaBBBBccDDD
                   B - 4               B - 33%
                   c - 2               c - 17%
                   D - 3               D - 25%

```

# Answer
> 9 votes
# Perl 5, 54 bytes

```
$_=q{print$_[rand@_]for@_="\$_=q{$_};eval"=~/./g};eval

```

Try it online!

Produces output like:

```
_anr_;q.=fn_}v"_eo_f=n\di{nqde}[;}}o}t==@$@$=nvr$}/r=.
"q}=g{;}=[av$a}a__l[q@@;$;_}./@__a.ne=@@i_}_aet.=$=_o"
/arr_r]po{{l_=;__e"_et=="@vr__a_}@nl"ll~$=~_q~d"=v$~$/
q/@=_$__{f{vl;.]@=__=@lpapr}da@eeg_[$@lr\_{{pq$$$vrq=/
=v{[_l=p{{={/n$nv$n[_/aev_v=@on}la;}q{_otr$oaglve$.a_}
_aa;@r='{{=@{ntf;;.if}f}a$;$g/n;g;_}rroaqra=;}l.gre[t'

```

In a brief test, ~3-4% of the results of the program `eval` successfully. I'm not sure what that says about Perl...

# Answer
> 8 votes
## CJam, 14 bytes

```
{{E*`mR}`mR}E*

```

Try it online!

### Explanation

Each character appears exactly twice, so the probabilities of the characters should all be the same.

```
{           e# Repeat this block 14 times.
  {E*`mR}   e# Push this (nonsensical) block.
  `         e# Stringify it, giving the string "{E*`mR}", which contains each of the
            e# seven characters once.
  mR        e# Select one of the characters at random.
}E*

```

# Answer
> 7 votes
# Jelly, 13 bytes

```
“;⁾vṾWṁ$X€”vṾ

```

Try it online!

### How it works

```
“;⁾vṾWṁ$X€”vṾ  Main link. No arguments.

“;⁾vṾWṁ$X€”    Set the argument and return value to the string s := ';⁾vṾWṁ$X€'.
            Ṿ  Uneval; construct a string representation of s.
               This yields r := '“;⁾vṾWṁ$X€”'.
           v   Dyadic eval; evaluate s with argument r.

 ;⁾vṾWṁ$X€     Evaluated link (s). Argument: r

  ⁾vṾ          Yield 'vṾ'.
 ;             Concatenate r with 'vṾ'.
               This yields t := '“;⁾vṾWṁ$X€”vṾ', i.e., the original source code.
       $       Combine the previous two links into a monadic chain.
     W           Wrap; yield ['“;⁾vṾWṁ$X€”vṾ'].
      ṁ          Mold; repeat ['“;⁾vṾWṁ$X€”vṾ'] once for each charcter in t.
        X€     Random each; select a character, uniformly at random, of each
               of the 13 repetitions of t.

```

# Answer
> 4 votes
# Japt, 22 bytes

```
"+Q ²£ZgMqB"+Q ²£ZgMqB

```

Test it online!

### How it works

```
"+Q ²£ZgMqB"+Q ²£ZgMqB  // Implicit: B = 11
"+Q ²£ZgMqB"            // Take this string.
            +Q          // Append a quotation mark.
               ²        // Double the result.
                £       // Replace each char in the result Z with
                 Zg     //  the char in Z at index
                   MqB  //   random integer in the range [0, 11).
                        // Implicit: output last expression

```

# Answer
> 4 votes
# Pyth, 16 Bytes

```
smO+N"m1NOs+6"16

```

**try it online!**

Contains each char twice therefore the probability is the same as if each was only in there once.

```
smO+N"m1NOs+6"16     #
   +N"m1NOs+6"       # Add a quotation mark to the string: "m1NOs+6
  O                  # random choice from the string
 m            16     # do this 16 times.
s                    # join the list into a string

```

# Answer
> 3 votes
# PHP, ~~71~~ ~~140~~ ~~110~~ ~~124~~ ~~140~~ 120 bytes

```
for($i=2*$n=strlen($s='for($i=2*$n=strlen($s=.chr(39));$i--;)echo$s[rand(0,$n-1)];'.chr(39));$i--;)echo$s[rand(0,$n-1)];

```

run with `php -d`

1. creates a string containing the code without the quotation marks
2. and concatenates the quotation mark *once* using `ord`
(same probability as if I would double the string and add two quotes);
3. then loops over twice the length of the string to get random characters from it.

Can possibly be golfed further, but my attempts on eval where futile so far.
I will probably not go deeper here.

# Answer
> 3 votes
**Python 2, 88 bytes**

```
s='''from random import*; print "".join(choice(s) for c in "s='"+s+"';exec s")''';exec s

```

All *actual* merit in getting this far goes to mbomb007 - thanks for your help (and the pointer about backslashes)

# Answer
> 3 votes
## Ruby, 47 bytes

```
eval r="47.times{$><<('eval r=%p'%r)[rand 47]}"

```

This is based on the standard `eval` quine:

```
eval r="$><<'eval r=%p'%r"

```

It's a byte longer than the shortest quine, but it's usually the better choice for generalised quines, because any computation done on the source code string does not need to be duplicated. Whereas in the usual quine, every additional computation needs to go both inside and outside the main string, it is only needed inside the main string for this kind of quine.

As for what the code actually does: after obtaining a string representing the entire source code, we simply select a random character (by selecting a random index) 47 times and print each character separately.

# Answer
> 3 votes
# Wolfram Language/Mathematica, 109 Bytes

```
Function[Print[StringJoin[RandomChoice[StringSplit[StringJoin[ToString[FullForm[Slot[0]]],"[]"],""],109]]]][]

```

sample output:

```
niPi[no,ili[Siu[,Sdoio9nthg"t ginuu[1[o]"i,icgi[0TncrS"[ln"o0]r,i][Jon[[et]0"]m [ri"a[]motrin,iFoFnultnnno,Jl

```

Oh those square brackets.

# Answer
> 3 votes
# JavaScript, 128 bytes

```
a=";a+=uneval(a);alert(a.replace(/./g,_=>a[Math.random()*64|0]))a=";a+=uneval(a);alert(a.replace(/./g,_=>a[Math.random()*64|0]))

```

Note: only works in Firefox due to the use of `uneval`.

Sample runs:

```
)a(rgc=d6m_a4uar=hp(lll(,d=m=dee(M(gtraoan0)(M(aaaa(M]c)e)/M()/u//M6_n/a"*unea(/>atugrn(a=nav"|;)|=)/,ataa,aaangtue;am)t0;|ctoa/
=lvct;eee,,a.e=6r0;);Mtaaoa.aeea4)a[r.6]e/ll+l.)=)|a[(c"rao4ea/=_acaMh=veerva"a(_(d(l)lgn.;rM">=ea40a*).e(h(laa6r)4a)rhlar=t(ta[
[rt]ll]n))aota.e)g;>ae*;..4tt];l[;].*lnr4(mnM|alg(a.ag(.=e(a>>aa>.hga;a/pat+elc];apc=(ag)tao.).ll4u)dah]r(ul)>lr;,)ret(e/g(=_c*r
M.r)_;.a(lraalg("mac>dmrlr"0/ah(a()ead|/0a(m.|u0)(a(0_[dn)a]/raal;eata)a.ataeaa*l)=ra()la=(a)*aaea>n;.a.)ca)orM(tm*a,a=)p;(>r)aa

```

# Answer
> 2 votes
# Jelly, 44 bytes

I hope I have interpreted all the rules correctly (I'm not *quite* sure what the "carry payload" thing is in meta or if it's even relevant to this challenge).

```
“ẋ2;8220Ọ;8221ỌXµ44Ð¡Ḋ”ẋ2;8220Ọ;8221ỌXµ44Ð¡Ḋ

```

Test it out at **TryItOnline**

This constructs a string from which to choose characters. The initial string has all the character used *except* the open and close quotes. It then doubles that string and concatenates *one of each* of the open and close quotes from ordinals (hence the need to double the other characters). Lastly it repeatedly picks random characters from the composed string to the length of the program.

# Answer
> 2 votes
## Pyke, 35 bytes

```
35F\";"\\+3322 5**F;H)s"\"2*+2* H)s

```

Try it here!

To check: remove the final `H` and the resulting string contains the right number of each character (with the extra `H`)

This does NOT use a generalised quine or in fact a quine at all. It relies on being able to create a string containing all the characters in the source. It *should* be able to do it for any code but each character logarithmically increases code size. The only number of times a character is allowed in the source is 2 or 7

# Answer
> 2 votes
**C, 125 bytes**

```
char*s="char*s;l,i;f(){l=i=strlen(s);while(i--)putchar(s[rand()%l]);}";l,i;f(){l=i=strlen(s);while(i--)putchar(s[rand()%l]);}

```

**C, 60 bytes for golfed but not quine code taking any string**

```
l,i;f(char*s){l=i=strlen(s);while(i--)putchar(s[rand()%l]);}

```

While for counting characters my solution needed 86:

```
c[256];i;f(char*s){i=256;while(*s)c[*s++]++;while(--i)while(c[i]?c[i]--:0)putchar(i);}

```

# Answer
> 2 votes
## Ruby, ~~81~~ 67 bytes

*Saved a bunch of bytes by stealing some tricks from Martin's solution*

```
s="s=%p;67.times{$><<(s%%s)[rand 67]}";67.times{$><<(s%s)[rand 67]}

```

I didn't realize that you had to randomly select every time; I thought a shuffle would do the trick. This can probably be golfed, but it's the shortest I could get it.

Standard Ruby quine with a few modifications so it prints out the shuffled string. I'm sad because it took like fifteen minutes to figure out the formatting quirks before I realized that I was subconsciously stealing it anyway.

I think the string shuffling can be shortened but I don't know how; I might also be able to finagle the formatting into being shorter once I put some thought into it. Help would be appreciated.

Try it online!

# Answer
> 2 votes
# C, 136 bytes

```
main(a){for(a=136;a--;)rand()%68?putchar("main(a){for(a=136;a--;)rand()%68?putchar([rand()%67]):putchar(34);}"[rand()%67]):putchar(34);}

```

Example output:

```
;%7c(u)"r4-hd)nnr-%n6;6(4or(n4(6(a:=a3r-:()hp(:aa%;4rru}h;(a()3mh3rdi7));a-u36:r3on[4?p((]6n6?()-6t736unhr%:[%[[d(p:[ru)-n(6r=:](p-})8"]

```

This program outputs 136 characters randomly.

The entire source code (less " quotation marks) is contained in a string. The program determines the probability of outputting a quotation mark as 2/136, otherwise outputting one of the other 67 characters randomly.

There are two occurrences of each character in the string in the program. The probability of outputting a character from the string is 134/136. The probability of choosing a specific character in the string is 1/67. So the chance of outputting a character in the string is 134/136 * 1/67 = 2/136. There are two occurrences of each string character in the program, so there is a 1/136 probability of outputting a character for each occurrence in the program.

The order of symbols inside the string doesn't matter.

# Answer
> 2 votes
# , 174 bytes

```
cat(sample(el(dimnames(a<-table(c("\n",el(strsplit(scan(,""),"")))))),174,T,a),sep="")
cat(sample(el(dimnames(a<-table(c("\n",el(strsplit(scan(,""),"")))))),174,T,a),sep="")

```

Try it online!

The function `sample` performs discrete random sampling. Itcan take as 4th argument a vector `prob` of probabilities. The vector `prob` does not need to be normalized (i.e. it does not need to sum to 1): here, we use a vector of counts, and `sample` does the renormalizing.

The 2 lines are identical. The 1st line does the hard work, and reads the contents of the 2nd line to get the counts of each character. So here, the vector of probabilities `a` actually sums to 87=174/2. Note the special treatment of the newline, which `scan` does not read. I can't think of a way of avoiding this without having to add more bytes to handle quotation marks.

# Answer
> 1 votes
# Python 3, ~~134~~ 132 bytes

I use every character in my source code within the string the correct number of times, then multiply the string by two to include itself. The program prints a random character from that string for each character in the code (the length is hard-coded.)

```
from random import*
for i in[0]*134:print(choice("""from random import*
for i in[0]*134:print(choice(""*""2""),end='')"""*2),end='')

```

**Try it online**

I avoided backslashes like the plague. As soon as the code contains `\n` or `\"`, you have a problem, because the string doesn't contain backslashes yet, so you have to add those also, but in a separate string multiplied by a higher number, because it takes two backslashes to represent one (`\\`).

### Example output:

```
i(tc*"3]i o''r=,,,h34t"r
ri"](fco t)niap)t "it2nc0o  npoi3'"nto(*4 i(ido' r*4f"oi]d rm ,i"eif)m"d
m emi
dfr n*p 3*(i""r1d"dr menc hio'

```

I gotta say, it reminds me of FlogScript.

# Answer
> 1 votes
## PowerShell v2+, 175 bytes

```
$d='$d={0}{1}{0}{2}-join(0..174|%{3}[char[]]($d-f [char]39,$d,"`n",[char]123,[char]125)|Random{4})'
-join(0..174|%{[char[]]($d-f [char]39,$d,"`n",[char]123,[char]125)|Random})

```

Quines in PowerShell suck, because the string replacement delimiters `{}` also denote loops and whatnot, so you need to use a *bunch* of `char`s in the `-f` operator, which bloats the code.

Similar-ish to my Quine on Every Line answer. Basically we loop from `0` to `174` and each iteration re-calculate the quine `$d`, cast it as a `char`-array, and pull out a `Random` element chosen uniformly from the input. By definition, this gives probability `(occurrences in source) / (length of source)` as required. Those characters are encapsulated in parens and `-join`ed together back into a string.

### Example

```
PS C:\Tools\Scripts\golfing> .\faux-souce-code.ps1
}}[${hr[`ini}}] [5i,=[]0,j2($=n4(dm]jh]jc]]7
}..j"rnj9|fn,4r]{9]('["jdh0}$rd,-f,a.c"}{h1 ]5d,),0n5|nh(]73a9da4aRi[5}a}430}}rd$,$r)-hhr%or79-R.R-`'r'aa|=1f0][|[{7}do1]$ja0 rd{h

```

(Yes, that's a newline in the output -- when a string containing a newline is `char`-array'd, the ``n` is treated as a character, since a `char`-array is just an array of byte codes, so it also has a 1/175th chance of being selected.)

# Answer
> 1 votes
# Dyalog APL, 20 bytes

```
f←{(,⎕CR'f')[?⍴⍨20]}

```

`f←{`...`}` define **f** as

`(,⎕CR'f')` listified (`,`) **C**haracter (table) **R**epresentation (`⎕CR`) of **f** (`'f'`)

`[?⍴⍨20]` indexed with (`[`...`]`) random-up-to (`?`) repeat-itself-times (`⍴⍨`) of twenty

Let us run it (with a dummy argument) a few times:

```
      f⍬
)0'0](⍨(([],}⎕))⎕'f2
      f⍬
{'['}f[←R[)2←?}⍨]}C2
      f⍬
,,⍨←?2}⍴?'⍨}C,'{⎕(C0

```

Fine, but is the distribution correct? Let us run it on 10,000 dummy arguments and see how many times each character occurs:

```
      {⍺ , 1E¯4× ⍴⍵}⌸ ∊ f¨ ⍳1E4
C 0.9952
⎕ 0.9996
' 1.9777
f 2.004
← 1.0018
⍨ 1.0173
0 1.0213
] 1.0049
[ 0.9988
2 0.9943
{ 0.9895
) 1.0093
R 1.0054
, 1.0029
? 0.9943
} 0.9861
⍴ 1.0032
( 0.9944

```

Clearly, `f` and `'` occur twice as often as the other characters, just like in the original source code.

How did we do it?

```
{⍺ , 1E¯4× ⍴⍵}⌸ ∊ f¨ ⍳1E4`

```

`⍳1E4` generates the first 10,000 integers

runs **f** on each of those numbers

flattens all the pseudo-quines into a single 200,000-character string

is a higher-order function which for each unique character in the right side data, feeds the left-side function the unique element as left-argument and the indices where that character occurs as right-argument. The left-side function is

```
{⍺ , 1E¯4× ⍴⍵}

```

left-argument, i.e. the unique character

`,` followed by

`1E¯4×` 1×10⁻⁴ times

`⍴⍵` the shape of the right-argument (the occurrence indices), i.e.how many times it occurs

Finally,  puts it all together in a table.

# Answer
> 1 votes
# C#, ~~277~~ ~~280~~ 268 bytes.

```
using System;class a{static void Main(){var s="using System;class a{static void Main(){var s=\"x5Cx5C\x5C\x5C\";Random d=new Random();for(int i=0;i++<268;)Console.Write(s[d.Next(0,134)]);}}";Random d=new Random();for(int i=0;i++<268;)Console.Write(s[d.Next(0,134)]);}}

```

Ungolfed:

```
using System;
class a
{
    static void Main()
    {
        var s="using System;class a{static void Main(){var s=\"x5Cx5C\x5C\x5C\";Random d=new Random();for(int i=0;i++<268;)Console.Write(s[d.Next(0,134)]);}}";
        Random d=new Random();
        for(int i=0;i++<268;)
            Console.Write(s[d.Next(0,134)]);
    }
}

```

Pretty sure this works correctly.

Sample output:

```
    fn;i)(]ns;<ftt08et]i+ii8]m[W}dr{rmte,)t edayid 2s cmsee\;ta["e n;o}]iolys;t sftoR{.=g vs8;(sd isWrecn++iia]iuf"avs\i<{ee vfs[ensin\s i]0a(We.0ns R(2roo=ldxil\{t(o"aistt.;.  r w"m1];idi}Ctitiindnn;M[,[+0(,o"]mca[rmnm)<;n"8ReaystinRsanr([(d,n\.ateiR sd.=[=;ttn.;wna)cCt[=+t{Wxs(\}rg

```

# Answer
> 1 votes
# Julia 1.0, 50 bytes

```
(a=:(print.(rand("(a=:($(a)))|>eval", 50))))|>eval

```

Try it online!

based on this quine:

```
(a=:(print("(a=:($(a)))|>eval")))|>eval

```

Try it online!

# Answer
> 1 votes
# , 136 bytes

```
a=scan(,"");cat(intToUtf8(sample(rep(c(10,utf8ToInt(a)),2),136,T)))
a=scan(,"");cat(intToUtf8(sample(rep(c(10,utf8ToInt(a)),2),136,T)))

```

Try it online!

The "read-a-second-copy-and-sample-from-it" approach is shamefully copied from Robin Ryder's answer: please upvote that one.

Here, however, rather than counting the instances of each character and using this to weight the sampling, we just sample uniformly from the full set of characters (including repetitions).

# Answer
> 1 votes
# Python 3.8 (pre-release), 75 bytes

```
exec(a:='from random import*;print(*choices("exec(a:=%r)"%a,k=75),sep="")')

```

Try it online!

---
Tags: code-golf, random, quine
---


title: Is this expression Python 2/3 safe?

text:
# Question
Title: Is this expression Python 2/3 safe?
Given an expression like `4 / 2 + 3`, determine whether the expression has the same value in Python 2 and Python 3. Recall that in Python 2 division rounds down (so that `5 / 2 -> 2`), whereas in Python 3 division returns a float (so that `5 / 2 -> 2.5`).

For simplicity's sake, we will only consider expressions of the form:

```
a o1 b o2 c

```

Where

* `a`, `b`, and `c` are numbers between 1 and 5 inclusive; and
* `o1` and `o2` are either the addition, multiplication or division operators (`+`, `*`, `/`)

Note that the restrictions mean the expression will always be the same length and will never have any zero division issues.

Operator precedence is the same as in Python (`*` and `/` have equal and higher precedence to `+`, evaluated left to right).

Since this is in part a parsing challenge, you must take the input exactly as given including spacing in a string-like form appropriate for your language (and not, for example, a preparsed AST).

You can print or return any two distinct consistent values to indicate true or false.

## Test cases

```
1 + 2 + 3 -> true
2 * 3 + 5 -> true
3 / 3 + 3 -> true
4 / 2 * 2 -> true
2 * 2 / 4 -> true
4 / 2 / 1 -> true
5 + 4 / 2 -> true

1 / 2 + 3 -> false
5 / 2 * 2 -> false
3 / 2 * 4 -> false
2 + 3 / 5 -> false
4 / 4 / 4 -> false

```

## Scoring

This is code golf, shortest code in bytes wins.

# Answer
# C (clang), ~~121~~ \\$\cdots\\$ ~~119~~ 117 bytes

```
#define P(v)v=*x-47?*x-43?v*a:t?a:v:v/a
float d;b;t;a;f(*x){for(t=b=d=*x-48;*++x;t=!++x)a=x[1]-48,P(d),P(b);*x=d==b;}

```

Try it online!

Inputs the Python expression as a wide string.
Parses the string and returns (at the end of the input string) \\$1\\$ if the expression is the same in both Python 2 and 3 or \\$0\\$ otherwise.

### Commented code

```
#define P(v)                              // Macros are type-less so will
                                          // calculate both floating point
                                          // and integral values
            v=                            // set the parameter to:
              *x-47?                      // is the char at *x not '/' ?
                    *x-42?                // is the char at *x not '+' ?
                          v*a:            // then it's '*' so multiply
                              t?          // here it's '+' so check t
                                a:        // t is only truthy at the start
                                          // so set parameter to a
                                  v:      // after that t's 0 so leave
                                          // parameter as is
                                    v/a   // here it's '/' so divide
float d;                                  // floating point type for Python 3
                                          // calculations
        b;                                // integral type for Python 2
                                          // calculations
          t;                              // toggle for signalling first and
                                          // second parts
            a;                            // value in Python expression
f(*x) {                                   // function taking wide string
                                          // parameter
       for(                               // loop over first and
                                          // second part
           t=                             // set t to non-zero value
             b=d=*x-48;                   // set d and b to first number
                       *++x;              // move pointer to next char and
                                          // finish looping at the end of the
                                          // input string
                            t=!           // after first loop set t=0
                               ++x)       // bump x again
            a=x[1]-48,                    // set a to next number
                      P(d),               // parse with floating point type
                           P(b);          // parse with integral type
        *x=d==b;                          // set end of string to 1 if the
                                          // floating point value is equal to
                                          // integral or 0 otherwise
}

```
> 10 votes

# Answer
# Python 2, 28 bytes

```
lambda s:eval("1.*%s.>"%s+s)

```

Try it online!

This saves a byte using that Python 2 value will always be less or equal within the constraints of this challenge. Inverted output: False means safe, True unsafe.

## Old Python 2, 29 bytes

```
lambda s:eval("1.*%s.=="%s+s)

```

Try it online!

Forces Python 3 semantics in Python 2 by converting terms 1 and 3 to float, evaluates and compares to the original.
> 7 votes

# Answer
# Python 3.8 (pre-release), 33 bytes

```
lambda s:eval(s)%1>eval(s[:5])%-1

```

Try it online!

Port of tsh's Javascript answer.

### Old version

# Python 3.8 (pre-release), 41 bytes

*Thanks @Unrelated String for -2 bytes through some eval wizardry*

```
lambda s:eval(s+'=='+s.replace("/","//"))

```

Try it online!
> 6 votes

# Answer
# Desmos, ~~122~~ 113 bytes

```
L=l-48
g(a,b,o,k)=\{o=-6:ab,o=-1:a/b,k=0:b,a\}
h(k)=mod(g(g(L[1],L[5],L[3],0),k,L[7],1),1)
F(l)=\{h(L[9])>-h(1)\}

```

Basically just a port of tsh's Javascript answer, though a bit more complicated (when was using Desmos in a string parsing challenge ever a good idea??).

Takes in input as a list of character codepoints. Returns `undefined` for truthy cases, and `1` for falsey cases.

Use this TIO link to convert from string input (`2 * 3 + 5`) to list of codepoints wrapped in the output function (`F\left([50, 32, 42, 32, 51, 32, 43, 32, 53]\right)`) which can be copy pasted into Desmos directly.

Try It On Desmos!

Try It On Desmos! - Prettified
> 6 votes

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

```
s=>eval(s)%1>-eval(s+'**0')%1

```

Try it online!
Try all testcases!

Basic idea: The expression is "Python 2 / 3 safe" iff both `a o1 b o2 c` and `a o1 b o2 1` is integer after evaluate.
> 5 votes

# Answer
# x86-64 machine code, ~~34~~ 33 bytes

```
B8 66 41 AD AC AC 24 07 9E 92 66 98 7A 0A 72 03 F6 E2 92 FF CF 7B EA B8 F6 F2 84 E4 74 F4 24 80 C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the length of the string (9) in RDI and its address in RSI, and returns a value in AL, 128 if the expression is Python 2/3 safe and 0 if not.

In assembly:

```
f:  .byte 0xB8

```

This will be explained later.

```
n:  .byte 0x66, 0x41, 0xAD

```

When jumping to `n`, the current number will be in DL.

This is a `lodsw` instruction, encoded in a strange way for reasons to be explained later. This loads two bytes from the string into AX, advancing the pointer; in particular, the operation symbol goes into AH.

```
    lodsb

```

Load another byte (a space) from the string into AL.

```
    lodsb

```

Load another byte (a digit) from the string into AL.

```
    and al, 7

```

Take the low three bits, obtaining the numerical value of the digit in AL.

```
    sahf

```

Set certain flags based on certain bits of AH, which contains the operation symbol. In particular:

```
      **PF** **CF**
+ 00101**0**1**1**
* 00101**0**1**0**
/ 00101**1**1**1**
```

```
    xchg edx, eax

```

Exchange registers.

```
    cbw

```

Sign-extend AL (previous number); this makes AH 0.

```
    jp d

```

Jump if PF=1, which is true only for `/`.

```
    jc t

```

Jump if CF is 1, which is true for `+` but not for `*`. An addition breaks a sequence of `*` and `/`, making the previous number irrelevant; the current number is correctly in DL.

Only `*` is left here.

```
    mul dl

```

Multiply AL (previous number) by DL (new digit).

```
s:  xchg edx, eax

```

Exchange registers. The product goes into DL.

```
t:  dec edi

```

(`+` joins here.) Subtract 1 from EDI.

```
    jpo n

```

Jump if the sum of the low 8 bits is odd. This is true the first two times, with 8 (1000₂) and 7 (111₂), but not true the third time, with 6 (110₂).

```
    .byte 0xB8

```

If we get here, the expression is Python 2/3 safe.

This subsumes the next two instructions into `mov eax, 0xE484F2F6`.

```
d:  div dl

```

(Recall that `/` jumps here.)

Divide AX by DL, putting the quotient in AL and the remainder in AH.

```
    test ah, ah

```

Set flags based on the value of AH.

```
    jz s

```

If the remainder is 0, jump (and next, exchange the quotient into DL and proceed).

Also, the success case joins here. In that case, the zero flag was last set by `dec edi`, which gave a nonzero result, so the jump is not taken.

```
    and al, 0x80

```

Keep the high bit of AL.

In the success case, the high bit is 1 from the `mov`.

In the failure case, AL is the quotient, which is at most 12 (from 25/2), so the high bit is 0.

```
    ret

```

Return.

---

Now, the start can be explained. The first byte 0xB8 subsumes the next four bytes into `mov eax, 0xACAD4166`. Those bytes include a `lodsw` instruction, which was encoded with a nonfunctional REX.B prefix (0x41) so that that value goes into AH. After that, the first digit is read by `lodsb`. The 0x41 value, which is in the same place as an operation symbol would be in later iterations, has a 1 in bit 0 and a 0 in bit 2, so it gets treated in the same way as a `+`, making the first digit alone become the current number.
> 4 votes

# Answer
# Haskell, 118 bytes

```
f.words
r=read
f(a:"/":b:t)|(q,m)<-r a`divMod`r b=m<1&&f(show q:t)
f(a:"*":b:t)=f$show(r a*r b):t
f(_:_:t)=f t
f _=1>0

```

Try it online!

Can certainly be outdone, but it's at least something. Core observation is simply that addition doesn't matter at all.
> 3 votes

# Answer
# Jelly, ~~9~~ 8 bytes

```
ḣƬ5ŒV€ĊƑ

```

Try it online!

Port of tsh's (old) JavaScript answer.

```
ḣ 5         Take the first 5 characters
 Ƭ          repeatedly while unique.
   ŒV€      Eval each result as Python.
      ĊƑ    Are they the same if ceiled?

```

# Jelly, 10 bytes

```
Ḥẹ¦”/ŒV=ŒV

```

Try it online!

Have been trying to think of an *interesting* solution, but a Python eval builtin is a Python eval builtin. Was at least interesting to golf, starting from `”/=kj”/,¹ŒV€E`.

```
Ḥ             Double the characters of the input
  ¦           at indices
 ẹ ”/         of slash.
     ŒV       Concatenate and eval as Python.
       =ŒV    Is it equal to the input evaluated as Python?

```
> 2 votes

# Answer
# Perl 5 `-p`, ~~38~~ 34 bytes

```
/. [\/*] ./;$_=(eval.eval$&)!~/\./

```

Try it online!

*Simplified regex since the input format is very strict to save bytes.*
> 2 votes

# Answer
# , ~~69~~ 68 bytes

Or **\>=4.1, 54 bytes** by replacing two `function` occurrences with `\`s.

*Edit: -1 byte thanks to @Dominic van Essen.*

```
function(s,`-`=function(x)eval(parse(t=x)))-s>-paste("`/`=`%/%`;",s)

```

Try it online!

Outputs inversed `TRUE`/`FALSE`.

Compares results of evaluating the expression and evaluating the expression with ``/`=`%/%`;` prepended (which redefines division to be integer division). My first approach to simply substitute `/` with `%/%` in the expression fails due to `%/%` having higher precedence than `/` and `*`.
> 2 votes

# Answer
# Bash, 52 bytes

Inspired by des54321's comment that said:

> I'm waiting for a competitive solution to this that isnt simply "eval the string as a python expression"

I decided to "cheat" even further by actually running both Python versions:

```
f(){ p=python;r=print\($1;$p\3<<<$r==`$p<<<$r\)`\);}

```

Try it online!

Simplified, it's essentially just doing:

```
f() { python3 <<< "print\($0 == `python <<< print\($0\)`\)"; }

```
> 2 votes

# Answer
# Wolfram Language (Mathematica): 24 65 Bytes

Realized my old code doesn't work, had to replace it with something more complicated. Also doesn't work on TIO. `e="Python"~ExternalEvaluate~#&;e@StringReplace[#,"/"->"//"]==e@#&`

Uses the same trick as the 10-byte Jelly answer, but is significantly longer due to Mathematica's ExternalEvaluate taking almost 30 bytes instead of 2.
> 1 votes

# Answer
# Julia 1.0, ~~46~~ 40 bytes

```
~x=eval(Meta.parse(x))%1>0
!s=~s|~s[1:5]

```

Try it online!

port of tsh's answer
> 1 votes

# Answer
# 05AB1E (legacy), 9 bytes

```
'/x.:‚.EË

```

Try it online or verify all test cases.

**Explanation:**

Uses the legacy version of 05AB1E for two reasons:

1. It's build in Python 3, and `.E` is therefore an 'Eval as Python' builtin, whereas the new 05AB1E version is build in Elixir and `.E` is an 'Eval as Elixir' builtin.
2. Double works on strings in the legacy version of 05AB1E, so we can use `x` instead of `„//` to save 2 bytes.

**Explanation:**

```
'/        '# Push string "/"
  x        # Double it (without popping): "//"
   .:      # Replace all "/" for "//" in the (implicit) input-string
     ‚     # Pair it with the implicit input-string
      .E   # Evaluate both as Python
        Ë  # Check if the results in the pair are the same
           # (after which the result is output implicitly)

```
> 1 votes

# Answer
# , ~~61~~ 59 bytes

(or 52 bytes in R≥4.1 using `\` instead of `function`)

```
function(s,t=48-s,u=t<2)!(t[1]*t[5]^(-1)^u[3]/t[9]^u[7])%%1

```

Try it online!

Checks 'by hand' without using `eval`. Input is list of codepoints.

---

# , 64 bytes

(or 57 bytes in R≥4.1 using `\` instead of `function`)

```
function(s,`$`=sapply)any(substring(s,1,3*2:3)$str2lang$eval%%1)
```

Attempt This Online!

`eval` approach, but different to that used by pajonk's R answer: here we check that both `"a o1 b "` and `"a o1 b o2 c"` are integers when evaluated as expressions in R, which uses `/` for floating-point division. Output is reversed (`TRUE` indicates NOT python 2/3 safe).
> 1 votes

# Answer
# TI-Basic, 44 bytes

```
Input Str1
"0
For(I,1,9,2
Ans+sub(Str1,I,1
End
fPart(expr(Ans)) or fPart(expr(Ans+"^0

```
* uses the same approach than tsh's answer: *The expression is "Python 2 / 3 safe" iff both `a o1 b o2 c` and `a o1 b o2 1` is integer after evaluate*
* spaces are significant in TI-Basic, they produce a `Syntax Error` if evaluated, so the loop keeps only the relevant characters (starting with an extra zero because an empty string is not possible
* `fPart` keeps the fractional part of a number
* outputs `1` for not safe and `0` for safe
> 1 votes

# Answer
# PARI/GP, 29 bytes

```
s->!(eval([s,Str(s"^0")])%1.)
```

Attempt This Online!

A port of tsh's JavaScript answer.

---

# PARI/GP, 48 bytes

```
s->eval(Str(s"=="strjoin(strsplit(s,"/"),"\\")))
```

Attempt This Online!

A port of Aiden Chow's Python answer.
> 0 votes

# Answer
# Retina 0.8.2, 73 bytes

```

\d
$*
^1+\+|[+*]1+$

1(?=1*\*(1+))|\*1+
$1
+r`^(\2)+/(1+)\b
$#1$*
^1+$

```

Try it online! Link includes test cases. Edit: After reading the question more carefully, code now parses according to input rules, saving 1 byte because only digits `1`..`5` need to be supported (code actually supports `1`..`9`) but adding 3 bytes to delete spaces. Explanation:

```

```

Delete spaces.

```
\d
$*

```

Convert to unary.

```
^1+\+|[+*]1+$

```

Delete any additions and trailing multiplications as they have no effect.

```
1(?=1*\*(1+))|\*1+
$1

```

If there's still a multiplication left then perform it now.

```
+r`^(\2)+/(1+)\b
$#1$*

```

Perform divisions from left to right where possible.

```
^1+$

```

Check that all the divisions succeeded.
> 0 votes

# Answer
# Charcoal, 34 bytes

```
¹Ｎθ≡Ｓ/«Ｎζ¿﹪θζ⎚≧÷ζθ»+Ｎθ≧×Ｎθ≡Ｓ/¿﹪θＮ⎚

```

Try it online! Link is to verbose version of code. Allows any sized integer inputs but only two space-separated operations and outputs a Charcoal boolean i.e. `-` for safe, nothing for unsafe. Explanation:

```
¹

```

Assume that the expression is safe.

```
Ｎθ

```

Input the first integer.

```
≡Ｓ

```

Switch over the first operator.

If it's a `/`, then:

```
Ｎζ

```

Input the second integer.

```
¿﹪θζ⎚

```

If the second integer does not divide the first then clear the canvas.

```
≧÷ζθ»

```

Otherwise divide the second integer by the first.

```
+Ｎθ

```

If the first operator is a `+` then ignore the first integer and input the second integer.

```
≧×Ｎθ

```

Otherwise input the second integer and multiply the first integer by it. (This case is chosen as the default case because it can't parse as an expression.)

```
≡Ｓ/

```

If the second operator is a `/`, then...

```
¿﹪θＮ⎚

```

... if the third integer does not divide the current total then clear the canvas.
> 0 votes

# Answer
# MATLAB, 72 bytes

```
function p(i),eval(i);eval(regexprep(['x=' i],'(\d)','int8($1)'));ans==x

```

pretty boring, eval the string as doubles and then again as integers. If the expression is different as an integer, then yeah. I don't know python, but I can guess how it works.

Try it online!
> -1 votes

---
Tags: code-golf, decision-problem, parsing
---


# Question
Title: Random Point from a 2D Donut Distribution
A donut distribution (for lack of a better term) is a random distribution of points in a 2-dimensional plane, forming a donut-like shape. The distribution is defined by two parameters: the radius `r` and spread `s`, in which the distance to the origin follows a normal (Gaussian) distribution around `r`, with a standard deviation `s`. The angular distribution is uniform in the range `[0,2π)`.

## The challenge

Given a radius `r` and spread `s`, your code should yield the Cartesian (`(x,y)`) coordinates of a single point chosen from this distribution.

## Remarks

* Running your code multiple times with the same input should result in the specified distribution.
* Outputting polar coordinates is too trivial and not allowed.
* You can output Cartesian coordinates in any way allowed by the default I/O rules.
    + This includes complex values.

## Valid approaches

Several algorithms can be used to yield the desired distribution, including but not limited to

1. Choose `a` from the uniform distribution `[0,2π)` and `b` from the normal distribution `(r,s)`.
Let `x = b*cos(a)` and `y = b*sin(a)`.
2. Choose `a` from the uniform distribution `[0,4)` and `b` from the normal distribution `(r,s)`.
Let `x+y*i = b*i^a`.
3. Choose `a,b,c` all from the normal distribution `(0,1)`.
Let `d = a+b*i` and `x+y*i = d/abs(d) * (c*s+r)`.

## Example distributions (N=1000)

`Below: r=1, s=0.1`

`Below: r=3, s=1`

`Below: r=1, s=0`

`Below: r=100, s=5`

# Answer
> 8 votes
# APL(Dyalog Unicode), 38 bytes SBCS

Takes `r` on the left and `s` on the right and returns a complex number.

```
{(⍺+⍵×(.5*⍨¯2×⍟?0)×1○○2×?0)×¯12○2×○?0}

```

Try it on APLgolf!

Uses the first approach presented in the question. Dyalog doesn't have a builtin for sampling from a normal distribution, so this uses the Box–Muller transform to convert to random numbers from \\$(0,1)\\$ to a normally distributed value:

`(⍺+⍵×(.5*⍨¯2×⍟?0)×1○○2×?0)` draws a normally distributed value \\$b \sim N(\alpha, \omega^2)\\$:
`?0` random number \\$c \in (0,1)\\$
`1○○2×?0`: \\$\sin(2\pi c)\\$
`?0` random number \\$d \in (0,1)\\$
`.5*⍨¯2×⍟?0`: \\$\sqrt{-2\ln{d}}\\$
`⍺+⍵×` Scale from \\$N(0, 1)\\$ to \\$N(\alpha, \omega^2)\\$

`?0` generates a random number \\$a \in (0,1)\\$
`¯12○2×○?0`: \\$e^{i 2\pi a} = \sin(2\pi a)i + cos(2\pi a)\\$

The product of these two values is the result.

Plotting code and images:

```
'InitCauseway' ⎕CY 'sharpplot'
InitCauseway ⍬
sp←⎕NEW Causeway.SharpPlot(700)
sp.SetTrellis(2 2)
sp.TrellisStyle←4

F ← {(⍺+⍵×(.5*⍨¯2×⍟?0)×1○○2×?0)×¯12○2×○?0}

:For r s :In (1 0.1)(3 1)(1 0)(100 5)
    sp.NewCell
    sp.Heading←'r = ',(⍕r),'; s = ',⍕s
    sp.SetAxesScales(1)
    sp.DrawScatterPlot↓9 11∘.○{r F s}¨⍳1000
:EndFor

sp.SaveSvg(⊂'plot.svg')

```

# Answer
> 8 votes
# MATL, 10 bytes

```
Xr*+Jr4*^*

```

Inputs are `r`, then `s`. Output is a complex number.

**Try it online!** Or see the plot for 1000 points at **MATL Online**! (it takes 10‒15 seconds).

### How it works

Uses method 2 described in the challenge.

```
Xr   % Push random number with standard Gaussian distribution
*    % Implicit input: r. Multiply
+    % Implicit input: s. Add
J    % Push imaginary unit
r    % Push random number with stantard uniform distribution
4    % Push 4
*    % Multiply
^    % Power
*    % Multiply. Implicit output

```

# Answer
> 7 votes
# Factor, 56 bytes

```
[ normal-random-float 2pi random 2dup cos * -rot sin * ]

```

Try it online!

Verifying correctness:

## Explanation

```
                      ! 1 0.1
normal-random-float   ! 1.091729295255315
2pi                   ! 1.091729295255315 6.283185307179586
random                ! 1.091729295255315 4.669140230445313
2dup                  ! 1.091729295255315 4.669140230445313 1.091729295255315 4.669140230445313
cos                   ! 1.091729295255315 4.669140230445313 1.091729295255315 -0.04323526873134136
*                     ! 1.091729295255315 4.669140230445313 -0.04720120946224146
-rot                  ! -0.04720120946224146 1.091729295255315 4.669140230445313
sin                   ! -0.04720120946224146 1.091729295255315 -0.9990649185802335
*                     ! -0.04720120946224146 -1.090708439475907

```

# Answer
> 6 votes
# , 40 bytes

```
function(r,s)rnorm(1,r,s)*1i^runif(1,,4)

```

Try it online! or plot the results at rdrr.io

# Answer
> 5 votes
# Wolfram Language (Mathematica), 42 bytes

```
Re[#+#2√Log[16/r^2]I^r]I^r&
r:=4Random[]

```

Try it online!

`RandomVariate@NormalDistribution` is costly (and, as noted by Ben Izd, doesn't work with stdev=0), so this uses Box-Muller to generate a normal distribution from two uniform ones.

Sample distributions (N=10000):

# Answer
> 5 votes
# Julia 1.0, 26 bytes

```
r\s=(randn()s+r)im^4rand()

```

Try it online!

uses the second formula. output is a complex number. `randn` gives a random number from a normal distribution (0,1), and `rand` from a uniform distribtion in \[0,1)

1000 points from `10\1`:

# Answer
> 3 votes
## Mathematica - 108 bytes

Following the first method, we could have:

```
fn=AngleVector/@RandomVariate[ProductDistribution[NormalDistribution[#,#2],UniformDistribution[{0,2Pi}]],1000]&;

```

then visualize it by:

```
visualize =
  Graphics[{PointSize[.01], Point[fn[#, #2]]}, Frame -> True] &;

```

`r=1, s=0.1`:

`r=3, s=1`:

`r=100, s=5`:

Notes:

* `Variance: 0` in `NormalDistribution` is not supported (could be hacked by having a small number)

# Answer
> 3 votes
# Python 2, 58 bytes

Might not be the shortest, but here is the base-case for python i guess.

Outputs a complex number:

```
lambda r,s:1j**uniform(0,4)*gauss(r,s)
from random import*

```

Try it online!

# Answer
> 3 votes
# , 45 bytes

```
function(r,s)exp(runif(1)*2i*pi)*rnorm(1,r,s)

```

Try it online!

Uses the first method in the description, of course using the neat fact that \\$e^{i\theta}=\cos(\theta)+i\sin(\theta)\\$. Longer than Dominic van Essen's answer by 5 bytes, though.

# Answer
> 3 votes
# Java 17, 127 bytes

```
(r,s)->{double a=new java.util.Random().nextGaussian(r,s),b=Math.random()*Math.PI*2;return new P(a*Math.cos(b),a*Math.sin(b));}

```

This is a `BiFunction<Double, Double, P>` where P is a `record P(double x, double y) {}`

# Answer
> 3 votes
# Desmos, ~~80~~ ~~70~~ 68 bytes

```
b=random(1,t)τ
f(r,s,t)=(normaldist(r,s).random(1,t)(cosb,sinb))[1]

```

Takes an extra argument `t` as the seed, which is the only way to re-use the function to get different samples without pressing the randomize button.

Try it on Desmos!

*-10 bytes thanks to Aiden Chow*

*-2 bytes thanks to emanrescu A (`\tau` to `τ`)*

All functions in Desmos are pure, so they can't return a different value when evaluated at different times, even in a list comprehension. This causes an issue with the CGSE policy of functions being re-usable.

There's a randomize button to re-seed all of the random seed-dependent function calls: . This doesn't vibe with me because it requires user interaction to re-seed, but it would allow the following 53-byte submission:

```
b=random()τ
f(r,s)=(cosb,sinb)normaldist(r,s).random

```

In this submission, I opted to take the random seed as an extra argument, which is a common design decision in Desmos if a program needs to avoid user action when re-seeding. This is the only way to get different outputs from random functions without the user pressing the randomize button.

# Answer
> 1 votes
# 05AB1E, 36 bytes

```
9°©D(ŸDÄ®>αÅ1*˜Ω®/*+žq·®*ÝΩ®/DÅ¾sÅ½‚*

```

Inputs in the order \\$r,s\\$.

Try it online. (With the `9` replaced with `3` so it won't time out.)

**Explanation:**

Uses the first method described in the challenge description.

However, 05AB1E lacks a Gaussian distribution random builtin, as well as a builtin to get a random decimal number given a range. Both of those are therefore done manually.

```
9°©D(ŸDÄ®>αÅ1*˜Ω®/ # Push a random value with Gaussian distribution within the
                   # range [-1,1]:
9°                 #  Push 1,000,000,000 (10**9)
  ©                #  Store it in variable `®` (without popping)
   D               #  Duplicate it
    (              #  Negate the copy
     Ÿ             #  Pop both and push an integer-list list in the range
                   #  [-1000000000,1000000000]
      D            #  Duplicate this list
       Ä           #  Get the absolute value of each in the copy
        ®>α        #  Get the absolute difference between each and `®`+1
           Å1      #  Map each inner value to a list of that many 1s
             *     #  Multiply each to the values at the same positions in the
                   #  remaining list
              ˜    #  Flatten this list of lists
               Ω   #  Pop and push a random integer
                ®/ #  Divide it by `®`
*+                 # Use the inputs to transform it into s*random+r:
*                  #  Multiply it to the (implicit) input `s`
 +                 #  Add the (implicit) input `r`
žq·®*ÝΩ®/          # Push a random value with uniform distribution within the
                   # range [0,2π):
žq                 #  Push builtin PI: 3.141592653589793
  ·                #  Double it to get tau: 6.283185307179586
   ®*              #  Multiply it by `®`
     Ý             #  Pop and push an integer list in the range [0,2π®]
      Ω            #  Pop and push a random integer from this list
       ®/          #  Divide it by `®`
DÅ¾sÅ½‚*           # Calculate the resulting [x,y] pair using the two random
                   # values:
D                  #  Duplicate it
 Å¾                #  Pop and push its cosine
   s               #  Swap so the random value is at the top again
    Å½             #  Pop and push its sine
      ‚            #  Pair them together
       *           #  Multiply both to the earlier random value
                   # (after which the result is output implicitly)

```

---
Tags: code-golf, math, arithmetic, geometry, random
---


title: Adding without using a + or - sign

text:
# Question
Title: Adding without using a + or - sign
There have been many "Do \__ without *_*\_" challenges before, but I hope that this is one of the most challenging.

## The Challenge

You are to write a program that takes two natural numbers (whole numbers \> 0) from STDIN, and prints the sum of the two numbers to STDOUT. The challenge is that you must use as few `+` and `-` signs as possible. You are not allowed to use any sum-like or negation functions.

**Examples**

input

```
123
468

```

output

```
591

```

input

```
702
720

```

output

```
1422

```

**Tie Breaker:** If two programs have the same number of `+` and `-` characters, the winner is the person with fewer `/` `*` `(` `)` `=` `.` `,` and `0-9` characters.

**Not Allowed:** Languages in which the standard addition/subtraction and increment/decrement operators are symbols other than `+` or `-` are not allowed. This means that Whitespace the language is not allowed.

# Answer
> 37 votes
## Perl (no +/-, no tie-breakers, 29 chars)

```
s!!xx!;s!x!$"x<>!eg;say y!!!c

```

As a bonus, you can make the code sum more than two numbers by adding more `x`s to the `s!!xx!`.

Alternatively, here are two 21-char solutions with 1 and 3 tie-breakers respectively

```
say length$"x<>.$"x<>

say log exp(<>)*exp<>

```

Note: These solutions use the `say` function, available since Perl 5.10.0 with the `-E` command line switch or with `use 5.010`. See the edit history of this answer for versions that work on older perls.

---

How does the solution with no tie-breakers work?

* `s!!xx!` is a regexp replacement operator, operating by default on the `$_` variable, which replaces the empty string with the string `xx`. (Usually `/` is used as the regexp delimiter in Perl, but really almost any character can be used. I chose `!` since it's not a tie-breaker.) This is just a fancy way of prepending `"xx"` to `$_` — or, since `$_` starts out empty (undefined, actually), it's really a way to write `$_ = "xx"` without using the equals sign (and with one character less, too).
* `s!x!$"x<>!eg` is another regexp replacement, this time replacing each `x` in `$_` with the value of the expression `$" x <>`. (The `g` switch specifies global replacement, `e` specifies that the replacement is to be evaluated as Perl code instead of being used as a literal string.) `$"` is a special variable whose default value happens to be a single space; using it instead of `" "` saves one char. (Any other variable known to have a one-character value, such as `$&` or `$/`, would work equally well here, except that using `$/` would cost me a tie-breaker.)

The `<>` line input operator, in scalar context, reads one line from standard input and returns it. The `x` before it is the Perl string repetition operator, and is really the core of this solution: it returns its left operand (a single space character) repeated the number of times given by its right operand (the line we just read as input).
* `y!!!c` is just an obscure way to (ab)use the transliteration operator to count the characters in a string (`$_` by default, again). I could've just written `say length`, but the obfuscated version is one character shorter. :)

# Answer
> 54 votes
# R (24 characters)

```
length(sequence(scan()))

```

What this does:

* `scan` reads input from STDIN (or a file)
* `sequence` generates integer sequences starting from 1 and concatenates the sequences. For example, `sequence(c(2, 3))` results in the vector `1 2 1 2 3`
* `length` calculates the number of elements in the concatenated vector

Example 1:

```
> length(sequence(scan()))
1: 123
2: 468
3:
Read 2 items
[1] 591

```

Example 2:

```
> length(sequence(scan()))
1: 702
2: 720
3:
Read 2 items
[1] 1422

```

# Answer
> 18 votes
## D

```
main(){
    int a,b;
    readf("%d %d",&a,&b);
    while(b){a^=b;b=((a^b)&b)<<1;}
    write(a);
}

```

bit twiddling for the win

as a bonus the compiled code doesn't contain a add operation (can't speak for the readf call though)

# Answer
> 13 votes
# Python 2, 43 bytes

```
print len('%s%s'%(input()*'?',input()*'!'))

```

# Answer
> 10 votes
# Seed, ~~3904~~ ~~3846~~ 11 bytes, 0 +/-, 10 tie breakers

```
4 141745954

```

# Answer
> 8 votes
C (32bit only)

```
int main(int ac, char *av) {
    scanf("%d\n%d", &ac, &av);
    return printf("%d\n", &av[ac]);
}

```

Pointer arithmetic is just as good.
How does it match the requirements?
* No `+` or `-`
* No `/`, `=`, `.`, `0`-`9`
* Only 3 pairs of parenthesis, which seems to me minimal (you need `main`, `scanf`, `printf`).
* One `*` (the pointer approach requires it).
* Four `,` (could save one by defining normal variables, not `ac,av`)

# Answer
> 8 votes
## C++ 0 +/-, 3 tie-breakers

```
#include <vector>
#include <iostream>

#define WAX (
#define WANE )
#define SPOT .

int main WAX WANE {
    unsigned x;
    unsigned y;
    std::cin >> x >> y;
    std::vector<int> v WAX x WANE;
    std::vector<int> u WAX y WANE;
    for WAX auto n : u WANE {
        v SPOT push_back WAX n WANE;
    }
    std::cout << v SPOT size WAX WANE;
}

```

# Answer
> 7 votes
### GolfScript

No +/- or tie-breakers:

```
# Twiddle some bits to get a few small integers
[]!~abs:two~abs:three!:zero~:minusone;

~[two base minusone%\two base minusone%]zip
zero:c;
{
    # Stack holds [x y] or [x] with implicit y is zero
    # Half adder using x y c: want to end up with sum on stack and carry back in c
    [~c zero]three<zero$
    ~^^\
    $~;:c;;
}%
[~c]minusone%two base

```

Much simpler version with two tie-breaker characters, using the same list-concatenation trick that other people are using:

```
~[\]{,~}%,

```

I'm assuming that GolfScript isn't disqualified for having `)` as an increment operator, as I'm not actually using it.

# Answer
> 6 votes
# Haskell, 0+2

```
import Monad
main = join $ fmap print $ fmap length $ fmap f $ fmap lines getContents
f x = join $ flip replicate [] `fmap` fmap read x

```

This uses no `+` or `-` characters, and only two `=` from the set of tie breaker characters, one of which is mandatory for binding `main`. The sum is done by concatenating lists of the appropriate lengths.

# Answer
> 6 votes
I didn't see anyone do it the Electrical Engineering way, so here's my take (in ruby):

```
def please_sum(a, b)
    return (a&b !=0)? please_sum( ((a&b)<<1) , a^b ):a^b
end

```

It is a little bit ugly, but it gets the job done. The two values are compared by a bitwise `AND`. If they don't have any bits in common, there is no "carry" into the next binary column, so the addition can be completed by bitwise `XOR`ing them. If there is a carry, you have to add the carry to the bitwise `XOR`. Here's a little ruby script I used to make sure my digital logic was not too rusty:

```
100.times do
    a=rand 10
    b=rand 10
    c=please_sum(a,b)
    puts "#{a}+#{b}=#{c}"
    end

```

Cheers!

# Answer
> 5 votes
**EDIT** This was posted BEFORE the rules changed to disallow `sum`...

The R language: No calls to `+` or `-`... And 9 tie-breaker characters!

```
sum(as.numeric(readLines(n=2)))

```

Example:

```
> sum(as.numeric(readLines(n=2)))
123
456
[1] 579

```

The `[1] 579` is the answer 579 (the `[1]` is to keep track of where in the result vector your are since in R all values are vectors - in this case of length 1)

Note that R has `+` operators just like most languages - it just so happens that it has `sum` too that sums up a bunch of vectors.

In this case, `readLines` returns a string vector of length 2. I then coerce it to numeric (doubles) and sum it up...

Just to show some other features of R:

```
> 11:20 # Generate a sequence
 [1] 11 12 13 14 15 16 17 18 19 20

> sum(1:10, 101:110, pi)
[1] 1113.142

```

# Answer
> 5 votes
# The R language

New rules, new answer, same language. No calls to `+` or `-`

**UPDATE** Using `scan`, it drops to 11 tie-breaker characters (and 27 characters in all).

```
as.numeric(scan())%*%c(1,1)

```

Original: 13 tie-breaker characters!

```
as.numeric(readLines(n=2)) %*% c(1,1)

```

Example:

```
> as.numeric(readLines(n=2)) %*% c(1,1)
123
456
     [,1]
[1,]  579

```

This time the result is achieved by matrix multiplication. The answer is displayed as a 1x1 matrix.

# Answer
> 5 votes
# Haskell, 0 `+`/`-`, ~~6~~ 2 tie-breakers (`=`)

## (does not use the string/list concatenation trick)

```
main = interact f
f x = show $ log $ product $ map exp $ map read $ lines x

```

# Answer
> 5 votes
# 05AB1E, 2 4 bytes, 0 `+`/`-`

```
F>

```

Try it online!

Apologies if I misunderstood this challenge, but I was surprised there was no 05AB1E answer. Shortest answer in this language I could come up with that doesn't use + or the built in sum function.

Explanation:

```
 F   #Loop A many times
  >  #Increment B
     #(Implicit output)

```

*-2 Bytes thanks to Grimy.*

# Answer
> 5 votes
# Python 3, 64 62 bytes

Without relying on hidden summations in other functions.

```
x=int(input());y=int(input())
while y:x,y=x^y,(x&y)*2
print(x)

```

Try it online!

# Answer
> 5 votes
# Excel, ~~(25, 8) (22, 6)~~ 13, 4 tie-breakers

Inputs are `A1`, `A2`.

```
=2*MEDIAN(A:A
^^^      ^

```

Because `MEDIAN` is shorter than `AVERAGE` and `AGGREGATE`.

# Answer
> 4 votes
## Javascript (17 tie-breaker characters)

```
eval('걢갽거걲걯걭거건갨걡갽거걲걯걭거건갨걹갽걦걵걮걣건걩걯걮갨걡갩걻걣갽걮걥걷갠걕걩걮건갸걁걲걲걡걹갨걡갩갻걦걯걲갨걩갠걩걮갠걣갩걩걦갨걩갽갽걾걾걩갩걸갮거걵걳걨갨갱갩걽갬걸갽걛걝갩갩갻걹갨걡갩갻걹갨걢갩갻걡걬걥걲건갨걸갮걬걥걮걧건걨갩갻'['split']('')['map'](function(_){return String['fromCharCode'](_['charCodeAt'](~~[])^0xac00)})['join'](''))

```

:P ("Obfuscated" to reduce number of tie-breaker characters. Internally, it's `b=prompt(a=prompt(y=function(a){c=new Uint8Array(a);for(i in c)if(i==~~i)x.push(1)},x=[]));y(a);y(b);alert(x.length);` .)

# Answer
> 4 votes
**Javascript, 56**

```
p=prompt;alert(Array(~~p()).concat(Array(~~p())).length)

```

Thanks to @JiminP on the ~~ tip! I'm going for least bytes, so the 1 byte saving on the p=prompt; is still worth it. I understand your argument about tie-breaker chars, but to be honest wouldn't you rather the least bytes :-p

**Version, 69**

```
i=parseInt;p=prompt;alert(Array(i(p())).concat(Array(i(p()))).length)

```

Thanks to some feedback from @Ilmari and @JiminP, I've shaved 13 bytes off my original solution.

*Originally, 82*

```
i=parseInt;p=prompt;a=Array(i(p()));a.push.apply(a, Array(i(p())));alert(a.length)

```

# Answer
> 4 votes
## C

```
b[500];i;j;main(){scanf("%d%d",&i,&j);printf("%d\n",sprintf(b,"%*s%*s",i,"",j,""));

```

# Answer
> 4 votes
## APL (no +/-, no tie breakers, 8 or 10 characters)

This entry is similar to the other ones that concatenate sequences generated from the input and find the length... but it's in APL, which can appear confusing even for a small problem like this. I used Dyalog APL, which offers a free educational license.

Code:

```
⍴⊃⍪⌿⍳¨⎕⎕

```

From right to left:

* Each quote-quad (  ) requests input from the user and evaluates it.
* The each operator ( `¨` ) applies the index generator function (  ) to each of the items in the array to its right.
* This flattens the resulting array of arrays into one array. The input array is reduced to a flat list by the reduction operator ( `/` ), which folds the array using the concatenation function ( `,` ). For the sake of this challenge, the one-dimensional reduction operator (  ) is used, along with the concatenation operator along the first axis (  ).
* As a result of using the reduction operator, the array is *enclosed*, which is like placing it in the bag; all we see on the outside is a bag, not its contents. The disclose operator (  ) gives us the contents of the enclosed array (the bag).
* Finally, the shape-of function (  ) gives us the lengths of the dimensions of an array. In this case, we have a one-dimensional array, so we obtain the number of items in the array, which is our result.

If we need to explicitly output the result, we can do so like this:

```
⎕←⍴⊃⍪⌿⍳¨⎕⎕

```

Comparable Python code, with corresponding APL symbols above:

```
import operator

⎕←     ⍴    ⌿        ⍪                 ¨              ⍳                ⎕        ⎕         ⊃
print (len (reduce (operator.__add__, [map (lambda n: range (1, n+1), [input(), input()])][0])))

```

I'd like to know if there's a shorter version possible in APL - another, simpler version I came up with that has more tie breakers (although still at 8 characters) is: `⍴(⍳⎕),⍳⎕`.

# Answer
> 4 votes
# Befunge-93, 0 `+-` characters, 0 tiebreakers, 33 bytes

```
"e:"%"X:"%::%p"h:"%"Y:"%::%p&&  @

```

Try it online!

### Explanation

Like @negative seven's Befunge answer, we generate `+` and `.` at runtime and put them onto the field to be executed. However, Befunge-93 does not include the `y` instruction, so we abuse the `%` modulo operator instead.

```
"e:"%                                            # Calculate 101 ('e') mod 58 (':') to get 43 ('+')
     "X:"%                                       # Calculate 88 ('X') mod 58 to get 30
          ::%                                    # Calculate 30 mod 30 to get 0
             p                                   # Put character 43 ('+') at position (30, 0)
              "h:"%                              # Calculate 104 ('h') mod 58 to get 46 ('.')
                   "Y:"%                         # Calculate 89 ('Y') mod 58 to get 31
                        ::%                      # Calculate 31 mod 31 to get 0
                           p                     # Put character 46 ('.') at position (31, 0)
                            &&                   # Get two numbers from STDIN
                              (changed to '+')   # Add the numbers together
                               (changed to '.')  # Output the result
                                @                # End the program

```

# Answer
> 4 votes
# Scala 2.12, 20 bytes, 0 +/- signs

```
readInt\u002breadInt

```

The unicode literal is just turned into a `+` before compilation

# Answer
> 4 votes
# Vyxal `as`, 0 bytes

Try it Online!

The `a` flag takes newline separated inputs as a list, and the `s` flag sums the top of the stack.

# Non-trivial `a`, ~~4~~ 2 bytes

*-2 bytes because I realized the challenge guarantees 2 number input.*

```
ṁd

```

Try it Online!

Explanation:

```
    # 'a' flag - take newline separated inputs as a list
ṁ   # Mean of inputs
 d  # Multiply by 2
    # Implicit output

```

Effectively calculates `((a + b) / 2) * 2`, which is equivalent to `a + b`. The previous version worked for any amount of numbers, but it turns out the challenge specifies taking 2 numbers as input, so this works fine.

# Answer
> 2 votes
## Shell, 52

```
read a
read b
(seq 1 $a;seq 1 $b)|wc|awk '{print$1}'

```

This is basically the same answer I gave for another problem.

# Answer
> 2 votes
## C

```
a,b;A(int a,int b){return a&b?A(a^b,(a&b)<<1):a^b;}
main(){scanf("%d%d",&a,&b);printf("%d\n",A(a,b));}

```

# Answer
> 2 votes
**C#**

It's not the shortest by any stretch:

```
private static int getIntFromBitArray(BitArray bitArray)
{
    int[] array = new int[1];
    bitArray.CopyTo(array, 0);
    return array[0];
}

private static BitArray getBitArrayFromInt32(Int32 a)
{
    byte[] bytes = BitConverter.GetBytes(a);
    return new BitArray(bytes);
}

static void Main(string[] args)
{
    BitArray first = getBitArrayFromInt32(int.Parse(Console.ReadLine()));
    BitArray second = getBitArrayFromInt32(int.Parse(Console.ReadLine()));
    BitArray result = new BitArray(32);

    bool carry = false;
    for (int i = 0; i < result.Length; i++)
    {
        if (first[i] && second[i] && carry)
        {
            result[i] = true;
        }
        else if (first[i] && second[i])
        {
            result[i] = false;
            carry = true;
        }
        else if (carry && (first[i] || second[i]))
        {
            result[i] = false;
            carry = true;
        }
        else
        {
            result[i] = carry || first[i] || second[i];
            carry = false;
        }
    }
    Console.WriteLine(getIntFromBitArray(result));
}

```

# Answer
> 2 votes
# J, ~~15~~ 7 chars, 1 tie breaker, incomplete program

This is my J attempt. It is not a full program, because I have not yet figured out how to write one. Just put that line in a script to get the function `p` that can be used for adding an arbitrary amount of numbers. It is a monad and takes a list of numbers to add (such as `p 1 2 3 4`):

```
p=:#@#~

```

The idea is very simple. The function is written in tacit aka pointless style. Here is a pointed definition:

```
p=:3 :'##~y'

```

Read from right to left. In the tacit version, `@` composes the parts of the function. (like a ∘ in mathematics \[(f∘g)(x) = f(g(x)\])

* `y` is the parameter of `p`.
* `~` makes a verb reflexive. For some verb `m`, `m~ a` is equal to `a m a`.
* `#` (copy, `a#b`): Each element in `a` is replicated `i` times, where `i` is the element at the same index as the current element of `a` of `b`. Thus, `#~` replicates an item `n` `n` times.
* `#` (count, `#b`): Counts the number of elements in `b`.

Conclusion: J is awsome and less readable than Perl (that makes it even more awsome)

## Edits

* 15 -\> 7 using `#` instead of `i.`. Yeah! Less chars than golfscript.

## More of a program

This one queries for input, but it still isn't a full program: (13 chars, 3 breakers)

```
##~".1!:1<#a:

```

# Answer
> 2 votes
# C#,

Program works on 1 line; separated on multiple lines to avoid horizontal scrolling.

```
using C=System.Console;
class A{
static void Main(){
int a,b,x,y;
a=int.Parse(C.ReadLine());
b=int.Parse(C.ReadLine());
do{x=a&b;y=a^b;a=x<<1;b=y;}while(x>0);
C.WriteLine(y);
}}

```

# Answer
> 2 votes
# Zsh, ~~26~~ 25 bytes, ~~7~~ 5 tiebreakers

-1 byte, -2 tiebreakers thanks to @Nahuel Fouilleul.

```
set {1..$1} {1..$2}
<<<$#

```

Try it online!

---

# Zsh, ~~62~~ 60 bytes, 0 tiebreakers

-2 bytes because `repeat foo` evaluates `foo` in arithmetic mode.

```
read a b
{repeat a;printf x;repeat b;printf x}|read x
<<<$#x

```

Try it online!

# Answer
> 2 votes
# C++, () only for `main`

```
#include <iostream>

int main()
{
    unsigned int a, b;
    std::cin >> a;
    std::cin >> b;

    unsigned int p = a ^ b;
    unsigned int g = a & b;

    unsigned int gg {g | p & g << 1};
    unsigned int pp {p & p << 1};

    unsigned int ggg {gg | pp & gg << 2};
    unsigned int ppp {pp | pp << 2};

    unsigned int gggg {ggg | ppp & ggg << 4};
    unsigned int pppp {ppp & ppp << 4};

    unsigned int ggggg {gggg | pppp & gggg << 8};
    unsigned int ppppp {pppp | pppp << 8};

    unsigned int gggggg {ggggg | ppppp & ggggg << 16};

    unsigned int result {a ^ b ^ gggggg << 1};
    std::cout << result;
}

```

Assumes 32-bit unsigned ints. Very ugly code to remove tiebreak characters. Emulates a Kogge-Stone adder.

# Answer
> 2 votes
# Octave/MATLAB, 37 bytes

```
f=@()e^(input(''));disp(log(f()*f()))

```

Try it online!

# Answer
> 2 votes
# Python 3

```
import numpy as n;i=lambda:n.e**int(input());print(int(n.log(i()*i())))

```

Try it online!

# Answer
> 2 votes
# Gol\>\<\>, 8 bytes

```
IRmIRmlh

```

Minus one byte!, I figured out that I didn't need to take both inputs first

Try it online!

**Previous answer, 9 bytes**

```
IIRfrRflh

```

Explanation below

```
II        take both inputs
  Rm      Pop and repeat that number of times, pushing -1
    r     Reverse stack (to get the first num on top)
     Rm   Pop and repeat that number of times, pushing -1
       lh Push length of stack, and output as a number halting

```

Basically what I did was count it all out in unary, it would only take a few more bytes to expand it to be able to handle more than two numbers

Try it online!

# Answer
> 2 votes
# JavaScript (ES6), 48 bytes, 12 tie-breakers

```
a=>b=>"0".repeat(a).concat("0".repeat(b)).length

```

# Answer
> 2 votes
# JavaScript, 26 bytes

## Tiebreakers: 11?

```
a=>b=>Math.log2(2**a*2**b)

```

Takes input as `(a)(b)`. Uses the power index rule \\$a^{x+y}=a^{x}a^{y}\\$ and returns the \\$log\_2(2^{a}2^{b})\\$ which is basically \\$log\_2(2^{a+b}) = a+b\\$.

# Answer
> 2 votes
# Pip, 0 +/-, 0 tiebreakers (5 bytes)

```
#JoXg

```

Try it online!

### Explanation

A string-concatenation approach:

```
    g  List containing the command-line args
  oX   For each arg, make a string of that many 1s (o is a variable preinitialized to 1)
 J     Join the list into a single string
#      Get its length

```

# Answer
> 2 votes
# Python 2, 0 +/-, 2 tie-breaker (144 bytes)

```
exec`["%c"%[ord(i)^True<<True<<True<<True][False]for i in"""xzaf| :""afx}| !":""afx}| !'':!&ja|Wdmfo|` !"""]`[True<<True::True<<True<<True|True]

```

Try it online!

### How it works :

The general idea is to remove tie-breaker character of a non cheaty working solution. To do that I converted a solution by changing the 5th bit of each character.

Some tricks are used to avoid using tiebreaker character during the translation :

* `True` and `False` are evaluated by python as 1 and 0. Using that I can easyly create some usefull integers like 2, 5 and 8 in my solution without using `[0-9]`
* Parenthesis are bad (for this challenge at least). To replace them I used `[expression][False]` which return the first element of an 1-element array, using the \[\]-priority over other operators.
* To join an array of char, the common technique is to use `"".join(my_array)` but it uses 3 tie-breakers. I instead uses ``my_array`[2::5]` which take the representation of the array and select only the wanted character by concatenating them.
* To get the ascii character from its interger representation, intead of using the built-in `chr(i)` (which uses 2 tie-breaker), I used `"%c"%i` wich does the same

In better understandable python, here is my solution :

```
exec`["%c"%(ord(i)^8)for i in""" CODED_SOLUTION """]`[2::5]

```

with `CODED_SOLUTION` once decoded :

```
print(2*input()*2**input()//2).bit_length()

```

which looks like my older solution (and which doesn't use any form of addition :p)

## Older Solution (7 tiebreaker, 50 bytes)

```
print int.bit_length(True<<input()<<input()>>True)

```

Try it online!

The idea is to shift a `True` interpreted as `1` by python Xtimes and Ytimes then shift once the other way and take the len of the binary representation

## Cheated solution (45 bytes, 6 Tie-breaker)

I also have a cheated solution in 45 bytes:

```
print eval("\x2binput()"*[True<<True][False])

```

Try it online!

which evaluates the string `+input()+input()` but convert the char `+` by its hexadecimal representation.

the `[True<<True][False]` is equal to 2

## Other Ideas:

I had the idea to use `a=abs(~a)` to increment a by 1 but I didn't totaly managed to produce a working solution with that.

# Answer
> 2 votes
# Python 3, 0 +/-, 2 Tie-breaker, (68 bytes)

```
lambda x,y:A[f"{True<<x<<y:b}"[True:]]
class A:__class_getitem__=len

```

Try it online!

`class A:__class_getitem__=len` allows me to replace `len(x)` by `A[x]`

## Old, 3 Tie-breaker, (40 bytes)

```
lambda x,y:len(f"{True<<x<<y:b}"[True:])

```

Try it online!

## Explanation :

* `True`in python is evaluated as 1 =\> `1`
* shift `x` times then `y` times =\> `4` =\> `32` (for x=2 and y=3)
* convert it to its string binary representation =\> `"100000"`
* remove the first char of the string =\> `"00000"`
* get the length =\> `5`

# Answer
> 1 votes
# Clojure (44 chars)

```
(pr(#(count(concat(%)(%)))#(repeat(read)0)))

```

Edit: fixed to print on STDOUT instead of just returning sum.

# Answer
> 1 votes
## D

```
main(){
    int a,b;
    readf("%d %d",&a,&b);
    write((new int[a]~new int[b]).length);
}

```

this time using array lengths

# Answer
> 1 votes
## Scala

* score:
    + +- : 0
    + (). : 5+5+3=13

Code:

```
(List.fill (readInt) (1) ::: List.fill (readInt) (2)).size

```
* List.fill (4)(7) produces List (7, 7, 7, 7)
* a ::: b concatenates 2 Lists into one
* The rest should be obvious

# Answer
> 1 votes
# K, 11

```
{#,[!x;!y]}

```

Same concatenation trick as the R solution. Reading right to left: Enumerate the two input variables, concatenate and then count.

# Answer
> 1 votes
## Keg (SBCS on Keg wiki)

Basically a port of the R answer.

```
¿¿Ï_"Ï_!.

```

## Explanation

```
¿¿#        Take 2 integer inputs
  Ï_"Ï_#   Generate 2 arrays the length of the integer inputs
       !.# Output the length of the stack

```

# Answer
> 1 votes
# PowerShell, ~~27~~ 42 bytes, 0 `+-`, ~~4~~ 1 secondary

Thanks to mazzy for saving a `+` and 4 secondaries

```
$args|%{[int[]]$_*$_}|measure|select count

```

Try it online! or Pretty Table for an extra 3 bytes

**-Or- adding four secondaries to save 19 bytes:**

# ~~32~~ 23 bytes, ~~1~~ 0 `+-`, ~~12~~ 5 secondaries

-9 bytes thanks to mazzy

```
($args|%{,$_*$_}).count

```

Try it online!

For each argument, we push `n` array elements (consisting of `[n]` but that's not important) to the pipeline which are grouped by the parens and then counted.

# Answer
> 1 votes
# Ruby -na0, no +/-, no tiebreakers, 60 bytes

```
$F<<?a until~%r[
]&&$F::join[%r[a{#$`}a{#$'}]]
p$F::count ?a

```

Try it online!

Actually harder than I thought, I'm almost certainly missing a trick.

Reads in the input, then adds `a` characters to the argument array until the array, when joined into a string, matches a regular expression that uses the two input numbers as quantifiers, then counts how many it added.

Syntax tricks include using `%r[]` instead of `//` for a regexp, and `::` instead `.` for a method call.

# Answer
> 1 votes
# Ruby, 0 +/-, 0 tie-breakers, 39 bytes

And fairly unreadable.

```
p"#{"%#{"%ss%%%ss"%$F}"%%w[o o]}"::size

```

Try it online!

# Answer
> 1 votes
# MathGolf, 3 bytes, 0 `+-`, 1 tiebreaker

```
~{)

```

Input as a list. If taking the two inputs separated is mandatory, a trailing `ê` should be added (read entire STDIN input as integer-array).

Try it online.

**Explanation:**

```
~    # Push the value of the (implicit) input-list to the stack
 {   # Loop the top value amount of times
  )  #  And increase the other value once every iteration
     # (after which the entire stack joined together is output implicitly as result)

```

# Answer
> 1 votes
# Lua, 46 bytes

```
print(load'return io.read"n"\x2Bio.read"n"'())

```

Try it online!

### How It Works

`load` loads a string and returns a function, we pass a hexadecimal to it and call the function.

# Answer
> 1 votes
# brainfuck, 11 bytes, 2 +-, 3 tie breaker

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

```

Sadly i can’t think up anyway of manipulating number without `+-`

Try it online!

# Answer
> 1 votes
# Desmos, 22 bytes, 0 +/-, 2 tiebreakers

```
lne^{\ans_0}e^{\ans_1}

```

Input numbers in the first two lines. I have to admit, I spent an embarrassing amount of time trying to go from the obvious 4 tiebreakers solution `[\ans_0,\ans_1].total` to a 2 tiebreakers solution. I considered many other interesting ideas to go from 3 to 2 (integrals, percent of, `{}` evaluates to 1, etc.), but at the end, it turned out to be very simple...

I'm pretty sure 2 tiebreakers is optimal for Desmos because a `0` and `1` are required to obtain input. Defining a function is even worse: You need `(`, `)` and `=`, which is 3 tiebreakers.

Try It On Desmos!

# Answer
> 1 votes
# JavaScript, 2 tie-breakers

```
alert(`${``[`repeat`][`call`]`${prompt``}`}${``[`repeat`][`call`]`${prompt``}`}`[`length`])

```

Could I have made it shorter? Yes. But I find this version especially amusing.

Peculiarities:

* Only uses lowercase letters and the symbols `$` `[` `]` ``` `{` `}`
* Uses no mathematical operators.
* Relies heavily on especially cryptic JavaScript features

Tricks used:

* `obj['prop']` instead of `obj.prop` to avoid using `.`
* tagged template literals to avoid using `(` `)` to call functions
    + `func`string`` evaluates to `func(['string'])`
    + `func`${ expression }`` evaluates to `func(['', ''], expression)`
* `['', ''].toString()` produces `','`
* `''.repeat.call(',', value)` is equivalent to `','.repeat(value)`. This hack is used to turn the repeat function into one which takes the number of repeats as its second argument, so that we can use that function as a tag.

Edit: oops, forgot to alert the result. Uh, I'll just wrap that in an alert for now, feel free to suggest an improvement

# Answer
> 0 votes
## Python

```
i=input
print eval('%d\x2b%d'%(i(),i()))

```

37 chars with a little bit of cheating :p

# Answer
> 0 votes
**A very yucky C version**

Has no `+`, `-`, `/` or any digits. One use of `*` for a pointer type. The others (`()=,`) are needed a lot in the language itself.

```
#include <malloc.h>
#include <string.h>
#include <stdio.h>
typedef unsigned char *ptr;

char
  y;

const size_t
  one = sizeof y;

unsigned char
  zero='a'^'a',
  a [] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  z [] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  x [] = "xxxxxxxxxxxxxxxxx";

size_t plus_one (size_t i)
{
  ptr b=&a[one];
  memset (a,'x',sizeof a);
  b[i]=zero;
  return strlen(a);
}

size_t minus_one (size_t i)
{
  ptr b=&a[one];
  memset (a,'x',sizeof a);
  a[i]=zero;
  return strlen(b);
}

size_t minus_zero (size_t i)
{
  size_t p;
  for (p = zero ; z[p] ; p = plus_one (p))
  {
    i = minus_one(i);
  }
  return i;
}

unsigned char to_zero (unsigned char i)
{
  size_t p;
  for (p = one>>one ; x[p] ; p = plus_one (p))
  {
    i = (unsigned char) minus_one(i);
  }
  return i;
}

main (int argc, ptr argv [])
{
  ptr
    a = argv [argc>>one],
    b = argv [argc>>one<<one];

  size_t
    len_a = strlen (a),
    len_b = strlen (b),
    len = len_a > len_b ? len_a : len_b,
    o = plus_one(len),
    i,
    c=one>>one;

  ptr
    res=(ptr)malloc(plus_one(o));

  res[o]=zero;

  for (i = zero ; i < len ; i=plus_one(i))
  {
    size_t va;
    unsigned char r;

    va = (len_a > zero ? minus_zero (a[minus_one(len_a)]) <<one<<one<<one<<one : zero) | (len_b > zero ? minus_zero (b[minus_one (len_b)]) : zero);
    r = (c?"bcdefghijAuhjsadcdefghijABsadlkfdefghijABCvsxwerefghijABCDDNIWjsfghijABCDEOQJdccghijABCDEFIndDjlhijABCDEFGCnjndwijABCDEFGHsadXSkjABCDEFGHICSjshdABCDEFGHIJcbaCBA":"abcdefghijaswhHDbcdefghijAQWuciucdefghijABCOasdpdefghijABCCnjaskefghijABCDCIUdasfghijABCDEuoiDSAghijABCDEFCsalkjhijABCDEFGcapCPcijABCDEFGHCWEoerjABCDEFGHIkjIjIj") [va];
    c=r<'a';
    r&=~(one<<one<<one<<one<<one<<one);
    o=minus_one(o);
    res[o]=to_zero(r);

    if (len_a) len_a = minus_one (len_a);
    if (len_b) len_b = minus_one (len_b);
  }
  if(c)
  {
    o=minus_one(o);
    res[o]=to_zero('B');
  }
  printf("%s\n",&res[o]);
  free (res);
}

```

# Answer
> 0 votes
## Common Lisp

Always surprising for such a verbose language.

```
((lambda(n m)(princ(length(append(make-list n)(make-list m)))))(read)(read))

```

# Answer
> 0 votes
## VBA - No +/-, 7 tie-breakers

`+`,`-`,`/`,`*`,`,`,`.`,`0-9` = 0
`(` = 3 (3 total pairs)
`)` = 3
`=` = 1

```
Function a(b)
    For Each c In b
        a = a & Space(c)
    Next
    MsgBox Len(a)
End Function

```

Takes an array of natural numbers as an argument. This will actually add more than just 2 values, if provided, as well as return the value of a single argument.

**Older versions**

---

`+`,`-`,`/`,`*`,`=`,`.`,`0-9` = 0
`(` = 4 (4 total pairs)
`)` = 4
`,` = 1

```
Function a(b, c)
MsgBox Len(Space(b) & Space(c))
End Function

```

`+`,`-`,`/`,`*`,`=`,`.`,`0-9` = 0
`(` = 4 (4 total pairs)
`)` = 4
`,` = 3

```
Sub a(b,c)
MsgBox Len(String(b," ") & String(c," "))
End Sub

```

---

`+`,`-`,`/`,`*`,`.` = 0
`=` = 4
`(` = 2 (2 total pairs)
`)` = 2
`0-9` = 2
`,` = 1

```
Sub d(e,f)
For g=1 To e:h=h & " ":Next
For g=1 To f:h=h & " ":Next
MsgBox Len(h)
End Sub

```

# Answer
> 0 votes
# C #, 26 tiebreakers

```
+/- : 0
=   : 2
.   : 6
()  : 18

```

```
using System;
using System.Linq;
class P
{
    static void Main()
    {
        Func<int[]> f=()=>new int[int.Parse(Console.ReadLine())];
        Console.Write(f().Concat(f()).Count());
    }
}

```

# Answer
> 0 votes
# PHP, 22 chars

```
echo array_sum($argv);

```

**Documentation**: `array_sum()` and `$argv`
**Usage**: `php -r 'echo array_sum($argv);' 5 6` will output `11`.

# Answer
> 0 votes
## APL (10, 3 tie-breakers)

```
⎕←⍴(⍳⎕),⍳⎕

```

# Answer
> 0 votes
# Python 3 - 159 characters | ().,\*/= count: 39

A little long, but I felt like doing it HDL-style.

```
a,b,c,d=int(input()),int(input()),0,0;l=max(a,b,key=int.bit_length)
for i in range(len(bin(l<<1)[2:])):
 e=a>>i&1;f=b>>i&1;c|=(e^f^d)<<i;d=e&f|d&(e^f)
print(c)

```

# Answer
> 0 votes
## C# 141 characters 27 tiebreakers

```
+/- : 0
=   : 0
.   : 9
()  : 18

Console.WriteLine(Enumerable.Range(1,int.Parse(Console.ReadLine()))
.Concat(Enumerable.Range(1,int.Parse(Console.ReadLine())))
.Count());

```

# Answer
> 0 votes
## Python 42

```
a,b=input()
print eval("~-"*a+"~-"*b+"0")

```

Seven tie breakers, but those are string operations

# Answer
> 0 votes
C#, 12 tiebreakers (), 3 tiebreakers .

```
using System;
using System.Data;

class Program {
  static string ReadLine { get { return Console.ReadLine(); } }
  static void Main(string[] args) {
    Console.Out.Write(
     new DataTable().Compute(string.Join("\u002b",
     ReadLine,
     ReadLine), "")
    );
  }
}

```

# Answer
> 0 votes
# JavaScript 69

My attempt, using bitwise operators

`for(x=(z=prompt().split(" "))[0],y=z[1];y;)x^=y,y=(y&x^y)<<1;alert(x)`

# Answer
> 0 votes
# , 44 bytes

```
nchar(paste(strrep(" ",scan()),collapse=""))

```

Try it online!

Converts the two inputs to unary and "sums" via concatenation. Check out the other R answers:

# Answer
> 0 votes
# C, score 0 with 8 tie-breakers

```
f(a,b) { return b ? f(a^b, a<<1 & b<<1) : a; }
 ^ ^ ^               ^   ^    ^      ^^

```

I've highlighted the tie-break chars.

Negative numbers are assumed to be 2s-complement.

# Answer
> 0 votes
# Javascript (ES6) - 8 Tie-breaker characters

```
add: {
    let a = prompt``|false;
    let b = prompt``|false;
    while (a & b) {
        a = a ^ b;
        b = [b & ~a][false|false] << true
    }
    alert(a | b);
}

```
* 2 * `(`
* 2 * `)`
* 4 * `=`

# Answer
> 0 votes
# Gol\>\<\>, 12 bytes

```
IITM:{P}?trh

```

Thanks to JoKing for reminding me there was a Teleport Pad!!

**1st version, 25 bytes**

```
II!/M:{P}?\rh
   \     :/

```

Try it online!

This was alot easier than I thought it would be!!! I will be golfing this alot more!!!

# Answer
> 0 votes
# Runic Enchantments, (no +/-, 1 tie-breaker, 11 bytes)

```
'V2,k!$wi|;

```

Try it online!

Not allowed to have `+` characters? Fine, I'll create them myself with math and reflection. `V` has the byte value 86, which gets divided by 2 (the `,` and only tie-breaker character) converted to a character, and finally, reflectively written into the program under the instruction pointer. It then reads `i`nput, hits a reflector (`|`), reads input again, then reaches the space originally containing a `w` and adds them together before printing. The IP then performs an illegal action at `,` and is silently terminated.

Is this cheating? Probably. But the challenge says "don't use `+` characters" and the *source code* contains 0 of them.

# Alternate method, (no +/-, 3 tie-breakers, 16 bytes)

```
"ab"1,i*}i*qul$;

```

Try it online!

Makes two strings, one of length `x` and one of length `y`, concatenates them together, then computes the length of the string. Does this count as a "sum-like function"? Perhaps. `+` on two strings does do the same thing.

# Answer
> 0 votes
# APL (Dyalog Unicode), 4 bytes<sup>SBCS</sup>, 0 `+`/`-`, 0 tie breakers

Can sum any number of non-negative integers.

```
≢⎕⌿#

```

Try it online!

`#` reference to the root object

`⎕/` replicate by the number(s) from STDIN
<sup>for each number, we get that many copies of the corresponding element on the right, but since there is only one, all numbers get paired up with that one, forming a single list of N<sub>1</sub>+N<sub>2</sub>+…+N<sub>n</sub> references</sup>

tally

Output is implicitly to STDOUT.

# Answer
> 0 votes
# Befunge-98 (FBBI), 4 bytes, one +.

```
&&+.

```

Try it online!

# Answer
> 0 votes
# MathGolf, 3 bytes, 0 `+`/`-`

```
α▓∞

```

Try it online!

While perhaps violating the spirit of the "no `sum`" rule, this solution wraps the inputs into an array, calculates the average of the values in that array, and duplicates the result. Of course, the `avg` operator uses a `sum` internally, but its behavior is inherently different compared to the `sum` operator `Σ`.

The output is printed as a float, with `.0` at the end. If this is not acceptable, just add `i` to the end to convert it back into an integer.

## Explanation

```
α     wrap last two elements in array
 ▓    get average of list
  ∞   pop a, push 2*a

```

# Answer
> 0 votes
# Befunge-98 (PyFunge), 0 +/- characters, 0 tiebreaker characters, 47 bytes

```
brqzzzzzzzzzzzzzzzzzzzpyadgyacpyappyacybyabybay

```

Try it online!

Made all out letters, because why not?

More readable variant that does pretty much the same thing:

```
b<@                               &&pyapyabybay

```

Abuses the `y` GetSysInfo command, which can be used to retrieve the instruction pointer's current X coordinate. This is used to push the ASCII codes for `+` (add) and `.` (output), which later get `p`ut onto the field.

# Answer
> 0 votes
# C (gcc), 3 tiebreakers

I take no credit for this, as this is not an original answer, but merely an amalgamation of the following answers to this same challenge:

https://codegolf.stackexchange.com/a/5701/97511, https://codegolf.stackexchange.com/a/4613/97511

```
#include <stdio.h>

#define OP (
#define CP )
#define CO ,

int main OP ac CO av CP int ac; typeof OP "" CP av; {
    scanf OP "%d\n%d" CO &ac CO &av CP;
    return printf OP "%d\n" CO &av[ac] CP;
}

```

Try it online!

# Answer
> 0 votes
# Raku, 0 tie-breaker characters

```
say ½−½−$_ given ½−½−get−get

```

Try it online!

here is the Unicode character MINUS SIGN at codepoint 8722, rather than the ASCII/Unicode character `-`, HYPHEN-MINUS, at codepoint 45. The two are synonymous in Raku, but the former is by no stretch the "standard" subtraction operator.

`½−½−` is how I'm negating numbers without using any of the tiebreaking characters. It could be done with just a single leading MINUS SIGN, but that could arguably be considered a "negation function."

# Answer
> 0 votes
# Julia 1.0, no +/-, 1 tiebreaker

```
import Base:Meta.parse
["a"^[readline|>map|>parse][] "b"^[readline|>map|>parse][]]|>join|>length|>show

```

Try it online!

* `"a"^N` creates a string of length N
* `x|>f` is equivalent to `f(x)`
* `f|>map` calls `f` with no argument (`f()`)
* `[...][]` is equivalent to parenthesis
* we join both strings and check for the total length

### Julia 1.0 (function), no +/-, no tiebreaker

```
x->["a"^[x|>first][] "b"^[x|>last][]]|>join|>length

```

Try it online!

---
Tags: math, code-challenge
---


title: Draw New Posts' Profile!

text:
# Question
Title: Draw New Posts' Profile!
New Posts and New Sandbox Posts are chatbots that occupy CGSE's main chatroom, The Nineteenth Byte. They've been doing their jobs for almost one full year now, so I thought I'd make a challenge to honor their contributions!

The challenge is simple: Draw the profile picture of either New Posts (NP) or New Sandbox Posts (NSP). Your program must take as input a boolean value, and draw NP's profile picture if true and NSP's profile picture if false. (They're identical except for the color difference.)

Here are the images you need to output:

The colors of each image should be #0093E8 (NP) and #000000 (NSP). If your language is unable to output that exact shade of blue you may use the closest equivalent. The background may be white or transparent.

The image can be saved to a file or piped raw to STDOUT in any common image file format, or it can be displayed in a window.

# Answer
## PostScript, ~~132~~ 112 + 4 bytes

```
x{0 .58 .91 setrgbcolor}if
9 9 scale 16 16 false[1 0 0 1 0 0]<~s8S_ka8b3"J.ITILd2AV!!%`RKQ2ZJ`^/O&rW<~>imagemask

```

Uses an ASCII Base-85 string to encode a 16x16 bitmap.

Takes input from command line: `gs -dx=true np-nsp.ps` or `gs -dx=false np-nsp.ps`; +4 bytes for `-dx=`. Output is displayed.
> 3 votes

# Answer
# C (gcc), 295 bytes

*shorter version thanks to @ceilingcat*

```
#define p putchar(v?-1:b
*s=L"\xcd=C=C=7;104;104;10100.+6100.+6100.+6.3+3++.-.3+3++.-.3+3++.-.3+310.3+310.30.10.30B+30B+\xcf.D.0.D.0.D.0+;+1+3+;+1+3+;+1+3.8+1.0.5.1.0.5.1.C.J6I7I=1O1O1L1O1O1L.R.R.\xdf";main(b,v,n){b%=2;for(v=printf("P6 48 48 255 ");*s;v=!v)for(n=*s++-40;n--;p*232))p*0),p*147);}

```

Try it online!

# C (GCC), 318 bytes

```
#define p(x)putchar(v?255:b*x)main(b,v,n){unsigned char*s="\xcd=C=C=7;104;104;10100.+6100.+6100.+6.3+3++.-.3+3++.-.3+3++.-.3+310.3+310.30.10.30B+30B+\xcf.D.0.D.0.D.0+;+1+3+;+1+3+;+1+3.8+1.0.5.1.0.5.1.C.J6I7I=1O1O1L1O1O1L.R.R.\xdf";b%=2;for(v=printf("P6 %d %d 255 ",48,48);*s;v=!v)for(n=*s++-40;n--;p(232))p(0),p(147);}
```

Attempt This Online!

Outputs a PPM image. The image is run-length encoded in the variable `s`.

The boolean input is given via the number of arguments (basically corresponds to `argc % 2`).
> 1 votes

---
Tags: code-golf, kolmogorov-complexity, graphical-output
---


title: Horizontally Aligned ASCII Art

text:
# Question
Title: Horizontally Aligned ASCII Art
Your task is to accept as input two "ASCII Art"s, and align each piece of art next to each other horizontally.

For example, say you have two strings, `"abc\ndef"` and `"123\n456"`. You need to align them horizontally to produce the string `"abc123\ndef456`". I'm calling this "aligning horizontally" because while the inputs, when printed, look like this:

```
abc
def

```

and:

```
123
456

```

The output, when printed, will look like this:

```
abc123
def456

```

Note how one input is placed next to the other.

---

# Input

* Input will be strings, and can be as two separate arguments, or as a sequence of strings.
* The characters in the arts will have decimal codes in the range 32-126 (inclusive).
* It's fine to support an arbitrary number of arts to align instead of just two (but obviously you must support at least two).
* You can assume that each art will have the same dimensions, and that they will contain at least one line.
* You must be able to support at least 100x100 character arts.
* To align with conventions on the site, the argument order does not matter. It does not matter which art is on the left or right.

---

# Output

* Output will be the aligned arts as mentioned above, either returned or output to the stdout.
* Any trailing whitespace in optional.
* There must be no visual separator between the aligned arts.

---

Input and output arts must be `\n` or `\r` delimited strings. It would be overly trivial to allow 2D-arrays.

Submissions may be functions or full programs.

Test Cases:

```
"abc\ndef", "123\n456" -> "abc123\ndef456".

"qwertyuiop\n asdfghjkl", "Some other\nTextFiller" -> "qwertyuiopSome other\n asdfghjklTextFiller"

"  *  \n *** \n*****\n *** \n  *  \n", "  +  \n  +  \n+++++\n  +  \n  +  \n" -> "  *    +  \n ***   +  \n*****+++++\n ***   +  \n  *    +  \n"

```

# Answer
> 20 votes
# Canvas, 1 byte

```
×

```

Try it here!

# Answer
> 7 votes
# Haskell, 37 bytes

```
(unlines.).(.lines).zipWith(++).lines

```

Try it online!

IO as lists of lines would just be `zipWith(++)`. :P

# Answer
> 6 votes
# Python 2, 59 bytes

```
lambda y:'\n'.join(map(str.__add__,*map(str.splitlines,y)))

```

Try it online!

# Answer
> 4 votes
# 05AB1E, 6 bytes

```
|¶¡øJ»

```

Try it online!

**Explanation**

```
|        # push all input into a list
 ¶¡      # split on newlines
   ø     # zip
    J    # join the rows to single strings
     »   # merge on newlines

```

# Answer
> 3 votes
# Jelly, 4 bytes

```
Ỵ€ZY

```

Try it online!

# Answer
> 3 votes
# Perl 5 `-0F`, 28 bytes

Includes `+2` for the `\n` argument to `-F` (it's "code" so it should count)

Give inputs directly after each other on STDIN.

```
#!/usr/bin/perl -0F\n
say@F[$%++,$_]for@F/2..$#F

```

Try it online!

# Answer
> 3 votes
# Perl 6, 27 bytes

```
{join "\n",[Z~] $_>>.lines}

```

Try it online!

Works with arbitrary number of arts. IO as list of lists would be just `&[Z~]`.

# Answer
> 3 votes
# Bash + coreutils, 14

* 4 bytes saved thanks to @DavidFoerster.

```
paste -d "" $@

```

Input is given as two filenames as command-line parameters.

Try it online.

# Answer
> 2 votes
# Java 8, ~~100~~ ~~84~~ 78 bytes

```
a->b->{for(int i=0;;)System.out.println(a.split("\n")[i]+b.split("\n")[i++]);}

```

Exits with an `ArrayIndexOutOfBoundsException` to STDERR after it has printed the result to STDOUT, which is allowed.

-6 bytes thanks to *@OlivierGrégoire*.

**Explanation:**

Try it online.

```
a->b->{                        // Method with two String parameters and no return-type
  for(int i=0;;)               //  Loop over the substrings of the first input
    System.out.println(        //   Print:
     a.split("\n")[i]          //    The substring of the first input
     +b.split("\n")[i++]);}    //    plus the same-indexed substring of the second input

```

# Answer
> 2 votes
# APL (Dyalog Unicode), 9 bytesSBCS

Full program. Prompts (STDIN) for any length list of `\r`-delimited strings. The strings may be ragged and of different widths as long as they have the same number of lines. Prints (STDOUT) resulting ASCII art.

```
⊃,/⎕FMT¨⎕

```

Try it online!

prompt for evaluated input

`⎕FMT¨` format (evaluate all control characters and return character matrix) each

`,/` combine them horizontally (catenation reduction)

disclose (because the reduction reduced the rank from 1 to 0)

# Answer
> 2 votes
# Ruby, 48 bytes

```
->a,b{$;=$/;a.split.zip(b.split).map(&:join)*$/}

```

Try it online!

A lambda taking two strings and returning a string. Setting the default `split` delimiter to newline with `$;=$/;` doesn't save any bytes, but it makes the rest look a little nicer.

# Ruby, 49 bytes (arbitrarily many strings)

```
->s{s.map{|a|a.split$/}.transpose.map(&:join)*$/}

```

Try it online!

Just for fun. It turns out we can accept an array of strings at an additional cost of only 1 byte.

# Answer
> 2 votes
## JavaScript (ES6), 51 bytes

```
f=
(a,b)=>a.replace(/.+/g,a=>a+b.shift(),b=b.split`
`)
;document.write("<pre>"+f("abc\ndef", "123\n456")+"</pre>")
```

# Answer
> 2 votes
# Wonder, 21 bytes

```
->#oN.zip#++.-> <>"
"

```

Usage example:

```
(->#oN.zip#++.-> <>"
")["abc#ndef" "abc#ndef"]

```

`#n` is used instead of `\n` to denote newlines.

## Explanation

Verbose version:

```
(map #oN) . (zip #con) . (map split "#n")

```

Split each string in the input array along newlines, zip with string concatenate, and output each item.

# Answer
> 2 votes
# Kotlin, 73 bytes

```
a,b->a.split("\n").mapIndexed{i,s->s+b.split("\n")[i]}.joinToString("\n")

```

Try it online!

# Answer
> 2 votes
# Vyxal `j`, 4 bytes

```
↵∩vṅ

```

Try it Online!

# Answer
> 2 votes
# K (ngn/k), ~~15~~ 14 bytes

```
"\n"/,'/"\n"\'

```

Try it online!

-1 byte thanks to ngn

# Answer
> 1 votes
# APL (Dyalog Unicode), 22 bytes (Adám's SBCS)

```
{⊃,/↑¨⍵}'[^\n]+'⎕S'&'¨

```

Try it online!

# Answer
> 1 votes
# Add++, 24 bytes

```
L,c10CdVAptA$pG$tBcB@£+n

```

Try it online!

# Answer
> 1 votes
# C, 96 bytes

```
#define L(s)for(;*s++>10;)putchar(s[-1]);
i;f(s,t)char*s,*t;{for(;i=!!s[-i];puts("")){L(s)L(t)}}

```

Try it online!

# Answer
> 1 votes
# PowerShell, ~~51~~ 49 bytes

```
param($a,$b)$a-split"
"|%{$_+($b-split"
")[$i++]}

```

Try it online!

Takes input as literal strings with newlines. You could also use ``n` (the newline delimiter in PowerShell, not `\n`) instead.

We first `-split` the left input string on newlines, which creates an array, and loop through that `|%{...}`. Each iteration, we string concatenate with the right input string again split on newlines, indexed and incremented.

Those are left on the pipeline and the implicit `Write-Output` at completion gives us output as an array of strings, which are printed with newlines between.

# Answer
> 1 votes
# JavaScript (ES6), 52 bytes

Takes input in currying syntax `(a)(b)`.

```
a=>b=>a.split`
`.map((s,i)=>s+b.split`
`[i]).join`
`

```

Try it online!

# Answer
> 1 votes
# Japt `-R`, ~~8~~ ~~7~~ 5 bytes

```
·í+V·

```

Try it

```
·í+V·     :Implcict input of strings U & V
·         :Split U on newlines
 í        :Interleave with
   V·     :  V split on newlines
  +       :  Reduce by concatenation
          :Implicit output, joined by newlines

```

# Answer
> 1 votes
# Red, 78 bytes

```
func[a b][b: split b"^/"foreach c split a"^/"[prin c print first b b: next b]]

```

Try it online!

# Answer
> 1 votes
# Bash, 92 bytes

```
a=();for b;do c=;while IFS= read -r d;do a[c++]+=$d;done<<<"$b";done;printf '%s\n' "${a[@]}"

```

Try it online!

**Ungolfed:**

```
array=()                             # Initialize the array
for argument in "${@}"; do           # Loop over the arguments list
  index='0'                          # Reset the index
  while IFS='' read -r 'line'; do    # Loop over every line of the current argument
    array[index]+="${line}"          # Append the line to its corresponding place
    (( index++ ))                    # Increment the index
  done <<< "${argument}"             # End while loop
done                                 # End for loop
printf '%s\n' "${array[@]}"          # Print array's content

```

**Examples:**

```
$ foo $'abc\ndef' $'123\n456'
abc123
def456

$ foo $'qwertyuiop\n asdfghjkl' $'Some other\nTextFiller'
qwertyuiopSome other
 asdfghjklTextFiller

$ foo \
>   $'  *  \n *** \n*****\n *** \n  *  \n' \
>   $'  +  \n  +  \n+++++\n  +  \n  +  \n'
  *    +
 ***   +
*****+++++
 ***   +
  *    +

# https://gist.github.com/nxnev/dad0576be7eb2996b860c320c01d0ec5
$ foo "$(< input1)" "$(< input2)" "$(< input3)" > output

```

---

I also have a shorter one but it fails if the second `read` statement returns a non-zero value.

# Bash, 55 bytes

```
while IFS= read -r a;IFS= read b<&3;do echo "$a$b";done

```

Note: `<&3` doesn't seem to work on tio.run

This one uses file descriptors (`1` and `3`) instead of arguments:

```
$ foo <<< $'qwertyuiop\n asdfghjkl' 3<<< $'Some other\nTextFiller'
qwertyuiopSome other
 asdfghjklTextFiller

```

# Answer
> 1 votes
# Charcoal, 8 bytes

```
ＰθＭ⌕θ¶→η

```

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

```
 θ          First input
Ｐ           Print without moving the cursor
    θ       First input
     ¶      Literal newline
   ⌕        Find index
  Ｍ   →     Move that many squares right
       η    Implicitly print second input

```

Add 2 bytes to accept multiple inputs:

```
ＦＡ«ＰιＭ⌕ι¶→

```

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

```
 Ａ          Input
Ｆ «         Loop over all entries
   Ｐι       Print current entry
     Ｍ⌕ι¶→  Move to next entry

```

Add 4 bytes to accept unpadded input:

```
ＰθＭ⌈Ｅ⪪θ¶Ｌι→η

```

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

```
      θ         First input
       ¶        Literal newline
     ⪪          Split
    Ｅ           Map over each string
         ι      Current string
        Ｌ       Length
   ⌈            Maximum
  Ｍ       →     Move that many squares right

```

# Answer
> 1 votes
# JavaScript (Node.js), 79 bytes

```
a=>(b=a.map(x=>x.split`
`))[i=0].map(y=>b.map(z=>c+=z[i],c="")&&++i&&c).join`
`

```

Try it online!

Supports arbitrary number of ASCII arts joining together rather than just 2 (as in the 2 previous JS answers).

# Answer
> 1 votes
# Clean, 61 bytes

```
import StdEnv
$a b=flatlines[u++v\\u<-mklines a&v<-mklines b]

```

Try it online!

# Answer
> 1 votes
# Swift 4, 119 bytes

```
func f(s:[String])->String{return s[0].split{$0=="\n"}.enumerated().map{$0.1+s[1].split{$0=="\n"}[$0.0]+"\n"}.joined()}

```

**Explanation**

```
func f(s: [String]) -> String {
    return s[0].split{ $0=="\n" }       //splitting the first string after every \n
    .enumerated()                       //create a tuple of offsets and elements
    .map {
        $0.1 +                          //current element
        s[1].split{$0 == "\n"}[$0.0] +  //splitting the second string + indexing
        "\n"                            //new line after every line
     }
     .joined()
}

```

Try it online!

# Answer
> 1 votes
# Julia 1.0, 34 bytes

```
^,x=split,"\n"
a\b=join(a^x.*b^x,x)

```

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), 43 bytes (41 chars)

```
Column[StringJoin/@(#~StringSplit~"
")]&

```

 is an unprintable character in the private use area which represents Transpose in Mathematica.

This function takes input as a list of any number of strings and returns a Column object, which displays in a Mathematica notebook in the required manner (although it doesn't on TIO). For an additional ten bytes, replacing `Column[---]` with `StringRiffle[---," "]` will cause an output in the form of a single string. This code can take input of any number of strings with varied-length lines, as long as each string has the same number of lines.

---

Explanation:

`#~StringSplit~` Split the input (implicitly applied to each string in the list)

`" "` at each newline.

Then, transpose this list of lists of strings

`StringJoin/@` and join together each of the sublists.

`Column` Finally, convert this list of strings to a Column object.

Try it online!

# Answer
> 0 votes
# Julia 0.6, 41 bytes

```
(a,b)->map(*,split(a,'\n'),split(b,'\n'))

```

Try it online!

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