title: Shifting Caesars Shifts

text:
# Question
Title: Shifting Caesars Shifts
### Description

A Caesar Shift is a very simple monoalphabetic cipher where each letter gets replaced by the one after it in the alphabet. Example:

```
Hello world! -> IFMMP XPSME!

```

*(`IBSLR, EGUFV!` is the output for the actual challenge, this was an example of shifting by 1.)*

As you can see, spacing and punctuation remain unattuned. However, to prevent guessing the message, all letters are capitalized. By shifting the letters back, the message was deciphered, convenient, but also really easy to decipher by other persons who are supposed not to know what the message means.

So, we'll be helping Caesar a bit by using an advanced form of his cipher: the *Self-shifting Caesar Shift*!

### Challenge

Your task is to write a program or function, that, given a string to encipher, outputs the encrypted string corresponding to the input. The advanced Caesar Shift works like this:

```
1. Compute letter differences of all adjacent letters:
    1.1. Letter difference is computed like this:

         Position of 2nd letter in the alphabet
        -Position of 1st letter in the alphabet
        =======================================
                              Letter difference

    1.2. Example input: Hello
         H - e|e -  l|l  -  l|l  -  o
         7 - 5|5 - 12|12 - 12|12 - 15 Letter differences: 3; -7; 0; -3
            =3|   =-7|     =0|    =-3

2. Assign the letters continously a letter difference from the list,
   starting at the second letter and inverting the differences:
    2.1. 2nd letter: first difference, 3rd letter: second difference, etc.

    2.2. The first letter is assigned a 1.

    2.3. Example input: Hello with differences 3; -7; 0; -3

         Letter || Value
         =======||======
            H   ||   1
            E   ||  -3
            L   ||   7
            L   ||   0
            O   ||   3

3. Shift the letters by the value x they have been assigned:
    3.1. In case of a positive x, the letter is shifted x letters to the right.
    3.2. In case of a negative x, the letter is shifted |x| letters to the left.
    3.3. In case of x = 0, the letter is not shifted.

    3.4. If the shift would surpass the limits of the alphabet, it gets wrapped around
         Example: Y + Shift of 2 --> A

    3.5. Example input: See the table under 2.3.

                ||       || Shifted
         Letter || Value || Letter
         =======||=======||=========
            H   ||   1   ||    I
            E   ||  -3   ||    B     Program output:
            L   ||   7   ||    S     IBSLR
            L   ||   0   ||    L
            O   ||   3   ||    R

```

Spaces and other special symbols, such as punctuation are skipped in this process. It is guaranteed that your program will be given a string containing only printable ASCII characters. The output of your function/program must only be in upper case.

This is , so standard loopholes apply, and may the shortest answer in bytes win!

# Answer
# 05AB1E, ~~28~~ ~~27~~ 24 bytes

```
láÇ¥R`XIlvyaiAyk+Aèëy}u?

```

Try it online!

**Explanation**

```
l                          # convert input to lower case
 á                         # keep only letters
  Ç¥                       # compute deltas of character codes
    R`                     # reverse and push separated to stack
      X                    # push 1
       Ilv                 # for each char y in lower case input
          yai              # if y is a letter
             Ayk           # get the index of y in the alphabet
                +          # add the next delta
                 Aè        # index into the alphabet with this
            ëy             # else push y
              }            # end if
            u?             # print as upper case

```
> 5 votes

# Answer
# Python 3, 100 bytes

```
b=0
for c in map(ord,input().upper()):
 if 64<c<91:b,c=c,(c+c-(b or~-c)-65)%26+65
 print(end=chr(c))

```

Try it online!

`b` keeps track of the last letter’s ASCII code, or is initially zero; the formula `c+c-(b or~-x)` means a letter with ASCII code `c` gets shifted by `c-b` if `b` is non-zero, and `c-(c-1) == +1` if `b` is zero (for the very first letter).

`b` will never become zero again, as the string is guaranteed to consist of *printable* ASCII characters.

Finally, `64<c<91` checks if `c` is an uppercase ASCII letter, and `(…-65)%26+65` wraps everything back into the `A-Z` range.

ovs saved a byte. Thanks!
> 4 votes

# Answer
# 05AB1E, ~~32~~ ~~30~~ 29 bytes

```
lDáÇ¥1¸ìUvyaiAX¾èAyk+sè¼ëy}Ju

```

Try it online!
> 3 votes

# Answer
## Perl, ~~90~~89

Though non-codegolf languages are rarely competitive, we can go below 100 ;)

```
@a=split//,<>;say uc(++$a[0]).join'',map{uc chr(2*ord($a[$_+1])-ord($a[$_])+!$_)}0..$#a-1

```

I've decided to ungolf this:

`@a = split//,<>;` Takes input from STDIN, stores character list (with newline!) in @a.

`say uc(++$a[0])` output uppercase first letter shifted by 1. Turns out you can increment a letter in perl if you use a prefix ++. This is a mutator ofc.

`2*ord($a[$_+1])-ord($a[$_])+!$_` We are asked to take character at x, and add the difference + (x-(x-1)). Well that's 2x - (x-1). However: I changed the first letter! So I've got to correct that error, hence `+!$_`, which will correct for having subtracted one too many at position 0 (only case !$\_ is not undef ). We then `uc chr` to get an uppercase letter from the calculated ASCII value.

`map{ ... } $#a-2` \- `$#a` is the position to access the last array element. Since I'm adding one I want `$#a-1`, but because the newline from input needs ignoring, this is `$#a-2`.

This is concatenated with the first letter, and we are done :)
> 1 votes

# Answer
# ES6 ( Javascript ) , 138 bytes :

```
s=>((s,a,f)=>((r=i=>s[i]&&(a[i]=String.fromCharCode((2*s[f](i)-(s[f](i-1)||71)-38)%26+64),r(i+1)))(0),a))(s.toUpperCase(),[],"charCodeAt")

```

http://jsbin.com/manurenasa/edit?console
> 1 votes

# Answer
# MATL, 27 bytes

```
tXkt1Y2mXH)tlwdh+64-lY2w)H(

```

Try it online!

I think this is the shortest I can get, but there are lots of different varieties since there is a lot of re-use of 'variables' (there are 3 `t` (duplication), and 2 `w` (swap) operations, clipboard `H` is used, and even then there is still a duplicate `1Y2`...). Sadly, I couldn't save bytes with the automatic `M` clipboard.

Over half of the program is dedicated to making it uppercase and ignoring non-alphabetic characters - just the cipher is no more than 13 bytes (Try it online!)
> 1 votes

# Answer
# Perl 5 `-F`, ~~73~~ ~~77~~ 74 bytes

```
/\w/&&($_=chr 65+(2*($n=ord uc)-65-($!||-1+ord uc))%26)&($!=$n)for@F;say@F

```

Try it online!
> 1 votes

# Answer
# PHP, ~~106~~ 98 bytes

pretty nasty that one ... if just `base_convert` wasn´t that long (or `ctype_alpha`) ...
but I got it under 100. satisfied.

```
for(;$a=ord($c=$argn[$i++]);print ctype_alpha($c)?chr(65+($p?(25-$p+2*$p=$a)%26:$p=$a)):$c)$a&=31;

```

Run as pipe with `-nR` or try it online.
> 1 votes

# Answer
# JavaScript (Node.js), 86 83 87 81 bytes

```
s=>s.replace(/[a-z]/gi,(x,i)=>Buffer(x).map(x=>((i?x%32-l:1)+26+(l=x%32))%26+64))

```

Try it online!
> 1 votes

---
Tags: code-golf, string, cryptography
---


title: Is this a staircase number?

text:
# Question
Title: Is this a staircase number?
# Challenge :

Check if the given number forms a `number staircase` or not

---

# Input :

A integer (greater than 0 and not decimal). NOTE : You can take input as string , array of digits.

---

# Output :

a truthy / falsy value depending on whether the number forms a staircase or not

---

# Number staircase :

A *number staircase* is an integer that , when read from left to right :

* Starts with 1
* which may be followed by 2
* which may be followed by 3
* and so on till `n`
* then the number descends starting at n - 1
* then n - 2
* then n - 3
* and so on till it reaches 1

## Note :

The *may be* part is used to indicate that if length \> is greater than 1. If it is the order must be followed as is. i.e : 12321

---

# Example :

```
12321                          ---> true
12345654321                    ---> true
9                              ---> false
1                              ---> true
2                              ---> false
123421                         ---> false
112312318901323                ---> false
123456789101110987654321       ---> true

```

---

# Note :

The input given will always be an integer greater than 0 and will not be a decimal. Your output must be a `truthy or falsy` value depending on the input

---

# Restrictions :

This is so shortest code in bytes (for each programming language ) wins.

---

# Answer
> 5 votes
# , 97 bytes

```
function(n)"if"(n>1,{while({T=T+1;x=paste(c(1:T,T:2-1),collapse="");nchar(x)<nchar(n)})0;x==n},T)

```

Try it online!

Takes `n` as a `character` or an `integer`; using `character` will give correct results for integers that can't be held precisely as a 64-bit `double`.

Generates staircase numbers until it finds one at least as long as `n` is, then tests for equality.

Equivalent to:

```
function(n)
    if(n > 1){
        T <- T + 1
        x <- paste(c(1:T,T:2-1),collapse="")
        while(nchar(x) < nchar(n)){
            T <- T + 1
            x <- paste(c(1:T,T:2-1),collapse="")
        }
        return(x == n)
    } else
        return(TRUE)

```

# Answer
> 3 votes
# Jelly, 5 bytes

```
ŒḄ€Vċ

```

Try it online!

Warning: Very slow (fast for `1` and `121`)! Prepend `DL` to make it faster.

# Answer
> 3 votes
# JavaScript (ES6), ~~62~~ 57 bytes

*Saved 2 bytes thanks to @l4m2*

Returns a boolean.

```
f=(s,k=1)=>(m=s.match(`^${k}(.*)${k}$`))?f(m[1],k+1):s==k

```

Try it online!

### How?

Starting with **k = 1**, we look for **k** at the beginning and at the end of the string, and recursively iterate the process on the remaining middle sub-string with **k + 1**. The recursion stops as soon as there's no match anymore. The input is a staircase number if the last sub-string is equal to **k**.

**Example for s = "1234321":**

```
 k | s         | match     | s == k
---+-----------+-----------+--------
 1 | "1234321" | 1(23432)1 | no
 2 | "2343"    | 2(343)2   | no
 3 | "343"     | 3(4)3     | no
 4 | "4"       | null      | yes

```

# Answer
> 2 votes
# Pyth, ~~13~~ 12 bytes

```
/mjk+Sd_Stdl

```

Saved a byte thanks to RK.
Try it here

### Explanation

```
/mjk+Sd_Stdl
 m         lQ   For each d up to the length of the (implicit) input...
    +Sd_Std     ... get the list [1, 2, ..., d, d-1, ..., 1]...
  jk            ... concatenated.
/               Count how many times the input appears.

```

If you really want the input as an integer, you can use `}Qmsjk+Sd_Std` instead, but this is horrifyingly slow.

# Answer
> 2 votes
# Haskell, ~~55~~ 54 bytes

-1 byte thanks to Laikoni!

```
f x=elem x[read$[1..z]++[z-1,z-2..1]>>=show|z<-[1..x]]

```

Try it online!

# Answer
> 2 votes
# Python 2, 69 bytes

```
f=lambda s,n=1,t='1',u='':t+':'>s>t<s*f(s,n+1,t+`n+1`,`n`+u)or s==t+u

```

Try it online!

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), ~~138~~ ~~107~~ 102 bytes

```
bool t(List<int>s)=>s.Select((j,i)=>s[0]==1&&s.Last()==1&&(i==0||j+1==s[i-1]||j-1==s[i-1])).All(x=>x);

```

Try it online!

Explanation:

```
bool t(List<int>s)=>
    s.Select((j,i) =>         //iterate over each item and store the return value
        s[0]==1&&s.Last()==1  //does the sequence start and end with 1?
        &&                    //AND
        (i==0                 //is it the first item?
        ||                    //OR
        j+1==s[i-1]           //is the item 1 greater than the previous?
        ||                    //OR
        j-1==s[i-1])          //is the item 1 smaller than the previous?
    ).All(x=>x);              //did all pass the criteria?

```

# Answer
> 1 votes
# 05AB1E, ~~9~~ 8 bytes

```
L€L€ûJså

```

Warning: EXTREMELY SLOW! Add `g` to the start to speed it up.

Try it online!

Explanation:

```
L           1..input
 €L         for each element, map to 1..element
   €û       palindromize each element
     J      join each element from a list to a string
      så    is the input in that list?

```

Old Explanation:

```
F           For [0 .. input] map over
 NL          Push 1..i
   û         Palindromize
    J        Join
     ¹       First input
      Q      Equal?
       }   end loop
        O  Sum.

```

Try it online!

# Answer
> 1 votes
# Python 2, 77 bytes

```
lambda s,r=range:s in[''.join(map(str,r(1,k+2)+r(k,0,-1)))for k in r(len(s))]

```

Try it online!

# Answer
> 1 votes
# Attache, ~~57~~ ~~55~~ 46 bytes

```
{GenerateFirst[N@Join@Bounce@1&`:,`>=:`#&_]=_}

```

Try it online! Ah, that's much more elegant.

With `Generate` (49 bytes):

```
{g@Generate[{g@_>=#_2}&_]=_}g:=N@Join@Bounce@1&`:

```

## Explanation

```
{GenerateFirst[N@Join@Bounce@1&`:,`>=:`#&_]=_}
{                                            }   anonymous lambda, argument: _
 GenerateFirst[                  ,        ]      find the first element satisfying...
               N@Join@Bounce@1&`:                    this generation function
                                  `>=:`#&_           and this condition
                                           =_    is it equal to the input?

```

The generation function simply creates the `N`th staircase number. Then, this search terminates once ``>=:`#&_` is satisfied. Expanded, this is:

```
 `>=:`#&_
 (`>= : `#) & _      NB. remember _ is the input
                     NB. also, f:g is f[...Map[g, args]]
 { #_1 >= #_2 } & _
 { Size[_1] >= Size[_2] } & _
 { Size[_1] >= Size[the original input] }
 [n] -> { Size[n] >= Size[input] }

```

So, this terminates once the length of the generation function's output is at least that of the inputs. Thus, this generates the smallest staircase number at least as long as the input number. Thus, if the input is a staircase number, the result will be the same staircase number, and otherwise the next longest staircase number. As such, a simple check with equality to the original input is sufficient for determining whether or not it was a staircase number.

## Attache, 55 bytes

```
0&{If[#_2>#g[_],$[_+1,_2],_2=g!_]}g:=N@Join@Bounce@1&`:

```

Try it online! With plan ol' recursion.

# Answer
> 1 votes
# Stax, 14 bytes

```
Ç╗☻W╧ΩÆΘαφ←≤─♣

```

Run and debug it

Very slow for bigger numbers.

# Answer
> 1 votes
# , 40 bytes

```
1#.[:(<-:"_1<@([:;>:<@":@-|@i:)@<:@#\)":

```

Try it online!

I'm not quite happy with this soluiton - a lot of `@` and boxing `<` .

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 109 bytes

```
	N =INPUT
	X =L ='1'
C	R =LT(SIZE(L R),SIZE(N)) X R	:F(O)
	X =X + 1
	L =L X	:(C)
O	OUTPUT =IDENT(L R,N) 1
END

```

Try it online!

Curiously, replacing `'1'` in the second line with `1` causes the program to fail on the input of `1`.

# Answer
> 1 votes
# , 36 bytes

```
{|/($x)~/:{,/$(1+!x),1+1_|!x}'1+!#x}

```

Takes a string such as "12321" as a parameter.

This function is written as a long chain of function applications, as in `f g h x`, so read the commented versions from the bottom, going up. `{x+1}` is `lambda x: x+1`, x is a default param name. Check out https://pastebin.com/cRwXJn7Z or the interpreter's help for operator meanings.

We generate the staircase number with `n` in the middle by `{,/$(1+!x),1+1_|!x}`:

```
{,/                      / join all the chars
   $                     / tostring each number
     (1+!x)              / take the range [0..x-1]; add 1 to each
            ,            / concat
             (1+1_|!x)}  / take the range [0..x-1]; reverse it; drop 1; add 1 to each

```

The whole function `{|/($x)~/:{,/$(1+!x),1+1_|!x}'1+!#x}`:

```
{|/                                   / any_is_true
   ($x)~/:                            / match the string with each of the generated staircases
          {,/$(1+!x),1+1_|!x}'        / make staircase number of each of the numbers
                                      / (note: the x in the inner lambda shadows the outer x)
                              1+!#x}  / take the range [1..length of the string, inclusive]

```

# Answer
> 0 votes
# Japt, 11 bytes

Takes input as a string.

```
Êõõ mê m¬øU

```

Try it

---

## Explanation

```
                :Implicit input of string U
Ê               :Length of U
 õ              :Range [1,Ê]
  õ             :Range [1,el] for each element
    mê          :Map & palidromise
       m¬       :Map & join
         øU     :Contains U?

```

---

## Alternative, ~~10~~ 9 bytes

This solution, which can take input as a string or an integer, will return an array of numbers for truthy or, eventually, throw an error for falsey, if it doesn't cripple your browser before that. Use with caution.

```
@¥Xê q}aõ

```

Try it

# Answer
> 0 votes
# Haskell, ~~64~~ ~~60~~ 58 bytes

-6 thanks to @BMO!

```
elem.show<*>(`take`[[1..n]++[n-1,n-2..1]>>=show|n<-[1..]])

```

Try it online!

# Answer
> 0 votes
# Perl 5 `-lp`, 49 bytes

```
$i++while s/^$i//;$i-=2;$i--while s/^$i//;$_||=$i

```

Try it online!

`0` = truthy, anything else = falsy

# Answer
> 0 votes
# Retina, ~~45~~ 43 bytes

```
$
;1
+`^(.+)(.*)\1;\1$
$2;$.(_$1*
^(.+);\1$

```

Try it online! Link includes test cases. Edit: Saved 2 bytes thanks to @Leo. Explanation:

```
$
;1

```

Initialise `n` to `1`.

```
+`^(.+)(.*)\1;\1$

```

While `s` begins and ends with `n`:

```
$2;$.(_$1*

```

Delete `n` from the ends of `s` and increment `n`.

```
^(.+);\1$

```

Test whether `n` is left.

# Answer
> 0 votes
# Java 10, 142 bytes

```
s->{int n=1,l,f=1;try{for(;;s=s.substring(l=(n+++"").length(),s.length()-l))if(!s.matches(n+".*"+n)&!s.equals(n+""))f=0;}finally{return f>0;}}

```

Try it online.

**Explanation:**

```
s->{                 // Method with String parameter and boolean return-type
  int n=1,           //  Stair integer, starting at 1
      l,             //  Length integer to reduce bytes
      f=1;           //  Result-flag, starting at 1
  try{for(;;         //  Loop until an error occurs
          s=s.substring(l=(n+++"").length(),s.length()-l))
                     //    After every iteration: remove `n` from the sides of the String
        if(!s.matches(n+".*"+n)
                     //   If the current String with the current `n` isn't a stair
           &!s.equals(n+""))
                     //   And they are also not equal (for the middle)
          f=0;       //    Set the flag to 0
   }finally{         //  After the error (StringOutOfBoundsException) occurred:
      return f>0;}}  //   Return whether the flag is still 1

```

# Answer
> 0 votes
# Regex (PCRE), 92 bytes

```
^(1|\d(?=1|9)|[2-79](?=8)|[2-68](?=7)|[2-57](?=6)|[2346](?=5)|[235](?=4)|[24](?=3)|3(?=2))+$

```

Try it online!

I'm open to any suggestions to improve this.

# Answer
> -1 votes
Thanks to following users:

```
@Nooneishere
@LyricLy
@JoKing

```

# Python 2, 147 bytes

```
g=s=input()
f=1
o='1'==s[0]
while`f`==s[0]:s=s[len(`f`):];f+=1
f-=2
o&=`f`==s[0]
while s and`f`==s[0]:s=s[len(`f`):];f-=1
o&=f==0
o|=g=='1'
print o

```

Try it online!

---
Tags: code-golf, math, number, decision-problem
---


title: Shortest 8-bit xor cipher

text:
# Question
Title: Shortest 8-bit xor cipher
8-bit XOR encryption takes a single byte and XORs every byte in the file by that byte. Here is a reference program in C++:

```
/*xorcipher.cpp
 *Encrypts a file using 8-bit xor encrytpion
 */

#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;

int main(int argc, char** argv){
   ifstream* in = NULL;
   ofstream* out = NULL;

   if(argc < 3){
      cerr << "Usage: xor <key> <filename...>" << endl;
      exit(1);
   }

   int key = atoi(argv[1]);

   for(int x = 2; x < argc; x++){
      in = new ifstream(argv[x], ios::binary);
      if(!in->good()){
         cerr << "Error reading from " << argv[x] << endl;
         exit(1);
      }

      //Get file size
      in->seekg(0, ios::end);
      int size = in->tellg();
      in->seekg(0, ios::beg);

      //Allocate memory
      int* data = new int[size];

      int c = 0;
      for(int y = 0; (c = in->get()) != EOF; y++)
         data[y] = c ^ key;

      in->close();
      delete in;
      in = NULL;

      out = new ofstream(argv[x], ios::binary);
      if(!out->good()){
         cerr << "Error writing to " << argv[x] << endl;
         exit(1);
      }

      for(int y = 0; y < size; y++)
         out->put(data[y]);

      out->flush();
      out->close();
      delete out;
      out = NULL;

      delete[] data;
      data = NULL;
   }
   cout << "Operation complete" << endl;

   return 0;
}

```

The shortest answer (whitespace doesn't count) that produces the same end result will be selected. It does not have to store everything in memory at once or open and close every file multiple times. It can do anything as long as a file encrypted with the reference program can be decrypted with the answer, and vice versa.

---

**Edit**: The above program is not a specification. The only requirement is that answers should be able to decrypt a file encrypted with the above program, and the above program should be able to decrypt a file encrypted with the answer. I'm sorry if that was unclear.

The above program can be compiled with:

```
g++ xorcipher.cpp -o ~/bin/xor

```

It can be run like this:

```
xor <key> <filename...>

```

For example, if the key is `42` and the file is `alpha.txt`, you would use:

```
xor 42 alpha.txt

```

# Answer
## PHP ~~40~~ 38 bytes

```
<?for(;;)echo@~fgetc(STDIN)^~$argv[1];

```

And updated version. Now handles all inputs correctly, and 2 bytes shorter as well.

Sample usage:

```
$ more in.dat
This is a test.
This is only a test.

$ php xor-cipher.php A < in.dat > out.dat

$ more out.dat
§)(2a(2a a5$25oK§)(2a(2a./-8a a5$25o

$ php xor-cipher.php A < out.dat
This is a test.
This is only a test.

```

---

## Perl 30 bytes

```
$k=pop;s/./print$&^$k/egsfor<>

```

I/O is the same as for the PHP solution above.
> 4 votes

# Answer
# Brainfuck - 269

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

```
> 6 votes

# Answer
## C, 61 59 bytes

Quite simple, and very similar to primo's solution.
First parameter is the key, in decimal, reads stdin, writes stdout.
The only tricky part is using `~getchar`, so `EOF` becomes `0` and terminates the loop, then printing `c^~key`, where the additional `~` undoes the previous one.

```
main(c,v)int*v;{
    while(c=~getchar())putchar(c^~atoi(v[1]));
}

```
> 4 votes

# Answer
# The Powder Toy, 598 bytes, 8 particles

Only 8 particles and O(n) speed. :) (This is unsurprisingly difficult in TPT for most tasks unless you know subframe really well; I do not.)

This creation takes input at a rate of 8 bits per frame, with a 8 bit word size. If you input the xor byte 3 times at once (24bit), then you can process 3 bytes of the stream per frame.

Reversible xxd dump:

```
00000000: 4f50 5331 5d04 9960 151d 0c00 425a 6839  OPS1]..`....BZh9
00000010: 3141 5926 5359 5cdf 0ea9 006c 37ff ffff  1AY&SY\....l7...
00000020: f553 0252 11d7 423f 27df b6bf f7df e340  .S.R..B?'......@
00000030: 0200 4000 0400 1050 0008 0000 2002 0840  ..@....P.... ..@
00000040: 01fc 69b5 3508 44d1 0068 0034 1ea0 6800  ..i.5.D..h.4..h.
00000050: 0d03 4034 6800 000d 0814 d4fd 2626 4c89  ..@4h.......&&L.
00000060: a68d 0190 0000 d343 4069 9003 4d03 8686  .......C@i..M...
00000070: 4d34 34c8 d0d3 2320 c8c8 d0c8 0c4d 1934  M44...# .....M.4
00000080: 0193 2310 c244 9232 86a6 327a 4191 a260  ..#..D.2..2zA..`
00000090: 0046 2604 6260 8600 d263 4dbb b2e2 d1e3  .F&.b`...cM.....
000000a0: 21f5 cd39 7920 2062 4360 0924 1e6c 4021  !..9y  bC`.$.l@!
000000b0: 2224 22bb f2b3 9fbd 77d2 c6ad dc4e 4b3c  "$".....w....NK<
000000c0: 9fac 12d3 9ad6 6cae 6940 2409 08b2 9961  ......l.i@$....a
000000d0: a30e 9a64 b599 68b6 e10a 87ac c869 64a6  ...d..h......id.
000000e0: 6977 e649 2102 4227 62ce 6214 0641 cc41  iw.I!.B'b.b..A.A
000000f0: b575 205e 255c 520c 4603 15cc a222 4325  .u ^%\R.F...."C%
00000100: 1df7 2106 df63 c319 3bfd d191 25a8 0020  ..!..c..;...%..
00000110: 0484 3ab5 62ab ef4d 0902 4236 d9d3 eb8d  ..:.b..M..B6....
00000120: 23f1 3ee4 8113 30c0 6435 d122 2572 033d  #.>...0.d5."%r.=
00000130: 9edb f17a ac03 636c 60c0 82b9 1226 125c  ...z..cl`....&.\
00000140: 20c0 8855 972a ac26 833a 8466 8143 208a   ..U.*.&.:.f.C .
00000150: 4c9d 811d 9ec1 d800 356e ad3f 9b51 e0a0  L.......5n.?.Q..
00000160: 8a96 54ff 891d c761 71c3 3618 5844 f4f2  ..T....aq.6.XD..
00000170: 5453 ac54 d94a b86d 8261 11c9 3b70 4222  TS.T.J.m.a..;pB"
00000180: 9bfb 2445 4443 f202 f004 5b14 e01d 1696  ..$EDC....[.....
00000190: e06d 7348 e262 981e 847f 9e4d ba42 9040  .msH.b.....M.B.@
000001a0: d740 45b1 8fd9 7a62 20b8 7850 a40b a2a1  .@E...zb .xP....
000001b0: 34a5 a790 c2ab 8af3 2bec d254 9b50 c39e  4.......+..T.P..
000001c0: 1b74 9ec7 3627 63b2 f9da f832 09a4 9406  .t..6'c....2....
000001d0: 135c 78e3 0a29 a9ac 991a 44da a6d9 e38c  .\x..)....D.....
000001e0: 4886 f6db 9a65 3ce9 bd32 b3a9 8522 a053  H....e<..2...".S
000001f0: 5ee2 a930 527b 8dd6 f7b5 b5a9 15d7 b771  ^..0R{.........q
00000200: 8d2f bace a196 d95b f48c a895 05a1 0402  ./.....[........
00000210: c2c3 48cc 8e90 3567 0b0c acab 0eb2 1ce2  ..H...5g........
00000220: 80e9 40e7 1432 82fe b141 4412 b86b e551  ..@..2...AD..k.Q
00000230: 33bf 6160 a733 e306 cca3 5479 bf93 9a21  3.a`.3....Ty...!
00000240: 8921 0024 2342 f402 4090 8f91 7724 5385  .!.$#B..@...w$S.
00000250: 0905 cdf0 ea90

```

### I/O

This creation takes the byte to XOR data by in particle #0, and the data stream at particle #4. Output is given by any particle at X 501. Once the stream is over it decodes the last byte(s) forever.

The XOR byte must have the 30th bit set, and the data byte must NOT have the 30th bit set. This is due to the fact that a input of 0 will cause no output if this is not done in this manner (TPT filt logic restriction, cannot be worked around)

### What does it look like?

\[TODO\]

### How does it work?

\[Also TODO. Sorry.\]
> 4 votes

# Answer
**Python, 78 chars**

```
from sys import argv as v

print ''.join(chr(ord(v[1])^ord(i)) for i in open(v[2]).read())

```

Must be run like:

```
python solution.py <key> <input_file> > <output_file>

```

Where `solution.py` is the python file that contains the above code, key is the single byte to XOR, `input_file` is the file to be encrypted and `output_file` will contain the decrypted output.

I am not sure if it matches your solution (as per "...that produces the same end result will be selected") since your example doesn't seem to produce output. However, it does successfully decrypt an encrypted file with the same key byte.

Since whitespace doesn't count, I used the following code to count chars:

```
>>> with open('solution.py') as f:
...     text = f.read()
...
>>> len(text) - text.count('\n') - text.count(' ') # There are no tabs in this code
78

```
> 2 votes

# Answer
# Python 75

```
import sys
for j in sys.stdin:print''.join(chr(int(sys.argv[1])^ord(i))for i in j),

```

The hardest requirement was not to keep the whole file in memory.

Usage:

```
python xor.py 123 <file.in >file.out

```
> 2 votes

# Answer
### GolfScript, 16 characters

```
"#{$*}"~{^}+%:n;

```

Usage is as given above - the key (numeric) passed as parameter while input/output is through console:

```
golfscript.rb xor.gs 42 <in.txt >out.txt

```

*Edit:* The issues with the trailing newline are now solved.
> 2 votes

# Answer
# Postscript ~~101~~ 67

```
(]){exch def}def
ARGUMENTS aload pop(w)file/O](r)file/I]cvi/K]{O I read not{exit}if K xor write}loop

```

The 67 byte version is equivalent to the above with all executable system names replaced by binary tokens. It is produced as output by this program (which shows a hex representation).

```
(xorb.ps)(w)file
<
    285D297B923E92337D9233
    415247554D454E54539202927528772992412F4F5D
    28722992412F495D922C2F4B5D
    7B4F2049927B92707B92407D92544B92C192BC7D9265
>
writestring

```

Invoke with ghostscript's argument-processing option `--`.

```
josh@Z1 ~
$ gs -dNODISPLAY -- xorw.ps
GPL Ghostscript 9.06 (2012-08-08)
Copyright (C) 2012 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.

josh@Z1 ~
$ xxd xorb.ps
0000000: 285d 297b 923e 9233 7d92 3341 5247 554d  (]){.>.3}.3ARGUM
0000010: 454e 5453 9202 9275 2877 2992 412f 4f5d  ENTS...u(w).A/O]
0000020: 2872 2992 412f 495d 922c 2f4b 5d7b 4f20  (r).A/I].,/K]{O
0000030: 4992 7b92 707b 9240 7d92 544b 92c1 92bc  I.{.p{.@}.TK....
0000040: 7d92 65                                  }.e

josh@Z1 ~
$ gs -dNODISPLAY -- xorb.ps 42 xor.ps xor.ps.out
GPL Ghostscript 9.06 (2012-08-08)
Copyright (C) 2012 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.

josh@Z1 ~
$ gs -dNODISPLAY -- xorb.ps 42 xor.ps.out xor.rev
GPL Ghostscript 9.06 (2012-08-08)
Copyright (C) 2012 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.

josh@Z1 ~
$ diff xor.ps xor.rev

josh@Z1 ~
$

```
> 1 votes

# Answer
# q/kdb+, 35 bytes (41 including whitespace)

**Solution:**

```
{x 1:0b sv'(0b vs 4h$y)<>/:0b vs'read1 x}

```

**Example:**

```
q)read0 `:test.txt
"Hello World!"
"Welcome to PPCG :)"
q){x 1:0b sv'(0b vs 4h$y)<>/:0b vs'read1 x}[`:test.txt;"A"]
`:test.txt
q)read0 `:test.txt
"\t$--.a\026.3-%`"
"\026$-\".,$a5.a\021\021\002\006a{h"
q){x 1:0b sv'(0b vs 4h$y)<>/:0b vs'read1 x}[`:test.txt;"A"]
`:test.txt
q)read0 `:test.txt
"Hello World!"
"Welcome to PPCG :)"

```

**Explanation:**

Read in the file as a bytestream, convert to bitstream, convert key to bitstream and xor `<>` with each byte. Convert back to bytestream and write back to file:

```
{x 1:0b sv'(0b vs 4h$y)<>/:0b vs'read1 x} / ungolfed solution
{                                       } / lambda function taking x and y as implicit parameters
                                 read1 x  / read file x as bytestream
                           0b vs'         / convert each byte to bits (boolean list)
                       <>/:               / xor (<>) left with each-right (/:)
           (          )                   / do this together
                  4h$y                    / convert key to a byte
            0b vs                         / convert byte to bits (boolean list)
     0b sv'                               / convert each list of bits to a byte
 x 1:                                     / write bytes to file x

```

**Notes:**

If we drop to the `k` prompt we have a 32 byte solution (33 inc whitespace), pretty much a straight port except we dont have `<>` for xor.

```
{x 1:0b/:'~(0b\:4h$y)=/:0b\:'1:x}

```

**K4 Example:**

```
  {x 1:0b/:'~(0b\:4h$y)=/:0b\:'1:x}[`:test.txt;"A"]
`:test.txt
  0:`:test.txt
,"\t$--.a\026.3-%`K\026$-\".,$a5.a\021\021\002\006K"
  {x 1:0b/:'~(0b\:4h$y)=/:0b\:'1:x}[`:test.txt;"A"]
`:test.txt
  0:`:test.txt
("Hello World!";"Welcome to PPCG")

```
> 0 votes

# Answer
# Tcl, 120 bytes

```
set t [open t w]
lmap x [split [read [open $argv]] ""] {puts -nonewline $t [format %c [expr 255^[scan $x %c]]]}
close $t

```

Try it online!
> 0 votes

# Answer
# Chip, 39 bytes (62 incl. whitespace)

```
 A0   C2   E4   G6
a{L}bc{L}de{L}fg{L}hS!9
  1B   3D   5F   7H

```

Try it online!

The first byte of stdin is the key, all other bytes are the message.

The elements `H-A` are the eight bits of each input byte, `h-a` are the eight bits of each output byte, and `7-0` are the eight bits of the stack head.

On the first cycle, `S!9` causes the input bits to be written to the stack (along with the pairs like `A0`, `1B`...), and prevents any output.

On subsequent cycles, the input bits are xor'd with their corresponding stack bits to produce the output bits. A single bit is computed like this:

```
 A0
a{'

```

or like this:

```
,}b
1B

```

(which are just rotations of each other). Those two patterns can be made to overlap slightly, and we use four of each to cover all eight bits.
> 0 votes

---
Tags: code-golf
---


title: Mutually Exclusive Quines

text:
# Question
Title: Mutually Exclusive Quines
Your challenge is simple. Write two programs that share no characters which output each other.

## Example

Two programs **P** and **Q** are mutually exclusive quines if:

1. **P** outputs **Q**
2. **Q** outputs **P**
3. There is no character *c* which belongs to both **P** and **Q**
4. Each program **P** and **Q** are **proper quines**
    1. This counts empty quines and quines that read their own (or the other's) source code as **invalid**.

## More rules

* The shortest combined length of these programs wins. That is, size(**P**) + size(**Q**) is your score, and the lowest score wins.
* Both programs are in the same language
* Each program may be a full program or function, and they need not be the same.
    + For example, **P** may be a full program and **Q** may be a function.

## Verification

This Try it online! snippet here can verify whether or not two programs are mutually exclusive. The inputs are put in the first two arguments.

# Answer
> 40 votes
# \>\<\>, Score: 41+41 = 82

Edit: both contained a 3. Fixed

```
'd3*}>a!o-!<<8:5@lI55>@z:5ll55>>q:>|q::|,

```

and

```
"r00gr40g44++bb+0p64++?b6+0.22#eW4s )Z

```

Try it online! (swap the lines to get the other output) With verification this time!

`><>` is an especially hard language to use here, as there is only one way to output characters, the command `o`. Fortunately, we can use the *p*ut command to place an `o` in the source code during execution, like in my Programming in a Pristine World answer.

This one took a *lot* of trial and error. I started off with the two mutually exclusive programs:

```
'd3*}>N!o-!<<data

```

and

```
"r00gr40g8+X0pN+?Y0.data

```

Each one transforms itself and its data by N, the first one subtracting and the second adding. It then outputs this in reverse. The point is that the data after each program is the other program in reverse, shifted by N. (`X` is the cell number where the program needs to put the `o` and Y is the cell where the pointer loops back to. `?` is where the `o` is put).

Both follow the same structure, represented in different ways. They run a string literal over the entire code, adding it to the stack. They recreate the string literal command they used and put it at the bottom of the stack. They loop over the stack, adding/subtracting N to each character and printing them.

The first program uses `'` as the string literal, and the simple `d3*}` to create the value 39 and push it to the bottom of the stack. The second uses `"` as the string literal with the same function. It `r`everses the stack, `g`ets the character at cell 0,0 and reverses the stack again. It then `g`ets the value at cell 4,0 (`g`) and adds 8 to it to get `o` and puts that at X.

Both programs use a different method of looping. The first program uses the skip command (`!`) to run only half the instructions while going left, reverses direction and runs the other half. The second uses the jump command (`.`) to skip backwards to the start of the loop at cell Y. Both of these run until there are no more items on the stack and the program errors.

I ran into a number of problems with most of the lower values of N, because shifting one character would turn it into another character essential for that program (and therefore couldn't be used as data for the other program) or two characters from the two programs would shift into the same character. For example:

1. `+`+1 = `,` = `-`-1
2. `.`+2 = `0`
3. `*` = `-`-3
4. `g`+4 = `k` = `o`-4

etc.

Eventually I got to 10 (`a`), where I was able to avoid these issues. There might be a shorter version where the shifts are reversed, and the first program is adding N while the second subtracts it. This might be worse off though, as the first program is generally on the lower end of the ASCII scale, so subtracting is better to avoid conflicts.

# Answer
> 19 votes
# Forth (64-bit little-endian gforth), 428 + 637 = 1065 bytes

```
s"	:	l	bl	-	;	:	m	l	emit	;	:	s	space	;	:	z	m	m	m	m	s	;	:	p	.	't	'i	'm	'e	z	;	'e	'r	'e	'h	z	:	q	>r	char	l	bl	l	do	dup	@	.	'L	m	s	cell+	loop	r>	.	;	:	n	'e	'p	'y	't	z	;	q	;	's	p	'B	l	p	#tab	p	'p	'u	'd	'Q	char+	z	n	'B	l	p	n":	l	bl	-	;	:	m	l	emit	;	:	s	space	;	:	z	m	m	m	m	s	;	:	p	.	't	'i	'm	'e	z	;	'e	'r	'e	'h	z	:	q	>r	char	l	bl	l	do	dup	@	.	'L	m	s	cell+	loop	r>	.	;	:	n	'e	'p	'y	't	z	;	q	;	's	p	'B	l	p	#tab	p	'p	'u	'd	'Q	char+	z	n	'B	l	p	n

```

```
HERE 3245244174817823034 , 7784873317282429705 , 665135765556913417 , 7161128521877883194 , 682868438367668581 , 679209482717038957 , 680053688600562035 , 678116140452874542 , 682868623551327527 , 680649414991612219 , 682868636436227367 , 7136360695317203258 , 7809815063433470312 , 8458896374132993033 , 5487364764302575984 , 7810758020979846409 , 680166068077538156 , 4181938639603318386 , 8081438386390920713 , 8793687458429085449 , 2812844354006760201 , 7784826166316108147 , 676210045490917385 , 681493840106293616 , 7521866046790788135 , 679491013524025953 , 7928991804732031527 , 216 115 EMIT 34 EMIT 9 EMIT 2DUP TYPE 34 EMIT TYPE

```

Try it online!

Verification script

Thanks to @Nathaniel for the idea of using Forth - he reminded me in the comments that **Forth is not case-sensitive**. Then came the mood swings - I've been finding reasons why this will not work, followed by solutions to these problems, again and again. All while spinning my indoor training bike like an oversided and misshaped fidget spinner (you just have to grab one end of the handle bar and tilt it a bit).

Before writing these programs, I drafted what characters can be used by which program. Specifically, the second program can only use uppercase letters, decimal digits, tabs, and commas. This would mean that the first program is all lowercase, but I used some uppercase letters for their ASCII values.

Because tabs are unwieldy, I'll use spaces in the explanation instead.

The first program is of the form `s" code"code` \- the `s"` starts a string literal, which is then processed by the second copy of the code - a standard quine framework. However, instead of outputting its own source code, it will create the other program, which looks like this:

* `HERE`
* For each 8 bytes in the original string, `64-bit-number-literal ,`
* `length-of-the-string`
* `115 EMIT 34 EMIT 9 EMIT 2DUP TYPE 34 EMIT TYPE`

This uses Forth's data space. `HERE` returns the pointer to the end of the currently allocated data space area, and `,` appends a cell filled with a number to it. Therefore, the first three bullet points can be seen like a string literal created using `s"`. To finish the second program off:

* `EMIT` outputs a character given its ASCII value, so:
    + `115 EMIT` prints a lowercase `s`
    + `34 EMIT` prints the quote character `"`
    + `9 EMIT` prints a tab
* `2DUP` duplicates the top two elements on the stack `( a b -- a b a b )`, here it's the pointer to and the length of the string
* `TYPE` prints a string to output the first copy of the code
* `34 EMIT` prints the closing quote `"`, and finally
* `TYPE` outputs the second copy of the code

Let's see how the first program works. In many cases numbers have to be avoided, which is done using the `'x` gforth syntax extension for character literals, and sometimes subtracting the ASCII value of space, which can be obtained using `bl`:

```
s" ..."      \ the data
: l bl - ;   \ define a word, `l`, that subtracts 32
: m l emit ; \ define a word, `m`, that outputs a character. Because 32 is
             \ subtracted using `l`, lowercase characters are converted to
             \ uppercase, and uppercase characters are converted to some
             \ symbols, which will become useful later
: z m m m m space ; \ `z` outputs four characters using `m`, followed by a
                    \ space. This is very useful because all words used in the
                    \ second program are four characters long
: p . 't 'i 'm 'e z ; \ define a word, `p`, that, given a number, outputs that
                      \ number, followed by a space, `EMIT`, and another space
'e 'r 'e 'h z \ here is where outputting the second program starts - `HERE `
: q \ define a helper word, `q`, that will be called only once. This is done
    \ because loop constructs like do...loop can't be used outside of a word.
  >r \ q is called with the address and the length of the data string. >r saves
     \ the length on the return stack, because we don't need it right now. While
     \ it might seem like this is too complicated to be the best way of doing
     \ this for codegolf, just discaring the length would be done using four
     \ characters - `drop`, which would give you the same bytecount if you could
     \ get the length again in... 0 characters.
  char l \ get a character from after the call to q, which is `;`, with the
         \ ASCII value of $3B, subtract $20 to get $1B, the number of 64-bit
         \ literals necessary to encode the string in the second program.
  bl l \ a roundabout way to get 0
  do   \ iterate from 0 (inclusive) to $1B (exclusive)
    \ on the start of each iteration, the address of the cell we are currently
    \ processing is on the top of the stack.
    dup @ . \ print the value. The address is still on the stack.
    'L m space \ the ASCII value of L is exactly $20 larger than the one of ,
    cell+ \ go to the next cell
  loop
  r> . \ print the length of the string
;
: n 'e 'p 'y 't z ; \ define a word, `n`, that outputs `TYPE`
q ; \ call q, and provide the semicolon for `char` (used to encode the length
    \ of the string in 64-bit words). Changing this to an uppercase U should
    \ make this work on 32-bit systems, but I don't have one handy to check that
's p \ print the code that outputs the lowercase s
'B l p \ likewise, 'B l <=> $42 - $20 <=> $22 <=> the ASCII value of a comma
#tab p \ print the code that outputs a tab
'p 'u 'd 'Q char+ z \ char+ is the best way to add 1 without using any digits.
                    \ it is used here to change the Q to an R, which can't be
                    \ used because of `HERE` in the second program. R has an
                    \ ASCII value exactly $20 larger than the ASCII value of 2,
                    \ so this line outputs the `2DUP`.
n 'B l p n \ output TYPE 34 EMIT TYPE to finish the second program. Note the
           \ that the final `n` introduces a trailing space. Trying to remove
           \ it adds bytes.

```

To finish this off, I'd like to say that I tried using `EVALUATE`, but the second program becomes larger than both of the ones presented above. Anyway, here it is:

```
: s s" ; s evaluate"s" : l bl - ; : m l emit ; : d here $b $a - allot c! ; : c here swap dup allot move ; : q bl l do #tab emit dup @ bl l u.r cell+ #tab emit 'L m loop ; here bl 'B l 's bl 's bl 'Z l d d d d d d d -rot c bl 'B l 's 'B l d d d d s c 'B l d c 'e 'r 'e 'h m m m m 'A q #tab emit 'e 'p 'y 't m m m m"; s evaluate

```

If you manage to golf this down enough to outgolf my `s" ..."...` approach, go ahead and post it as your own answer.

# Answer
> 17 votes
# Perl, ~~(311+630 = 941 bytes)~~ 190+198 = 388 bytes

Both programs print to standard output.

The first perl program contains mostly printable ASCII characters and newlines, and it ends in exactly one newline, but the two letter ÿ represents the non-ASCII byte \xFF:

```
@f='^"ÿ"x92;@f=(@f,chr)for 115,97,121,36,126,191,153,194,216,113;print@f[1..5,5,10,5..9,0,9,0,5]'^"ÿ"x92;@f=(@f,chr)for 115,97,121,36,126,191,153,194,216,113;print@f[1..5,5,10,5..9,0,9,0,5]

```

The second one contains mostly non-ASCII bytes, including several high control characters that are replaced by stars in this post, and no newlines at all:

```
say$~~q~¿*ÂØ¡Ý*Ý*ÆÍÄ¿*Â×¿*Ó***Ö***ßÎÎÊÓÆÈÓÎÍÎÓÌÉÓÎÍÉÓÎÆÎÓÎÊÌÓÎÆËÓÍÎÉÓÎÎÌÄ*****¿*¤ÎÑÑÊÓÊÓÎÏÓÊÑÑÆÓÏÓÆÓÏÓÊ¢Ø¡Ý*Ý*ÆÍÄ¿*Â×¿*Ó***Ö***ßÎÎÊÓÆÈÓÎÍÎÓÌÉÓÎÍÉÓÎÆÎÓÎÊÌÓÎÆËÓÍÎÉÓÎÎÌÄ*****¿*¤ÎÑÑÊÓÊÓÎÏÓÊÑÑÆÓÏÓÆÓÏÓÊ¢~

```

A hexdump of the first program with `xxd` is:

```
00000000: 4066 3d27 5e22 ff22 7839 323b 4066 3d28  @f='^"."x92;@f=(
00000010: 4066 2c63 6872 2966 6f72 2031 3135 2c39  @f,chr)for 115,9
00000020: 372c 3132 312c 3336 2c31 3236 2c31 3931  7,121,36,126,191
00000030: 2c31 3533 2c31 3934 2c32 3136 2c31 3133  ,153,194,216,113
00000040: 3b70 7269 6e74 4066 5b31 2e2e 352c 352c  ;print@f[1..5,5,
00000050: 3130 2c35 2e2e 392c 302c 392c 302c 355d  10,5..9,0,9,0,5]
00000060: 275e 22ff 2278 3932 3b40 663d 2840 662c  '^"."x92;@f=(@f,
00000070: 6368 7229 666f 7220 3131 352c 3937 2c31  chr)for 115,97,1
00000080: 3231 2c33 362c 3132 362c 3139 312c 3135  21,36,126,191,15
00000090: 332c 3139 342c 3231 362c 3131 333b 7072  3,194,216,113;pr
000000a0: 696e 7440 665b 312e 2e35 2c35 2c31 302c  int@f[1..5,5,10,
000000b0: 352e 2e39 2c30 2c39 2c30 2c35 5d0a       5..9,0,9,0,5].

```

And a hexdump of the second program is:

```
00000000: 7361 7924 7e7e 717e bf99 c2d8 a1dd 00dd  say$~~q~........
00000010: 87c6 cdc4 bf99 c2d7 bf99 d39c 978d d699  ................
00000020: 908d dfce ceca d3c6 c8d3 cecd ced3 ccc9  ................
00000030: d3ce cdc9 d3ce c6ce d3ce cacc d3ce c6cb  ................
00000040: d3cd cec9 d3ce cecc c48f 8d96 918b bf99  ................
00000050: a4ce d1d1 cad3 cad3 cecf d3ca d1d1 c6d3  ................
00000060: cfd3 c6d3 cfd3 caa2 d8a1 dd00 dd87 c6cd  ................
00000070: c4bf 99c2 d7bf 99d3 9c97 8dd6 9990 8ddf  ................
00000080: cece cad3 c6c8 d3ce cdce d3cc c9d3 cecd  ................
00000090: c9d3 cec6 ced3 ceca ccd3 cec6 cbd3 cdce  ................
000000a0: c9d3 cece ccc4 8f8d 9691 8bbf 99a4 ced1  ................
000000b0: d1ca d3ca d3ce cfd3 cad1 d1c6 d3cf d3c6  ................
000000c0: d3cf d3ca a27e                           .....~

```

In the second program, the quoted string (189 bytes long, delimited by tildes) is the entire first program except the final newline, only encoded by bitwise complementing each byte. The second program simply decodes the string by complementing each of the bytes, which the `~` operator does in perl. The program prints the decoded string followed by a newline (the `say` method adds a newline).

In this construction, the decoder of the second program uses only six different ASCII characters, so the first program can be practically arbitrary, as long as it only contains ASCII characters and excludes those six characters. It's not hard to write any perl program without using those five characters. The actual quine logic is thus in the first program.

In the first program, the quine logic uses a 11 word long dictionary `@f`, and assembles the output from those words. The first words repeats most of the source code of the first program. The rest of the words are specific single characters. For example, word 5 is a tilde, which is the delimiter for the two string literal in the second program. The list of numbers between the brackets is the recipe for which words to print in what order. This is a pretty ordinary general construction method for quines, the only twist in this case is that the first dictionary words is printed with its bytes bitwise complemented.

# Answer
> 14 votes
# Haskell, 306 + 624 = 930 bytes

Program 1: An anonymous function taking a dummy argument and returning a string.

```
(\b c()->foldr(\a->map pred)b(show()>>c)`mappend`show(map(map fromEnum)$tail(show c):pure b))"İĴİóđđđÝöÝâÝæÝääē××êääē××İēÀħđĮâħēĕóİóòòĮááħááđéêâéêēááĮÀħ""(\b c()->foldr(\a->map pred)b(show()>>c)`mappend`show(map(map fromEnum)$tail(show c):pure b))"

```

Try it online!

Program 2: `q[[40,...]]` at the end is an anonymous function taking a dummy argument and returning a string.

```
z~z=[[['@','0'..]!!4..]!!z]
q[x,q]_=z=<<x++q++[34,34]++x
q[[40,92,98,32,99,40,41,45,62,102,111,108,100,114,40,92,97,45,62,109,97,112,32,112,114,101,100,41,98,40,115,104,111,119,40,41,62,62,99,41,96,109,97,112,112,101,110,100,96,115,104,111,119,40,109,97,112,40,109,97,112,32,102,114,111,109,69,110,117,109,41,36,116,97,105,108,40,115,104,111,119,32,99,41,58,112,117,114,101,32,98,41,41,34],[304,308,304,243,273,273,273,221,246,221,226,221,230,221,228,228,275,215,215,234,228,228,275,215,215,304,275,192,295,273,302,226,295,275,277,243,304,243,242,242,302,225,225,295,225,225,273,233,234,226,233,234,275,225,225,302,192,295]]

```

Try it online!

Character set 1 (includes space):

```
 "$()-:>E\`abcdefhilmnoprstuw×ÝáâäæéêñòóöđēĕħĮİĴ

```

Character set 2 (includes newline):

```
!'+,.0123456789<=@[]_qxz~

```

Since only set 1 contains non-ASCII characters, their UTF-8 bytes are also disjoint.

# How it works

* Program 1 is generally written with lambda expressions, spaces and parentheses, free use of builtin alphanumeric functions, and with the quine data as string literals at the end.

+ Program 1's own core code is turned into string literal data simply by surrounding it with quote marks.
        - To support this, every backslash is followed by `a` or `b`, which form valid escape sequences that roundtrip through `show`.
        - Another tiny benefit is that `a`, `b` and `c` are the only lower case letters whose ASCII codes are less than 100, saving a digit in the numerical encoding used by program 2.
    + The string literal encoding of program 2's core code is more obfuscated by using non-ASCII Unicode: Every character has 182 added to its code point to ensure there is no overlap with the original characters.
        - 182 used to be 128, until I realized I could abuse the fact that 182 is twice the length of the string literal for program 1's code to shorten the decoding. (As a bonus, program 2 can use newlines.)
* Program 2 is generally written with top level function equations (except for the final anonymous one), character literals and decimal numbers, list/range syntax and operators, and with the quine data as a list of lists of `Int`s at the end.

+ Program 1's core code is encoded as a list of its code points, with a final double quote.
    + Program 2's core code is encoded as the list of code points of the string literal used in program 1, still shifted upwards by 182.

# Walkthrough, program 1

* `b` and `c` are the values of the string literals for program 2 and 1, respectively, given as final arguments to the lambda expression. `()` is a dummy argument solely to satisfy PPCG's rule that the program should define a function.
* `foldr(\a->map pred)b(show()>>c)` decodes the string `b` to the core code of program 2 by applying `map pred` to it a number of times equal to the length of `show()>>c == c++c`, or `182`.
* `tail(show c)` converts the string `c` to the core code of program 1, with a final double quote appended.
* `:pure b` combines this in a list with the string `b`.
* `map(map fromEnum)$` converts the strings to lists of code points.
* ``mappend`show(...)` serializes the resulting list of lists and finally appends it to the core code of program 2.

# Walkthrough, program 2

* The toplevel `z~z=[[['@','0'..]!!4..]!!z]` is a function converting code points back to characters (necessary to write since not all the characters in `toEnum` are available.)
    + Its code point argument is also called `z`. The laziness marker `~` has no effect in this position but avoids a space character.
    + `['@','0'..]` is a backwards stepping list range starting at ASCII code 64, then jumping 16 down each step.
    + Applying `!!4` to this gives a `\NUL` character.
    + Wrapping that in a `[ ..]` range gives a list of all characters, which `!!z` indexes.
    + The character is finally wrapped in a singleton list. This allows mapping the function `z` over lists using `=<<` instead of the unavailable `map` and `<$>`.
* The toplevel `q[x,q]_=z=<<x++q++[34,34]++x` is a function constructing program 1 from the quine data list.
    + `x` is the data for the core of program 1 (including a final double quote) and the inner `q` is the obfuscated data for the core of program 2. `_` is another dummy argument solely to make the final anonymous function a function instead of just a string.
    + `x++q++[34,34]++x` concatenates the pieces, including two double quote marks with ASCII code 34.
    + `z=<<` constructs program 1 by mapping `z` over the concatenation to convert from code points to characters.
* The final `q[[40,...]]` is an anonymous function combining `q` with the quine data.

# Answer
> 7 votes
# Jelly, <sub> ~~128 90 87 86 85 79~~</sub> 16 + 32 = 48 bytes

```
“OṾ⁾ọṙŒs”OṾ⁾ọṙŒs

```

Try it online!

```
79,7806,8318,7885,7769,338,115ỌṘ

```

Try it online!

The first program does the following:

```
“OṾ⁾ọṙŒs”OṾ⁾ọṙŒs
“OṾ⁾ọṙŒs”          String literal: 'OṾ⁾ọṙŒs'
         O         ord: [79, 7806, 8318,...]
          Ṿ        Uneval. Returns '79,7806,8318,7885,7769,338,115'
           ⁾ọṙ     Two character string literal: 'ọṙ'
              Œs   Swap case the two char literal: 'ỌṘ'.

```

This leaves the strings `79,7806,8318,7885,7769,338,115` and `ỌṘ` as the two arguments of the chain and they are implicitly concatenated and printed at the end.

The second program calculates the `chr` () of the list of numbers which returns `OṾ⁾ọṙŒs`.  prints `“OṾ⁾ọṙŒs”` (with quotes) and returns the input, leaving `“OṾ⁾ọṙŒs”OṾ⁾ọṙŒs` as the full output.

# Answer
> 5 votes
# Gol\>\<\>, <sub>~~23 + 23 = 46~~</sub> <sub>~~22 + 22 = 44~~</sub> 20 + 20 = 40 bytes

```
"lF{3+|3d*HqlJJJQpp2

```

Try it online!

```
'5ssTMMMotK-g6.6~Io

```

Try it online!

Verify it online!

### How they work

```
"lF{3+|3d*HqlJJJQpp2

"..."        Push everything to the stack
 lF{3+|      Add 3 to everything on the stack
       3d*   Push 39 `'`
          H  Print everything on the stack (from the top) and halt

'5ssTMMMotK-g6.6~Io

'...'        Push everything to the stack
 5ss         Push 37 (34 `"` + 3)
    T    t   Loop indefinitely...
     MMMo      Decrement 3 times, pop and print
               At the end, `o` tries to print charcode -3, which is fishy (thanks Jo King)
               Program terminates

```

Adapted from Jo King's \>\<\> answer. Having many more alternative commands for output and repeat, there was no need for `g` or `p`, and the two main bodies became much shorter.

Another main difference is that I generate the opponent's quote directly at the top of the stack. This way, it was slightly easier to keep the invariant of `quote + my code + opponent code(reversed and shifted)`.

---
Tags: code-challenge, quine
---


title: Product of Digits

text:
# Question
Title: Product of Digits
For a given positive integer number N, write a complete program to find the minimal natural M such that the product of digits of M is equal N. N is less than 1,000,000,000. If no M exists, print -1. Your code should not take more than 10 secs for any case.

```
Sample Inputs
1
3
15
10
123456789
32
432
1296

Sample Outputs
1
3
35
25
-1
48
689
2899

```

# Answer
### Golfscript, 45 43 40 chars

```
~9{{1$1$%!{\1$/1$}*}12*(}8*>{];-1}*]$1or

```

Replaces version which didn't group small primes into powers and saves 8 chars while doing so. Note: 12 = floor(9 log 10 / log 5).

Acknowledgements: two characters saved by nicking a trick from @mellamokb; 3 saved with a hint from @Nabb.
> 4 votes

# Answer
## Javascript (84 78 76 74 72 70 68)

```
n=prompt(m="");for(i=9;i-1;)n%i?i--:(m=i+m,n/=i);alert(n-1?-1:m?m:1)

```

http://jsfiddle.net/D3WgU/7/

**Edit:** Borrowed input/output idea from other solution, and shorter output logic.

**Edit 2:** Saved 2 chars by removing unneeded braces in `for` loop.

**Edit 3:** Saved 2 chars by rewriting `while` loop as `if` statement with `i++`.

**Edit 4:** Saved 2 chars by moving around and reducing operations on `i`.

**Edit 5:** Convert if statement into ternary format saving 2 more chars.

**Edit 6:** Save 2 chars by moving `i--` into true part of ternary, remove `++i`.
> 6 votes

# Answer
## JavaScript, ~~88~~ ~~72~~ ~~78~~ ~~74~~ ~~69~~ 68

```
~~for(s='',i=2,m=n=prompt();i<m;i++)while(!(n%i)){if(i>9){alert(-1);E()}n/=i;s+=i}alert(s)~~
```
~~4 characters longer, but actually an executable script (as opposed to a function).~~

~~Edit: Using ideas from the other JavaScript, I can reduce it to this:~~

~~```
for(s='',i=9,n=prompt();i>1;i--)for(;!(n%i);n/=i)s=i+s;alert(n-1?-1:s?s:1)

```~~

~~**Finally!** A 69-character solution, only uses 1 for loop ;)~~

~~```
for(s='',i=9,n=prompt();i>1;n%i?i--:[n/=i,s=i+s]);alert(n-1?-1:s?s:1)

```~~

Okay, shaved off one comma.

```
for(i=9,n=prompt(s='');i>1;n%i?i--:[n/=i,s=i+s]);alert(n-1?-1:s?s:1)

```
> 4 votes

# Answer
## awk (63 61 59 58 57)

```
{for(i=9;i>1;$1%i?i--:($1/=i)<o=i o);print 1<$1?-1:o?o:1}

```
> 4 votes

# Answer
## Perl (75) (72)

```
$d=shift;map{$m=$_.$m,$d/=$_ until$d%$_}reverse 2..9;print$d-1?-1:$m||1

```

inspired by mellamokb's javascript code; meant to be run with a parameter
> 3 votes

# Answer
## GolfScript (60 57)

```
~[{9,{)}%{\.@%!},)\;.@@/.9>2$1>&}do])[.])@@{1>},+\9>[-1]@if$

```

```
~{9,{)}%{\.@%!},)\;.@@/.9>2$1>&}do])[.])@@{1>},+$\9>-1@if

```

**Edit**

Ok, I think this version gives correct output for every case now :-)

**Edit 2**

Shaved off 3 chars per @Peter's suggestions.
> 3 votes

# Answer
## Haskell

```
f n=head([m|m<-[1..10^9],product(map(read.return)$show m)==n]++[-1])

```
> 3 votes

# Answer
## Windows PowerShell, 87

```
if(($n="$args")-le1){$n;exit}(-1,-join(9..2|%{for(;!($n%$_)){$_;$n/=$_}}|sort))[$n-eq1]

```
> 2 votes

# Answer
# Perl (68)

```
$x=pop;map{$_-=11;$x/=$_,$@=-$_.$@until$x%$_}1..9;print!$x?-1:$@||1

```

It *seems* like the awesome trick that @mellamokb uses in javascript to avoid the nested loop would translate well to perl but it comes out much more verbose because you cannot use the `foreach` style loop any longer. It's also a pity that perl does not think `map` is a loop else `redo` would come in handy.
> 2 votes

# Answer
### scala 106 chars:

```
def p(n:Int,l:Int=9):List[Int]=if(n<=9)List(n)else
if(l<2)List(-1)else
if(n%l==0)l::p(n/l,l)else
p(n,l-1)

```

Test & Invocation:

```
scala> val big=9*9*9*8*8*8*7*7*7*5*3
big: Int = 1920360960

scala> p(big)
res1: List[Int] = List(9, 9, 9, 8, 8, 8, 7, 7, 7, 5, 3)

```

Response time: immediately, \< 1s on 2Ghz CPU.
> 2 votes

# Answer
# Jelly, 18 13 10 bytes

```
×⁵RDP$€io-

```

Try it online!

**13-byte solution:**

```
×⁵RDP$€iµ’¹¬?

```

Try it online!

Explanation with input `N`:

```
×³R              create a range from 1 to N * 100 (replace ³ with ⁵ for a faster execution time)
   DP$           define a function ($) to get the product of the digits of a number,
      €          apply that function to each element in the list,
       iµ        get the index of the input N in the list (or 0 if it's not there), and yeild it as the input to the next link,
         ’¹¬?    conditional: if the answer is 0, then subtract one to make it -1, otherwise, yeild the answer

```

**18-byte solution:**

```
D×/
×⁵RÇ€i
Ç⁾-1¹¬?

```

Try it online!

```
D×/        product of digits function, takes input M
D          split M into digits,
 ×/        reduce by multiplication (return product of digits)

×⁵RÇ€i     range / index function
×⁵R        make a range from 1 to N*10,
   Ç€      run the above function on each of the range elements,
     i     get the index of N in the result, or 0 if it's not there

Ç⁾-1¹¬?    main function:
Ç    ¬?    run the line above and check if the answer is null (0)
 ⁾-1       if it is, return "-1",
    ¹      otherwise, return the answer (identity function).

```

The last link is only to replace 0 (Jelly's default falsey value, as all lists are one-indexed) with -1. If you consider 0 an OK falsey value, the program is **8 bytes**.
> 2 votes

# Answer
## Ruby (100)

```
n=gets.to_i;(d=1..9).map{|l|[*d].repeated_combination(l){|a|a.reduce(:*)==n&&(puts a*'';exit)}};p -1

```
> 1 votes

# Answer
# Python 2, 89 bytes

```
f=lambda n,a=0,u=1,i=9:n<2and(a or 1)or-(i<2)or n%i<1and f(n/i,a+i*u,u*10)or f(n,a,u,i-1)

```

Try it online!

Just because there's no Python answer yet. It's really painful to lack implicit type conversion between string and int.
> 0 votes

---
Tags: code-golf, math
---


# Question
Title: Detect Rectangular Text with Rectangular Code
Given a string of printable ASCII text (including newlines and spaces) that contains at least one character that is neither a newline nor a space, output a truthy value if the string is rectangular, and a falsey value otherwise. **Additionally, the source code for your solution must be rectangular**.

A string is rectangular if it meets all of the following conditions:

1. The first line and the last line contain no spaces.
2. The first and last character of each line is not a space.
3. All lines have the same number of characters.

For example, the following text is rectangular:

```
abcd
e fg
hijk

```

This text, however, is not rectangular (requirement #3):

```
1234
567
8900

```

## Test Cases

Truthy:

```
sdghajksfg

```

```
asdf
jkl;

```

```
qwerty
u i op
zxcvbn

```

```
1234
5  6
7890

```

```
abcd
e fg
hijk

```

Falsey:

```
a b c

```

```
123
456
7 9

```

```
12
345

```

```
qwerty
 uiop
zxcvnm

```

```
1234
567
8900

```

---

This is , so the shortest solution in bytes wins.

# Answer
# C (gcc), ~~127~~ ~~125~~ ~~124~~ 118 bytes

* Saved two bytes by golfing `r*=!e&(!t|t==c);` to `r>>=e||t&&t-c;`. *(This golf was the inspiration for my recent C tips answer Inverse flag update.)*
* Saved a byte by golfing `*(_-2)` to `_[~1]`.
* Saved six bytes by golfing `*_++-10||(...)` to `*_++<11?...:0` and utilizing the placeholder zero `...:0` (which is not used constructively) to golf the `c++` increment. Those golfs allowed some further loop reshuffling.
* When one can use multiple falsey values, 114 bytes could be possible.

```
r,e,c,t;_(char*_){for(r=1,t=c=0;*_;*_++<11?r*=(t||(t=c,!e))&*_>32&_[~1]>32&t==c,c=e=0:c++)*_-32||(e=1);r>>=e||t&&t-c;}

```

Try it online!

*Source layout achieving a taller rectangle.*

# Explanation

*The following explains the 124 bytes long version.*

```
r,e,c,t;_(char*_){     // `r` is the boolean result flag, `e` a boolean flag if the current line contains
                       //  a space, `t` the first line's width, `c` the current line's current width
 for(r=1,t=c=0;*_;c++) // initialize, loop through entire string
  *_-32||              // if the current char is a space,
   (e=1),              //  the current line contains a space
  *_++-10||            // if the current char is a newline (char pointer `_` now incremented)
   (r*=(t||(t=c,!e))   // if t is not yet set, the current line is the first line; set it
                       //  to this line's length, check that no spaces where found
    &*_>32             // the next line's first char should not be a space
    &_[~1]>32          // this line's last char should not have been a space
    &t==c,c=~0,e=0);   // the line lengths should match, reset `c` and `e` to zero
                       //  (`~0 == -1`, countering the loop's increment of `c`)
 r>>=e||t&&t-c;}       // return boolean flag, check that the last line does not contain spaces,
                       //  there was either no newline or line lengths match
                       //  (here) equivalent to `r*=!e&(!t|t==c)`

```

Try it online!
> 11 votes

# Answer
# Java 10, ~~214~~ ~~176~~ ~~169~~ ~~152~~ ~~144~~ 139 bytes

```
s->{String[]a=s.split("\n")
;int r=1,i=0,R=a.length;for
(;i<R;i++)if(i<1|i>R-2?a[i]
.contains(" "):a[i].trim( )
!=a[i])r=0;return-r<0;}////

```

-5 bytes thanks to *@Neil*.

Uses `String[]a` instead of `var a`; `return-r<0;` instead of `return r>0;`; and added a comment `//` at the very end, so there aren't spaces on the first and last rows.

Note that this rectangle is shorter than a single-line input, because `int r=1,...;` should be replaced with `int[]v{1,...};`, and all uses of the integers would then becomes `v[n]` (where *n* is the index of the variable in the array `v`).

Try it online.

**Explanation:**

```
s->{                        // Method with String parameter and boolean return-type
  String[]a=s.split("\n");  //  Input split by new-lines
  int r=1,                  //  Result-integer, starting at 1
      i=0,                  //  Index `i`, starting at 0
      R=a.length;           //  Amount of rows `R`
  for(;i<R;i++)             //  Loop `i` over the rows
    if(i<1                  //   If it's the first row,
       |i>R-2?              //   or the last row:
        a[i].contains(" ")  //   And the current row contains a space
       :a[i].trim()!=a[i])  //   Or either column of the current row contains a space
      r=0;                  //    Set the result `r` to 0
   return-r<0;}             //  Return whether `r` is still 1
////                        // Comment to comply to the rules of the challenge

```

Here is the same base program with spaces (**~~128~~ 126 bytes**):

```
s->{var a=s.split("\n");int r=1,i=0,R=a.length;for(;i<R;i++)if(i<1|i>R-2?a[i].contains(" "):a[i].trim()!=a[i])r=0;return r>0;}

```

-2 bytes thanks to *@Neil*.

Try it online.
> 4 votes

# Answer
# C++, ~~199~~ ~~183~~ ~~181~~ 175 bytes

This template function accepts lines as a collection of strings (which may be wide strings), passed as a pair of iterators.

```
#include<algorithm>//
template<class I>bool
f(I a,I b){return!~+(
*a+b[-1]).find(' ')&&
std::all_of(a,b,[&a](
auto&s){return' '+-s.
back()&&s[0]-' '&&a->
size()==s.size();});}

```

Thanks are due to user Erroneous for reminding me of the `back()` member of `std::string` and for pointing out that `npos+1` is zero.

## Ungolfed equivalent

The only real golfing is to concatenate the first and last lines so we can perform a single `find` for spaces in those.

```
#include <algorithm>
template<class It>
bool f(It a, It b)
{
    return (*a+b[-1]).find(' ') == a->npos
        && std::all_of(a, b,
                       [=](auto s) {
                           return s.back() != ' '
                               && s.front() != ' '
                               && s.size() == a->size(); });
}

```

# Test program

```
#include <iostream>
#include <string>
#include <vector>
int expect(const std::vector<std::string>& v, bool expected)
{
    bool actual = f(v.begin(), v.end());
    if (actual == expected) return 0;
    std::cerr << "FAILED " << (expected ? "truthy" : "falsey") << " test\n";
    for (auto const& e: v)
        std::cerr << "  |" << e << "|\n";
    return 1;
}
int expect_true(const std::vector<std::string>& v) { return expect(v, true); }
int expect_false(const std::vector<std::string>& v) { return expect(v, false); }

```

```
int main()
{
    return
        // tests from the question
        + expect_true({"sdghajksfg"})
        + expect_true({"asdf", "jkl;",})
        + expect_true({"qwerty", "u i op", "zxcvbn",})
        + expect_true({"1234", "5  6", "7890",})
        + expect_true({"abcd", "e fg", "hijk",})
        + expect_false({"a b c",})
        + expect_false({"123", "456", "7 9",})
        + expect_false({"12", "345",})
        + expect_false({"qwerty", " uiop", "zxcvnm",})
        + expect_false({"1234", "567", "8900",})
        // extra tests for leading and trailing space
        + expect_false({"123", " 56", "789"})
        + expect_false({"123", "45 ", "789"})
        // the function source
        + expect_true({"#include<algorithm>//",
                       "template<class I>bool",
                       "f(I a,I b){return!~+(",
                       "*a+b[-1]).find(' ')&&",
                       "std::all_of(a,b,[&a](",
                       "auto&s){return' '+-s.",
                       "back()&&s[0]-' '&&a->",
                       "size()==s.size();});}",})
        ;
}

```
> 3 votes

# Answer
# T-SQL, ~~237~~ 207 bytes

```
SELECT(SELECT(IIF(max(len(v))=min(len(v)),1,0)*IIF(SUM(len(v+'x')-len
(trim(v))-1)=0,1,0))FROM t)*(SELECT(IIF(SUM(charindex(' ',v))=0,1,0))
FROM[t]WHERE[i]IN(SELECT(min(i))FROM[t]UNION(SELECT(max(i))FROM[t])))

```

Outputs 1 for rectangular, 0 otherwise. I had to use tons of extra parens and brackets to eliminate spaces, I'm sure there is vast room for improvement.

**Explanation**:

Per our allowed I/O options and clarification in the question comments, input is taken as separate rows in a pre-existing table **t**. Because data in SQL is inherently unordered, that table includes a "row number" identity field **i**:

```
CREATE TABLE t (i INT IDENTITY(1,1), v VARCHAR(999))

```

Basically my SQL performs 3 subqueries, each of which returns `0` or `1` based on the 3 criteria of "rectangular" code. Those 3 values are multiplied together, only returning `1` for code that satisfies all 3.

**EDIT**: Combined criteria 2 and 3 into the same SELECT to save space

```
SELECT(
SELECT(IIF(max(len(v))=min(len(v)),1,0)                  --All rows same length
      *IIF(SUM(len(v+'x')-len(trim(v))-1)=0,1,0))FROM t) --no leading or trailing spaces
*(SELECT(IIF(SUM(charindex(' ',v))=0,1,0))               --No spaces at all in
FROM[t]WHERE[i]IN(SELECT(min(i))FROM[t]                  --   first row or
            UNION(SELECT(max(i))FROM[t])))               --   last row

```

The `TRIM(v)` function is only supported by SQL 2017 and above. Earlier versions would need `LTRIM(RTRIM(v))`, which would require rebalancing the rows.

One random note: the `LEN()` function in SQL ignores trailing spaces, so `LEN('foo ') = 3`. To get a "true" length you have to tack a character on to the end then subtract one :P
> 3 votes

# Answer
# Haskell, ~~106~~ ~~102~~ ~~98~~ ~~110~~ ~~109~~ 102 bytes

```
(\a->all(==[])a||and(e((1<$)<$>a):map(all(>='!').($a))[head,last,map$last,map$head]));e(a:s)=all(==a)s

```

Thanks to @nimi and @Laikoni for a byte each!

Try it online!
> 2 votes

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

```
x=>(x=x.split`\n`).some(s=>s.length-x[0].length|s.trim()!=s)<!/\s/.test(x[0]+x.pop())

```

Try it online!
> 2 votes

# Answer
# Haskell, 79 bytes

```
g(x:r)=all((==(0<$x)).(0<$))r&&all(>='!')(x++last(x:r)++(head<$>r)++(last<$>r))

```

Try it online! Takes input as a list of lines.

The pattern `g(x:r)= ...` binds the first line to `x` and the (possibly empty) list of remaining lines to `r`. Then `all((==(0<$x)).(0<$))r` checks if all lines in `r` have the same length as `x` (Using this tip).

If not, then the conjunction `&&` short-circuits and returns `False`, otherwise the right hand side is evaluated. There a string is build which consists of `x` for the first line, `last(x:r)` for the last line of `r` (or the first line again in case `r` is empty) and `(head<$>r)` for the first and `(last<$>r)` for the last character of each line. For this string, `all(>='!')` checks that it does not contain any spaces (we can't use `(>' ')` because of the source code restriction).
> 2 votes

# Answer
# Python 2, 82 bytes

```
lambda*s:len(set(map(len,s)))<2<'!'<=min(tuple(s[0]+s[-1])+zip(*s)[0]+zip(*s)[-1])

```

Try it online!

Invoke as `f("abcd", "e fg", "hijk")`.
> 2 votes

# Answer
# MATL, 13 bytes

```
ctgF6Lt&()32>

```

Input is an array of strings, in the format `{'abc' 'de'}`.

Output is an array containing only ones, which is truthy, or an array containing at least a zero, which is falsey.

Try it online! Or verify all test cases, including truthiness/falsihood test.

### Explanation

```
c       % Implicit input. Convert to char. This concatenates the
        % strings of the input cell array as rows of a rectangular
        % char array, right-padding with spaces as needed
tg      % Duplicate, convert to logical. Gives a logical array with
        % the same size containing true in all its entries
F       % Push false
6L      % Push the array [2, j-1], where j is the imaginary unit.
        % When used as an index, this is interpreted as 2:end-1
t       % Duplicate
&(      % Assignment indexing with 4 inputs: original array, new
        % value, two indexing arrays. This writes false at the inner
        % rectangle (2:end-1)×(2:end-1) of the logical array that
        % initially only contained true. This will be used as a
        % logical index (mask) into the rectangular char array
)       % Reference indexing. This selects the border of the char
        % array. The result is a column vector of chars
32>     % Is each entry greater than 32? (ASCII code for space)
        % Implicit display

```
> 2 votes

# Answer
# Canvas, ~~17~~ 15 bytes

```
４［↷Ｋ；｝┐）｛ＳＬ］∑４≡

```

Try it here!

Explanation (ASCII-fied for monospace):

```
4[↷K;}┐){SL]∑4=  full program; pushes the input to the stack.
4[   }           repeat 4 times
  ↷                rotate ToS clockwise. This also pads the input with spaces
   K;              take off the last line and put it below the item
      ┐          pop the remaining of the input (the center)
       )         and wrap the rest (the sides) in an array
        {  ]     map over those
         S         split on spaces - should result to one item in the array
          L        and get the length
            ∑    sum those lengths together
             4=  check if equal 4

```
> 1 votes

# Answer
# JavaScript (ES6), 88 bytes

```
s=>!s.split`\n`.some((s,i,a)=>s[L='length']-a[0][L]|(++i%a[L]>1?/^\s|\s$/:/\s/).test(s))

```

Try it online!
> 1 votes

# Answer
# Perl 5, 70 bytes

```
$f||=$_;$l||=y///c;$,||=/^\s|\s$/||$l-y///c;$e=$_}{$\="$f$e"=~/\s/||$,

```

Try it online!

Outputs `0` for truthy, any other number for falsey.
> 1 votes

# Answer
# Red, 216 191 bytes

```
func[s][d:(length?(first(s:(split(s)"^/"))))sp:
func[a][none = find a" "]b: on foreach c s[b: b
and(d = length? c )and(c/1 <>" ")and(" "<> last
c)]res:(sp(first(s)))and(sp(last(s)))and(b)res]

```

Try it online!

I put a lot of otherwise not necessary parentheses in the first and last rows.
> 1 votes

# Answer
# Jelly, 17 bytes

```
Ỵµ.ịÐ€;ịɗẎ⁶e<L€E$

```

Try it online!
> 0 votes

# Answer
# Jelly, 15 bytes

Uses a method developed by Mnemonic in a (currently - due to an edge-case failure) deleted Pyth submission. (if it is now fixed up, go give some credit!)

```
ỴµL€Eȧt€⁶ZUƊ4¡⁼

```

A monadic link accepting a list of characters which returns 1 or 0.

**Try it online!**

### How?

```
ỴµL€Eȧt€⁶ZUƊ4¡⁼ - Link: list of characters
Ỵ               - split at newlines (making a list of lists - the rows)
 µ              - start a new monadic chain, call that ROWS
  L€            - length of €ach row in ROWS
    E           - all equal? (an integer: 1 if so, otherwise 0)
            4¡  - repeat four times:
           Ɗ    -   last three links as a monad:
      t€⁶       -     trim spaces (⁶) from €ach row in current ROWS
         Z      -     transpose that result
          U     -     upend (reverse each new row)
     ȧ          - logical AND (0 if L€E was 0 else the result of the repeated transform)
              ⁼ - equal to X? (the integer 0 is not equal to any listy of characters)

```
> 0 votes

# Answer
# Japt, 22 bytes

Noncompeting answer: there's a known bug in Japt, where two-dimensional array rotations truncate the results. Due to that bug the code below only works on inputs that are square. If the bug wasn't present, though, the code below should work completely correctly.

```
e_Ê¶UÌÊÃ©Ueº4o)r_z)mx}U
e_                      // Check if every line in the input array
  Ê¶UÌÊ                 // has the same length as the last item.
       Ã©               // Also,
               r_z)mx}U // check if rotating and trimming the input array
           º4o)         // four times
         Ue             // is equal to the input array.

```

Takes input as an array of strings. Using parentheses instead of spaces makes the rectangular code requirement quite easy.
Try it here.
> 0 votes

# Answer
# C# (.NET Core), ~~145~~ 167 bytes

```
S[0].Length>1&&S[0].IndexOf
(" ") + S[ S.Count() - 1 ].
IndexOf(" ")<-1&Array.Find(
S,x=>x[0]==' '| x [x.Length
-1]  ==  ' '  | S[0].Length
!=x.Length)==null?11>0:0>1;

```

Try it online!

```
S[0].Length>1&                                    // And if the lenght of the first argument is more than 1 char
Array.Find(                                       // Find a string in an array
    S,                                            // The array which will be searched in
    x=>                                           // For x as the current string from the array
    x.Length!=S[0].Length|                        // If the string lenght match not the first argument lenght
    x[0]==' '|                                    // Or if the string begins with a spacer
    x[x.Length-1]==' '                            // Or if the string ends with a spacer
)==null&                                          // And if there was no string found which matched the conditions
S[0].IndexOf(" ")+S[S.Count()-1].IndexOf(" ")<-1  // And if the first and last string doesn't have a spacer
?                                                 // If all above is true do
1>0                                               // Return True
:                                                 // Else
0>1                                               // Return False

```
> 0 votes

# Answer
# Ruby 2.5+, 63 bytes

```
->a{!a.uniq(&:size)[1]&&a.none?(/^\s|\s$/)&&!(a[0]+a[-1])[?\s]}

```

Takes input as an array of strings. No test link, since the version on TIO (2.4) is too old for this one. Instead, here is a slightly longer (69 bytes) version for testing:

```
->a{!a.uniq(&:size)[1]&&a.none?{|l|l=~/^\s|\s$/}&&!(a[0]+a[-1])[?\s]}

```

Try it online!

The difference is that since 2.5 Ruby supports directly passing a Regex pattern to `all?, any?, none?` methods, which saves us a few bytes. The method itself is quite self-explanatory - we test:

1. If there is only 1 unique line size
2. If there are any spaces on line boundaries
3. If there are spaces on the first and last lines.
> 0 votes

# Answer
# C (gcc), 119 bytes

Takes input as a list (s) of n strings.

```
f(s,n,m,r,p)char**s,*p;{for(r=m=n;m--;r*=strlen(*s)==strlen(s[m])&(!p||m&&m^n-1&&p!=s[m]&&p[1]))p=strchr(s[m],32);n=r;}

```

Try it online!
> 0 votes

---
Tags: code-golf, decision-problem, restricted-source
---


title: Tips for golfing in The Powder Toy

text:
# Question
Title: Tips for golfing in The Powder Toy
Have fun with this one, The Powder Toy is a interesting challenge for golf, especially with filt logic.

The thing that makes TPT a challenge is the many many many many ways to approach a problem: `Should I use Cellular Automaton rules, SWCH logic, Filt logic, subframe filt logic, and/or wall logic?`

As such, a location for tips for TPT golfing would be quite helpful, so I made this question thread.

This thread will likely use a lot of abbreviations. A lot of them will be in-game elements, so searching them up on the Wiki will bring you a lot of information about them, like what they are.

Here are the most common ones you'll likely see in this thread, with their ingame description attached (and their full name), for people who don't want to go searching:

* SPRK: Electricity. The basis of all electronics in TPT, travels along wires and other conductive elements.
* FILT: Filter. Filter for photons, changes the color.
* ARAY: Ray Emitter. Rays create points when they collide.
* BTRY: Battery. Generates infinite electricity.
* DRAY: Duplicator ray. Replicates a line of particles in front of it.
* CRAY: Particle Ray Emitter. Creates a beam of particles set by its ctype, with a range set by tmp.
* SWCH: Switch. Only conducts when switched on. (PSCN switches on, NSCN switches off)

List of all elements

# Answer
> 3 votes
# Only use subframe logic when it's smaller

And, for more complex machines, it's often much smaller.

Subframe generally imposes the overhead of creating solid SPRK (about 3 pixels for most directions, an extra pixel compared to just a BTRY), FILT 'channels' (for fast BRAY transfer), and minimizing the amount of nonsubframe logic, even if it's smaller, due to it being many times (4x to 20x-30x slower!) slower.

Subframe logic is often good for complex operations (which is most of the challenges here), but for simpler ones, subframe logic is probably not optimal.

# Answer
> 2 votes
# Know your FILT modes

FILT is, at least for FILT and subframe logic, the cornerstone of computing in TPT. And as such, it has a bunch of tricks to make your life easier, in the form of it's various modes. You set a FILT mode using `tmp`, but a comprehensive list that describes the intricacies of these modes isn't really a thing right now. FILT takes two inputs: it's own color (CTYPE) and the color of what it's interacting with, either BRAY or CRAY. I'll label these FILTC and INTRC, respectively, for this list.

* Mode 0:

The simplest mode, it sets INTRC to the value of FILTC, nothing more.

```
INTRC = FILTC

```
* Mode 1:

This is a binary AND, it ands together INTRC and FILTC, setting INTRC to the result.

```
INTRC = INTRC & FILTC

```
* Mode 2:

This is a binary OR, it ors together INTRC and FILTC, setting INTRC to the result.

```
INTRC = INTRC & FILTC

```
* Mode 3:

This mode is slightly more complicated, it ands together the inverse of FILTC and INTRC, setting INTRC to the result.

```
INTRC = INTRC & (~FILTC)

```
* Mode 4:

This mode is a bit harder to describe. It's a red shift (binary left shift),

The catch here is that the amount it shifts by is controlled by it's temperature, with the equation (Temperature-273.0)\*0.025, defaulting to a shift by 1 if the value is less than 1. You can acheive a shift of any required amount by multiplying the number of bits you need by 40, and adding 273.0. I'll call the amount shifted X.

As such, INTRC is shifted left by X, setting INTRC to the result.

```
X = (temperature-273.0)*0.025
INTRC = INTRC << X

```
* Mode 5:

This is essentially mode 4, but with a right shift instead. See the information on mode 4 for how to use it.

```
X = (temperature-273.0)*0.025
INTRC = INTRC >> X

```
* Mode 6:

Does nothing.

```
INTRC = INTRC

```
* Mode 7:

Performs a binary XOR on INTRC and FILTC, setting INTRC to the result.

```
INTRC = INTRC ^ FILTC

```
* Mode 8:

Performs a binary NOT on INTRC, setting INTRC to the result.

```
INTRC = ~INTRC

```
* Mode 9:

Sets INTRC to a random color.

```
INTRC = rand()

```
* Mode 10:

Performs a different version of a red shift.

\[TODO: figure out how to describe\]

```
LSB = FILTC & (-FILTC)
INTRC = INTRC * LSB

```
* Mode 11:

Performs a different version of a blue shift.

\[TODO: figure out how to describe\]

```
LSB = FILTC & (-FILTC)
INTRC = INTRC / LSB

```

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


title: Range of numbers

text:
# Question
Title: Range of numbers
Came over a similar problem in a project I'm working on and found it quite hard to solve it without excesive use of `if`. I'm eager to see if anyone can come up with more elegant solutions to this, with the aribitary numbers I have given to the line segments.

### The problem

You are given two integers that act like the end points of a line segment. Determine what existing line segments this line will overlap with.

### Intervals / line segments

The other lines, named Q, W, E, R and T, are as following:

```
Q:   0 -   7
W:   8 -  18
E:  19 -  32
R:  33 - 135
T: 136 -

```

The last one, T, starts at 136 and has no end point.

### Example

Given the numbers `5` and `27`, the line will overlapp with `Q`, `W` and `E`. This can be roughly illustrated like this:

```
    Q  W   E       R           T
---+--+---+-------+-----------+-----
   0  7   18      32         135

     +---------+
     5         27

  (somewhat arbitrary scale)

```

### Input

Two integers from stdin.

### Output

A String containing the names of the lines that our new line overlap with, for instance in the example above `QWE`.

### Rules

Shortest code.

# Answer
## GolfScript (43 32 30 chars)

Contains escape characters. As a hex dump:

```
00000000  7e 29 27 51 08 57 0b 45  0e 52 67 27 32 2f 7b 29  |~)'Q.W.E.Rg'2/{)|
00000010  2a 7d 25 27 54 27 32 24  2a 2b 3c 3e 2e 26        |*}%'T'2$*+<>.&|

```

Base-64 encoded:

```
fiknUQhXC0UOUmcnMi97KSp9JSdUJzIkKis8Pi4m

```

Using bold to indicate escape characters:

```
~)'Q**^H**W**^K**E**^N**Rg'2/{)*}%'T'2$*+<>.&
```

Thanks to Howard for the suggestion to use escape characters.
> 6 votes

# Answer
## APL (39)

```
'QWERT'/⍨1↓⊃≠/1 0⌽¨0,¨0 7 18 32 135∘<¨⎕

```

Takes input as two whitespace-separated numbers.

Explanation:

* `0 7 18 32 135∘<¨⎕`: For each number in the input, see if 0, 7, 18, 32, and/or 135 is smaller than the number. If the input was `5 27` we now have `(1 0 0 0 0) (1 1 1 0 0)`. (The first one is taken to be the start of the line and the second one the end).
* `1 0⌽¨0,¨`: Prefix a zero to each of those lists and rotate the first one left by 1. (We now have `(1 0 0 0 0 0) (0 1 1 1 0 0)`).
* `≠/`: Gives a list where the individual items of the two input lists were not equal. (We now have `1 1 1 1 0 0`).
* `1↓⊃`: Remove the first item from this list. The other five stand for whether or not to display a Q, W, E, R or T.
* `'QWERT'/⍨`: For each letter, output N of those letters, where N is the corresponding value in the list on the right. Since the list was `1 1 1 0 0` the answer is `QWE`.
> 9 votes

# Answer
## Python ~~82~~ 84

There you are. Edit: Fixed for inputs like `-1 10` and `-10 -1` for 2 chars

```
z=lambda a:(a>7)+(a>18)+(a>32)+(a>135)+1
a,b=input()
print"QWERT"[z(a)-1:z(b)*(b>0)]

```
> 6 votes

# Answer
## J, 58 54 characters

```
'QWERT '#~0 8 19 33 136 _(([<1{])*(1|.[>:0{]))".1!:1[1

```

Reads one line of input from the keyboard.
> 5 votes

# Answer
## Python, 79

```
x,y=input()
print"".join(set(("Q"*8+"W"*11+"E"*14+"R"*103)[x:y+1]))+"T"*(y>135)

```

It could be a lot shorter if it's allowed to leave duplicates in the output, but I figured that would be bending the rules a bit.
> 3 votes

# Answer
# K, 68 58

`{$[y>135;`T,;]`Q`W`E`R@&max'(x+!1+y-x)in/:(!8;8+!11;19+!15;33+!104)}`

```
{$[y>135;"T",;]"QWER"@&(=).'(y>'0,-1_a),'x<'a:8 19 33 136}

```

.

```
k){$[y>135;"T",;]"QWER"@&(=).'(y>'0,-1_a),'x<'a:8 19 33 136}[5;27]
"QWE"
k){$[y>135;"T",;]"QWER"@&(=).'(y>'0,-1_a),'x<'a:8 19 33 136}[0;139]
"TQWER"
k){$[y>135;"T",;]"QWER"@&(=).'(y>'0,-1_a),'x<'a:8 19 33 136}[20;135]
"ER"
k){$[y>135;"T",;]"QWER"@&(=).'(y>'0,-1_a),'x<'a:8 19 33 136}[32;135]
"ER"

```
> 2 votes

# Answer
## PHP, 159 characters

```
<?$b=array(0=>"Q",8=>"W",19=>"E",33=>"R",136=>"T",1e9=>"");$a=split(" ",fgets(STDIN));foreach($b as $k=>$v){if($a[0]<$k&&$a[1]>=$j)$o.=$p;$p=$v;$j=$k;}echo $o;

```

With line breaks:

```
<?
$b=array(0=>"Q",8=>"W",19=>"E",33=>"R",136=>"T",1e9=>"");
$a=split(" ",fgets(STDIN));
foreach($b as $k=>$v)
{
    if($a[0]<$k&&$a[1]>=$j)
        $o.=$p;
    $p=$v;
    $j=$k;
}
echo $o;

```

Assumes that the line segments are contiguous and non-overlapping as in the given example.

Working version at ideone.com.
> 2 votes

# Answer
### Scala 113

```
val i=Seq(0,8,19,33,136,(1<<31)-1)
i.zip(i.tail)zip("qwert")filter(x=>x._1._2>readInt&&x._1._1<=readInt)map(_._2)

```

Handles test cases 5-27(QWE), 400-500(T), 40-40(R), 33-33(R).
> 2 votes

# Answer
### M (Micronetics System MUMPS 4.4) - *82 Chars*

```
f i=1:1:2 r a s x=(a>0)+(a>7)+(a>18)+(a>32)+(a>135) w:$d(y) $e("QWERT",y,x) s y=x

```

5-27(QWE), 400-500(T), 40-40(R), 33-33(R).
> 1 votes

# Answer
## PHP 119

```
<?fscanf(STDIN,'%d%d',$a,$b);foreach(array('Q'=>7,'W'=>18,'E'=>32,'R'=>135,'T'=>136)as$x=>$y)echo$y>=$a&&$y<=$b?$x:'';

```

Getting Input from command-line reduces the size, but, I don't think it is applicable here, but still:

## PHP 111

```
<?list(,$a,$b)=$argv;foreach(array('Q'=>7,'W'=>18,'E'=>32,'R'=>135,'T'=>136)as$x=>$y)echo$y>=$a&&$y<=$b?$x:'';

```
> 1 votes

# Answer
## Mathematica

```
Cases[{{q, 0, 7}, {w, 8, 18}, {e, 19, 32}, {r, 33, 135}, {t, 136, \[Infinity]}},
  {a_, b_, c_} /; Length@IntervalIntersection[Interval[{b, c}], Interval[{5, 27}]] !=0
   :> a]

```
> 1 votes

# Answer
# Jelly, 27 bytes (improvements wanted!)

```
®Ṁṭ“®¿Çg‘
ØQFḣ5ż¢Œṙ
Ɠ©r/ị¢Q

```

Try it online!

```
®Ṁṭ“®¿Çg‘    actual runlengths here
®Ṁ           recall the input numbers, and get the maximum of them
  ṭ          append that max (to be used as runlength for 'T') to...
   “®¿Çg‘    [ 8, 11, 14, 103 ] (listed as base-250 numbers on jelly's codepage)

ØQFḣ5ż¢Œṙ    run-length encoding function:
ØQF          get "QWERTYUIOPASDF..."
   ḣ5        get the first 5 characters of that to yield "QWERT"
     ż¢      zip it with the above link (RLE values)...
       Œṙ    and then apply RLE decode to produce the uncompressed string

Ɠ©r/ị¢Q      main function:
Ɠ©           take two integers from stdin, evaluate them and save them to a register
  r/         take the range between them (technically a fold)
    ị¢       for each element in the range, get the value at its index in the link above...
      Q      and return all the unique values (remove duplicates).

```

I think that I'm doing something wrong / non-optimally with the register save / recall to get the max value. If I just make that value 250, the program goes down to just **22 bytes**:

```
ØQFḣ5ż“®¿Çgż‘Œṙ
Ɠr/ị¢Q

```

Try it online!
> 1 votes

---
Tags: code-golf, number
---