# Question
Title: Create an object whose state changes on assignment
I find it deeply weird that this is possible in Ruby (I won't immediately say how):

```
obj = #code redacted

print obj.state # Some value.

LValue = obj

print obj.state # Different value!

```

Your challenge is to create code roughly of this form. Create an object and assign it to a variable. It should have some defined attribute (or deterministic, idempotent method) like `state` above, that changes after the object is assigned to a new identifier (`LValue` above), *even if* you still use the old identifier (`obj` above) to refer to it.

**Edit for emphasis**: `state` or the equivalent must be idempotent, so creating an accessor that modifies the value, or for any other reason returns different results when called several times in a row, isn't a valid solution. Or, more simply, it has to be the assignment that changes the state.

Any language with assignment is eligible, although there are probably some where there's no fully legitimate solution. I'll post my Ruby answer if nobody else gets it after a few days, and accept highest-voted answers on a rolling basis.

# Answer
## C++

This is trivial using the right tools.

```
#include <iostream>

using namespace std;

class Obj {
public:
   int state;

   Obj& operator= (Obj& foo) {
      foo.state++;
      this->state = foo.state - 2;
      return *this;
   }
};

int main() {
   Obj a, b, c, d;
   a.state = 3;
   b.state = 4;

   cout << a.state << " " << b.state << "\n";

   c = a;
   d = b;

   cout << a.state << " " << b.state << " " << c.state << " " << d.state << "\n";

   return 0;
}

```

Output:

```
3 4
4 5 2 3

```
> 29 votes

# Answer
# PHP (debug build, \>= 5.4)

We use refcount of the object in a getter. (So, by the assignment, refcount increases and value changes)

```
class State {
    public function __get($arg) {
        ob_start();
        debug_zval_dump($this); // e.g. "object(State)#1 (0) refcount(6)"
        return ob_get_clean()[29];
    }
}

$obj = new State;
var_dump($obj->state);
$a = $obj;
var_dump($obj->state);

```
> 17 votes

# Answer
# C#

Two simple options:

```
class Obj
{
    public int state;
    public static implicit operator int(Obj o)
    {
        return o.state++;
    }
}

static int LValueI;
static Obj LValueM { set { value.state++; } }
static void Main()
{
    var obj = new Obj { state = 1 };
    LValueI = obj;
    Console.WriteLine(obj.state); //2, caused by the implicit cast.

    LValueM = obj;
    Console.WriteLine(obj.state); //3, caused by the property setter.
    Console.ReadLine();
}

```

Or we could simply write to the same memory:

```
[StructLayoutAttribute(LayoutKind.Explicit)]
class Program
{
    [FieldOffset(0)]
    int state = 1;
    [FieldOffset(1)]
    int LValue;

    void Test()
    {
        var obj = this;

        Console.WriteLine(state);  //1
        LValue = state;
        Console.WriteLine(state);  //257
        Console.ReadLine();
    }
    static void Main() { new Program().Test(); }
}

```
> 14 votes

# Answer
# TeX, much shorter than other answers here

```
\setbox0=\hbox{Hello world!} % Put stuff in the box 0.
\message{\the\wd0}           % Print the width of the box => non-zero
\setbox2=\box0               % Put the box instead in box 2.
\message{\the\wd0}           % Now box 0 is void, hence has zero width.

```

As a typesetting system, TeX has a "box" type, which contains typeset material. Since the most common use case is to move this material around, split it, etc, rather than making copies of it, boxes are normally deleted when used (or rather, "box" variables are pointers and only one pointer at a time can point to an actual box in memory). No need for any magic.
> 12 votes

# Answer
## C++11 (So you guys have forgotten about unique\_ptr/shared\_ptr :-) )

```
#include <iostream>
#include <memory>
using namespace std;
int main() {
    std::unique_ptr<int> u1(new int(0)), u2;
    std::shared_ptr<int> s1 = std::make_shared<int>(0), s2;
    std::cout<<u1.get()<<" "<<u2.get()<<" "<<std::endl;
    std::cout<<s1.use_count()<<" "<<s2.use_count()<<" "<<std::endl;
    u2 = std::move(u1);
    s2 = s1;
    std::cout<<u1.get()<<" "<<u2.get()<<" "<<std::endl;
    std::cout<<s1.use_count()<<" "<<s2.use_count()<<" "<<std::endl;
   return 0;
}

```
> 8 votes

# Answer
# Fortran 03

This is somewhat similar to Hugo's D answer, but is a little more hidden (partly because who the #$%^ knows Object Oriented Fortran)?

```
module objects
   implicit none

   type ObjDef
      integer :: state
    contains
      procedure :: initObject
      procedure :: printObject
      procedure :: setNew
   end type
 contains
   subroutine initObject(this)
     class(ObjDef) :: this
     this%state = this%state + 1
   end subroutine initObject

   subroutine printObject(this)
     class(ObjDef) :: this
     print '(a,i0)',"this%state = ",this%state
   end subroutine printObject

   subroutine setNew(this,that)
     class(ObjDef) :: this,that
     that%state = this%state
   end subroutine setNew

end module objects

program objectChange
   use objects
   type(ObjDef) :: a,b

   call initObject(a)
   call printObject(a)
   call b%setNew(a)
   call printObject(a)
end program objectChange

```

The output is

```
this%state = 1
this%state = 0

```

If you can figure out what happened, bonus points to you! If not:

> When calling the procedure `setNew` in the form `call b%setNew(a)`, `b` is implicitly the first argument, not the second.
> 7 votes

# Answer
## PowerShell

This creates an object whose `state` property is the names of the variables that point to the object.

```
$a = @{}| Add-Member -MemberType:16 -PassThru state -Value {
        (gv|?{$this -eq $_.Value}|%{$_.Name}) -join ','}

'Before: ' + $a.state
$b = $a
'After: ' + $a.state

```

Output

```
Before: a,this
After: a,b,this

```

*Note:* This doesn't work if the assignment happens in a child scope.

```
'Before: ' + $a.state
&{$b = $a}
'After: ' + $a.state

```

Outputs

```
Before: a,this
After: a,this

```
> 7 votes

# Answer
# Perl 5

Here's one way to do it in Perl:

```
package Magic {
    sub new { bless {state => 1} }
    use overload '""' => sub { $_[0]{state}++ };
}
use feature 'say';

my $obj = new Magic;
say $obj->{state};
substr($_, 0) = $obj;
say $obj->{state};

```

This outputs:

```
1
2

```

**Explanation:**

This is a straightforward application of overloading. Specifically, I overload the string conversion operator `""`, which gets called when the overloaded object is assigned to `substr()` (which, yes, is a legal lvalue in Perl).

There are also plenty of special variables in Perl which stringify anything assigned to them. For example, the following also works:

```
my $obj = new Magic;
say $obj->{state};
$0 = $obj;
say $obj->{state};

```

---

## Alternative solution

Here's another way to it:

```
package Magic {
    use Devel::Peek 'SvREFCNT';
    sub new { bless \my $foo }
    sub state { SvREFCNT ${$_[0]} }
}
use feature 'say';

my $obj = new Magic;
say $obj->state;
my $other = $obj;
say $obj->state;

```

Here, `state` is a method (we could make it an attribute with further tie / overload shenanigans, but that would complicate things) that literally counts the number of references to the object. Thus, unlike in the first solution, you actually have to assign `$obj` to a normal variable that can hold an object reference to make the state change.
> 5 votes

# Answer
# JavaScript

Ok, so i made a shorter version that works as SSCCE, but does no longer try to parse JavaScript properly, so the reference counting might not work when put inside a more complex script.

```
(function run () {
    var lineOne = getLine (1), a, b, x, y, z;
    var x = {
        get state () {
            var x=/([a-z]+)\s*=\s*([a-z]+)/,c;
            return 1 + Object.keys (c = run.toString ().split ('\n').slice (0,getLine (2)).filter (function (a) {return (x.test (a))}).reduce (function (a,b,c,d) {var r=b.match (x),t=r[2];while (a[t]){t=a[t]};a[r[1]]=t;return a}, {v:0})).reduce (function (a,b) {return (c[b]=="x"?1:0) + a},0)
        }
    };
    console.log (x.state);  //1
    console.log (x.state);  //1
    y = x;
    console.log (x.state);  //2
    z = y;
    console.log (x.state);  //3
    a = z;
    b = a;
    console.log (x.state);  //5
    a = null;
    console.log (x.state);  //4
    b = null;
    console.log (x.state);  //3
})() //1 1 2 3 5 4 3

function getLine(n) {
   try {
      to
   } catch (dat) {
      var stack = dat.stack.split('\n');
       for (var i = 0; i < stack.length; i++) {
           if (~stack[i].indexOf ('getLine')) break;
       }
      return dat.stack.split ('\n')[i + ~~n].match (/:(\d+)/)[1] - ~~window.hasOwnProperty ('__commandLineAPI')
   }
}

```
> 5 votes

# Answer
# Python

It's cheating a little, but how about:

```
import gc
class A(object):
    @property
    def state(self):
        return len(gc.get_referrers(self))

a = A()
print a.state
b = {"x": a}
print a.state
a.y = a
print a.state
del a
print b["x"].state

```
> 4 votes

# Answer
## C++11

though this can be extended for other languages that supports implicit / explicit destrucors

```
#include <iostream>
using namespace std;

class Foo {
    int *ptr;
public:
    Foo() {
        ptr = new int(0);
    }
    int state() {
        return *ptr;
    }
    ~Foo() {
        (*ptr)++;
    }
};
int main() {
    Foo a, b;
    cout << a.state() << " " << b.state() << "\n";
    {
        Foo c, d;
        c = a;
        d = b;
    }
   cout << a.state() << " " << b.state()  << "\n";

   return 0;
}

```

> The default assignment operator performs a shallow copy. So the receiving object still owns the pointer and any change implicitly affects the original object;
> 4 votes

# Answer
## Scala

Implicit conversions let you accomplish this while assigning to a normal local variable:

```
import scala.language.implicitConversions

class Obj {
  var counter = 0
}

implicit def o2s(x: Obj): String = {
  x.counter += 1
  x.toString
}

val obj = new Obj
println(obj.counter)
val s: String = obj
println(obj.counter)

```

You can accomplish that with inferred types, too:

```
var s = ""
s = obj

```

You can also use a custom setter method, though that requires the L-value to be a field:

```
object L {
  var _value = new Obj
  def value = _value
  def value_=(x: Obj): Unit = {
    _value = x
    x.counter += 1
  }
}

val obj = new Obj
println(obj.counter)
L.value = obj
println(obj.counter)

```
> 4 votes

# Answer
## D

```
struct Obj {
    int state;

    void opAssign (ref Obj other) {
        ++other.state;
    }
}

void main () {
    import std.stdio;

    Obj obj, lvalue;
    writeln(obj);
    lvalue = obj;
    writeln(obj);
}

```

Output:

```
Obj(0)
Obj(1)

```
> 3 votes

# Answer
# C++

This behavior is actually specified in the standard (and that's why it was deprecated).

```
#include<iostream>
#include<memory>
int main()
{
    std::auto_ptr<int> a(new int(0));
    std::cout<<a.get()<<'\n';
    std::auto_ptr<int> b = a;
    std::cout<<a.get()<<'\n';
}

```

Output

```
some address
0

```

The process that causes this is the same as Abhijit's answer but without requiring a `std::move` and the same as marinus' answer but using a standard class instead of defining it myself.

Edit: I'm adding some explanation. In the output, "some address" will actually be a hex value for the address of the allocated integer. `std::auto_ptr` releases its stores pointer when assigned to another `auto_ptr` and sets its internal pointer to 0. Calling `get()` retrieves access to the stores pointer.
> 3 votes

# Answer
**In Java**

I thought this was impossible in Java. But…

*Main class :*

```
public class MyAppOfCats {

  public static void main(String[] args) {
    Cat tom = new Cat();
    System.out.println(tom.state());
    // Output : NOT-BEST-CAT
    Cat.bestCat = tom;
    System.out.println(tom.state());
    // Output : BEST-CAT
  }

}

```

*Class Cat :*

```
public class Cat {

  static Cat bestCat;

  public Cat() {
    super();
  }

  public String state() {
      return ((this == Cat.bestCat) ? "BEST-CAT" : "NOT-BEST-CAT");
  }

}

```

I have been inspired by @tbodt.
> 3 votes

# Answer
# Ruby

As promised, here's the answer that inspired the question.

```
obj = Class.new { def self.state; to_s[/</] ? "Has not been assigned\n" : "Assigned to #{to_s}"; end }

print obj.state

LValue = obj

print obj.state

```

`Class.new` creates an anonymous class. Calling `to_s` on an anonymous class gives the default string representation of objects, which looks like `#<Class:0x007fe3b38ed958>`. However, once the class has been assigned to a constant, `to_s` becomes that constant. In Ruby, a constant is a variable that begins with an uppercase letter, so `obj` is a reference to the class that allows it to stay anonymous.

My code wraps `to_s` in a `state` method, so the output becomes

```
Has not been assigned
Assigned to LValue

```

Unlike most of the solutions here, this only works once: assigning `obj` to another constant won't change its string representation, and neither will assigning a new value to `LValue`.
> 3 votes

# Answer
# Python

```
import sys
class K:state = property(sys.getrefcount)

```
> 3 votes

# Answer
# Python 2.x

I couldn't find a proper way to do this without defining an extra class.

```
class State(object):
    def __init__(self):
        self.state = 0
    def __set__(self, obj, other):
        # Keep different references
        other.state += 1
        self.state += 2

class Program(object):
    obj, value = State(), State() # Create two State-objects
    def __init__(self):
        print "Before assignment:", self.obj.state, self.value.state # 0 0
        self.value = self.obj # Set value to obj (supposedly)
        print "After  assignment:", self.obj.state, self.value.state # 1 2
        self.value = self.obj
        print "2nd    assignment:", self.obj.state, self.value.state # 2 4

Program()

```
> 2 votes

# Answer
# Java

All the other solutions use their language's form of operator overloading. Java doesn't have operator overloading, so I thought I was stuck. But I came up with something.

Here's the main class:

```
public class Program {
    public static void main(String[] args) {
        Thing thing = new Thing(0);
        System.out.println(thing.getState());
        Thing.otherThing = thing;
        Thread.sleep(1);
        System.out.println(thing.getState());
    }
}

```

There are a few suspicious lines, but they wouldn't do anything if the `Thing` class was completely normal. It isn't:

```
public class Thing {
    private int state;

    public Thing(int state) {
        this.state = state;
    }

    public int getState() {
        return state;
    }

    // Please do your best to ignore the rest of this class.
    public static volatile Thing otherThing;
    static {
        Thread t = new Thread() {
            public void run() {
                Thing t = otherThing;
                while (true)
                    if (t != otherThing) {
                        t = otherThing;
                        t.state++;
                    }
            }
        };
        t.setDaemon(true);
        t.start();
    }
}

```

It's not guaranteed to work because of the threads, but I tested it on JDK 1.8u5, and it works there.
> 1 votes

# Answer
# Common Lisp

I define state as the number of special variables bound to a vector. So, assignment to a special variable changes the state.

```
(defgeneric state (object)
  (:documentation "Get the state of this object."))

(defmethod state ((object vector))
  ;; The state of a vector is the number of symbols bound to it.
  (let ((count 0))
    ;; Iterate each SYM, return COUNT.
    (do-all-symbols (sym count)
      ;; When SYM is bound to this vector, increment COUNT.
      (when (and (boundp sym) (eq (symbol-value sym) object))
    (incf count)))))

(defparameter *a* #(this is a vector))
(defparameter *b* nil)
(defparameter *c* nil)

(print (state *a*))
(setf *b* *a*)
(print (state *a*))
(print (state *a*))
(setf *c* *a*)
(print (state *a*))

```

Output:

```
1
2
2
3

```

It only works with assignments to special variables, not to lexical variables, nor to slots within an object.

Beware that `do-all-symbols` looks in all packages, so it misses variables that have no package. It might double-count symbols that exist in more than one package (when one package imported the symbol from another package).

# Ruby

Ruby is almost the same, but I define state as the number of constants referring to an array.

```
class Array
  # Get the state of this object.
  def state
    # The state of an array is the number of constants in modules
    # where the constants refer to this array.
    ObjectSpace.each_object(Module).inject(0) {|count, mod|
      count + mod.constants(false).count {|sym|
        begin
          mod.const_get(sym, false).equal?(self)
        rescue NameError
          false
        end
      }
    }
  end
end

A = %i[this is an array]
puts A.state
B = A
puts A.state
puts A.state
C = A
puts A.state

```

Output:

```
state-assign.rb:9:in `const_get': Use RbConfig instead of obsolete and deprecated Config.
1
2
2
3

```

This is a generalization of histocrat's answer to Ruby objects that are not classes or modules. The warning appears because the Config constant autoloads some code that made the warning.
> 1 votes

# Answer
# C++

The result may differ in different platforms. Tested on ideone.

```
#include <iostream>
#include <cassert>
// File format: [ciiiiciiii...] a char (1 byte) followed by its state (4 bytes)
// Each group takes 5 bytes
char Buffer[30]; // 5*6, six groups

struct Group {
    char c;
    int state;
};

int main(void) {
    assert(sizeof(char) == 1);
    assert(sizeof(int) == 4);

    Group& first_group = *(Group*)(&Buffer[0]); // Group 1 is at 0
    Group& second_group = *(Group*)(&Buffer[5]); // Group 2 is at 5

    first_group.c = '2';
    first_group.state = 1234;

    std::cout << first_group.state << std::endl;

    second_group = first_group;

    std::cout << first_group.state << std::endl;

    return 0;
}

```

Output:

```
1234
13010

```
> 0 votes

# Answer
## C#

```
class A
{
    public int N { get; set; }
    public override string ToString() { return N.ToString(); }
}
class B
{
    public int N { get; set; }
    public override string ToString() { return N.ToString(); }
    public static implicit operator A(B b) { b.N = -b.N; return new A { N = b.N }; }
}
public static void Test()
{
    A a = new A { N = 1 };
    B b = new B { N = 2 };
    Console.WriteLine("a is {0}, b is {1}", a, b);
    Console.WriteLine("a is {0}, b is {1}", a, b);
    a = b;
    Console.WriteLine("a is {0}, b is {1}", a, b);
    Console.WriteLine("a is {0}, b is {1}", a, b);
}

```

Output:

```
a is 1, b is 2
a is 1, b is 2
a is -2, b is -2
a is -2, b is -2

```
> 0 votes

---
Tags: popularity-contest, programming-puzzle
---


title: Format a Drop Capital

text:
# Question
Title: Format a Drop Capital
# Introduction

Write a program or function that adds a drop capital to a paragraph. The program will input the text to format, the column width, and the number of lines to drop the capital. The drop capitals look like this:

```
Lines:        2     3      4
Drop capital: A|    A.|    A..|
              ~'    ..|    ...|    etc.
                    ~~'    ...|
                           ~~~'

```

This is a related challenge.

# Input

* Input a string of printable ASCII characters (no tabs or newlines) and 2 integers greater than one.
* One integer is the number of columns that the output should have.
* The other is the number of lines spanned by the drop capital.
* The text string contains words separated by single spaces.
* **Assume none of the words will be longer than the column width.** That is, `column width > longest word + drop capital height`
* All lines will have at least one word.
* For this challenge, a word consists of any character other than a space.
* Input may be in any convenient format following the rules above.

# Output

* A left-justified block of text containing a drop capital with the specified number of lines.
* A line should contain as many words as possible without being longer than the column width.
* There is a space between the drop capital and the rest of each line.
* One trailing space or newline is allowed.

# Examples

```
Lines: 2 Columns: 10 Text: The quick brown fox jumped over the lazy dog.

T| he
~' quick
brown fox
jumped
over the
lazy dog.

Lines: 3 Columns: 10 Text: (Same as above)

T.| he
..| quick
~~' brown
fox jumped
over the
lazy dog.

Lines: 4 Columns: 10 Text: (Same as above)

T..| he
...| quick
...| brown
~~~' fox
jumped
over the
lazy dog.

Lines: 2 Columns: 80 Text: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor.

L| orem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
~' Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec
consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero
egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem
lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor.

Lines: 3 Columns: 80 Text: (Same as above)

L.| orem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
..| Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec
~~' consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget
libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta
lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non
tortor.

Lines: 4 Columns: 80 Text: (Same as above)

L..| orem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam
...| lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra
...| nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam
~~~' eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim,
ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies
a non tortor.

```

This is and standard loopholes apply.

# Answer
# Python 2, 202 bytes

```
def f(l,c,t):
 l-=1;s=['.'*l+'|']*l+['~'*l+"'"]
 s[0]=t[0]+s[0][1:];t=t[1:].split();j=0
 while t:
  w=t.pop(0)
  if len(s[j]+w)>=c:j+=1
  if j>=len(s):s.append(w)
  else:s[j]+=' '+w
 return '\n'.join(s)

```

Call as `f(Lines, Columns, Text)`

`f(4,100,'Stuff')` gives

```
S..| tuff
...|
...|
~~~'

```
> 1 votes

# Answer
# C#, 244 bytes

```
string F(int d,int c,string t){var w=t.Substring(1).Split(' ');t=""+t[0];for(int i=0,x=c,y=0;i<w.Length;x+=w[i++].Length+1)t+=(1>(x=x+w[i].Length>c?0:x)?"\n"+(y++<d?(y<d?"| ":"' ").PadLeft(x=d+1,y<d?'.':'~'):""):" ")+w[i];return t.Remove(1,2);}

```

Indentation, new lines and comments for clarity:

```
string F(int d,int c,string t){
    var w=t.Substring(1).Split(' ');
    t=""+t[0];
    for(int i=0,x=c,y=0;i<w.Length;x+=w[i++].Length+1)
        t+=(1>(x=x+w[i].Length>c?0:x)?"\n"+(y++<d?(y<d?"| ":"' ").PadLeft(x=d+1,y<d?'.':'~'):""):" ")+w[i];
    return t.Remove(1,2);
}

```
> 1 votes

---
Tags: code-golf, typography
---


title: Reverse a regex

text:
# Question
Title: Reverse a regex
# The Challenge

Given a valid regex, output a regex that that matches the same set of strings, but reversed.

# The Task

This challenge uses the most basic regex operations: `^`, `$`, `?`, `+`, `*`, `[]`, `{}`, `|`. There's no such thing as capture groups or any of that complicated stuff. Special characters can be escaped.

# Sample Input/Output

**Note: Invalid input will never be given, and there are generally multiple possible answers for a given input!**

```
Input      | Sample Output
-----------|-------------
abc        | cba
tuv?       | v?ut
a(b|c)     | (c|b)a
1[23]      | [23]1
a([bc]|cd) | (dc|[bc])a
^a[^bc]d$  | ^d[^bc]a$
x[yz]{1,2} | [yz]{1,2}x
p{2}       | p{2}
q{7,}      | q{7,}
\[c[de]    | [de]c\[
ab[c       | <output undefined>
a(?bc)     | <output undefined>
a[]]bc     | <output undefined>

```

# Demo

Working demo that demonstrates correct inputs/outputs. This has some additional logic for validating inputs that isn't necessary in a real answer. Consider invalid inputs to be undefined behavior.

**Specifics**

For simplicity, all special characters either have their special meaning or are escaped; that is, `[[]` isn't a character range for `[`. Length ranges come from standard POSIX EREs; that is, `{n}`, `{n,}`, and `{n,m}` are supported. The character ranges `[]` and `[^]` are supported. Because of these rules, and since no invalid input is given, you really need only copy the contents of these directly to the output. Lastly, greediness doesn't matter, i.e. it doesn't matter if the reversed regex finds a *different* match first, it just needs to find a match for the same set of strings.

# Scoring

Smallest program in bytes (barring cheating such as network requests) wins. Program can either use real IO or simply define a function.

# Answer
# Retina, ~~136~~ ~~114~~ 110 bytes

Yo dawg, I heard you like regex...

```
^
;
(T`^$`$^`;.
(.*);(\[(\\.|[^]])*]|\\.|.)([*+?]|{\d+(,|,\d+)?})?
$2$4!$1;
^\(!
)
^\)(.*)!(.+?)
($2$1
;$|!
<empty>

```

Where `<empty>` represents an empty trailing line. Run the code from a single file with the `-s` flag.

...when you wanna reverse regex you should use regex. When you wanna use regex you should use a regex-based programming language.

This code assumes that the input contains neither `;` nor `!` nor spaces. While I agree that that's a pretty strong and potentially invalid assumption, you could replace those three in the code with any three unprintable characters (like null bytes, bell character, `<DEL>` you name it), and it wouldn't affect the code size or functionality at all.

I'll add an explanation when I'm done golfing.
> 7 votes

# Answer
# JavaScript ES6, 574 bytes

I can probably remove a few `var` statements.

```
R=e=>{for(var s=0,c=[],h=/(\?|\+|\{\d*,*\d*\}|\*)(\?*)/,t=0;t<e.length;t++)switch(s){case 0:switch(e[t]){case"\\":t++,c.push("\\"+e[t]);break;case"[":j=t,s=1;break;case"(":k=t,s=2;break;default:var l=e.search(h,t);(l>=t+1||0>l)&&c.push(l==t+1?e[t]+e.slice(t,e.length).match(h)[0]:e[t])}break;case 1:"\\"==e[t]?t++:"]"==e[t]&&(c.push(e.slice(j,t+1)+(e.search(h,t)==t+1?e.slice(t,e.length).match(h)[0]:"")),s=0);break;case 2:"\\"==e[t]?t++:")"==e[t]&&(a=R(e.slice(k+1,t)),c.push("("+a+")"),s=0)}c.reverse(),r=c;var i=c.length-1;return"^"==c[i]&&(r[i]="$"),"$"==c[0]&&(r[0]="^"),r.join``}}

```

## JS ES6, untested, 559 bytes

Will test at home.

```
R=e=>{for(s=0,c=[],h=/(\?|\+|\{\d*,*\d*\}|\*)(\?*)/,t=0;t<e.length;t++)switch(s){case 0:switch(e[t]){case"\\":t++,c.push`\\${e[t]}`;break;case"[":j=t,s=1;break;case"(":k=t,s=2;break;default:l=e.search(h,t);(l>=t+1||0>l)&&c.push(l==t+1?e[t]+e.slice(t,e.length).match(h)[0]:e[t])}break;case 1:"\\"==e[t]?t++:"]"==e[t]&&(c.push(e.slice(j,t+1)+(e.search(h,t)==t+1?e.slice(t,e.length).match(h)[0]:"")),s=0);break;case 2:"\\"==e[t]?t++:")"==e[t]&&(a=R(e.slice(k+1,t)),c.push`(${a})`,s=0)}c.reverse(),r=c;i=c.length-1;return"^"==c[i]&&(r[i]="$"),"$"==c[0]&&(r[0]="^"),r.join``}}

```

# JavaScript ES5, ungolfed, 961 bytes

```
function revRegex(str){
 var mode = 0;
 var oS = [];
 var post = /(\?|\+|\{\d*,*\d*\}|\*)(\?*)/;
 for(var i=0;i<str.length;i++){
  switch(mode){
   case 0: switch(str[i]){
    case "\\": i++; oS.push("\\"+str[i]); break;
    case "[": j=i; mode = 1; break;
    case "(": k=i; mode = 2; break;
    default:
     var pLoc = str.search(post,i);
     if(pLoc>=i+1||pLoc<0){ // current is not pLoc
      if(pLoc==i+1){
       oS.push(str[i] + str.slice(i,str.length).match(post)[0]);
      } else {
       oS.push(str[i]);
      }
     }
   }; break;
   case 1: if(str[i]=="\\") i++; else if(str[i]=="]"){oS.push

(str.slice(j,i+1)+(str.search(post,i)==i+1?str.slice

(i,str.length).match(post)[0]:""));mode = 0}; break;
   case 2: if(str[i]=="\\") i++; else if(str[i]==")")

{a=revRegex(str.slice(k+1,i));oS.push("("+a+")");mode =

0};break;
  }
 }
 oS.reverse();
 r=oS;
 var l=oS.length-1;
 if(oS[l]=="^") r[l]="$";
 if(oS[0]=="$") r[0]="^";
 return r.join("");
}

```
> 2 votes

# Answer
# JavaScript ES6, 343 bytes

```
t=r=>(u="substr",T="(?:[+?*]|{\\d+(?:,\\d*)?})?)([^]*)",(c=r[0])=="(")?([n,s]=v(r[u](1)),[_,q,s]=s.match("^(\\)"+T),["("+n+q,s]):c==")"||c==null?["",r]:c=="^"?["^",r[u](1)]:c=="$"?["^",r[u](1)]:r.match("^("+/(?:\[(?:[^\]\\]|\\[^])*\]|[^[\\]|\\[^])/.source+T).slice(1);(v=r=>{var o="";do{[n,r]=t(r);o=n+o;}while(n&&r);return[o,r]})(prompt())[0]

```

Original code (the functions, but without `prompt`):

```
function reverse(regex) {
    var out = "";
    do {
        // console.log("calling term");
        var [node, regex] = term(regex);
        // console.log("reverse: " + [node, regex]);
        out = node + out;
    } while (node && regex);
    return [out, regex];
}

function term(regex) {
    switch (regex[0]) {
        case "(":
            // console.log("calling reverse");
            var [node, sequel] = reverse(regex.substr(1));
            // console.log("term: " + regex + " / " + [node, sequel]);
            var [_, quantifier, sequel] = sequel.match(/^(\)(?:[+?*]|{\d+(?:,\d*)?})?)([^]*)/);
            return ["(" + node + quantifier, sequel];
        case ")":
        case void 0:
            return ["", regex];
        case "^":
            return ["$", regex.substr(1)];
        case "$":
            return ["^", regex.substr(1)];
        default:
            return regex.match(/^((?:\[(?:[^\]\\]|\\[^])*\]|[^[\\]|\\[^])(?:[+?*]|{\d+(?:,\d+)?})?)([^]*)/).slice(1);
    }
}

reverse("^\\(([The(){}*\\] ]{2,3}world\\\\(begin(ner|ning)?|ends*)+|Con\\|ti\\*n\\)ue...[^%\\[\\]()\\\\])$")[0]

```

The code is implemented as a recursive top-down parser, so it may cause stack overflow on deeply nested input.

The code may cause infinite loop in invalid cases, since I don't test them, taking advantage of the "undefined behavior" clause.
> 2 votes

# Answer
# Python 3, 144 bytes

(This one *does not support qualifiers on a group* like `(a)+(b)*(cde)?`.)

```
import re;f=lambda x:''.join({e:e,'^':'$','$':'^','(':')',')':'('}[e]for e in re.findall(r'(?:\\.|\[(?:\\?.)+?\]|.)(?:[?+*]|\{.+?\})?',x)[::-1])

```

Test cases:

```
test_cases = [
    # Provided test cases
    r'abc',
    r'tuv?',
    r'a(b|c)',
    r'1[23]',
    r'a([bc]|cd)',
    r'^a[^bc]d$',
    r'x[yz]{1,2}',
    r'p{2}',
    r'q{7,}',
    r'\[c[de]',

    # Pathological cases
    r'a{3}b',
    r'(a)?(b)+',            # <-- currently failing!
    r'[\[]{5}[^\]]{6}',
    r'[\[]\]{7}',
    r'[\[\]]{8,9}',
    r'\(\)\^\$',

    # Undefined cases
    r'ab[c',
    r'a(?bc)',
    r'a[]]bc',
]

for t in test_cases:
    print(t, '->', f(t))

```

Result:

```
abc -> cba
tuv? -> v?ut
a(b|c) -> (c|b)a
1[23] -> [23]1
a([bc]|cd) -> (dc|[bc])a
^a[^bc]d$ -> ^d[^bc]a$
x[yz]{1,2} -> [yz]{1,2}x
p{2} -> p{2}
q{7,} -> q{7,}
\[c[de] -> [de]c\[
a{3}b -> ba{3}
(a)?(b)+ -> )+b))?a)                    # <-- note: wrong
[\[]{5}[^\]]{6} -> [^\]]{6}[\[]{5}
[\[]\]{7} -> \]{7}[\[]
[\[\]]{8,9} -> [\[\]]{8,9}
\(\)\^\$ -> \$\^\)\(
ab[c -> c[ba
a(?bc) -> (cb(?a
a[]]bc -> cb[]]a

```
> 0 votes

---
Tags: code-golf, regular-expression, parsing
---


title: Cell Phone Keyboard Typing

text:
# Question
Title: Cell Phone Keyboard Typing
# Cell Phone Keyboard Typing

This question was asked a while back, but was closed due to poor specs. So, I'm redoing it, with better specs. This question is related, but goes in the opposite direction.

Before T9 came around, in order to type a character in a text message, you had to press one of the number keys a number of times to get the character you wanted. For reference, here is the standard mapping:

```
+-------+-------+-------+
|   1   |   2   |   3   |
|  .?!1 |  ABC2 |  DEF3 |
+-------+-------+-------+
|   4   |   5   |   6   |
|  GHI4 |  JKL5 |  MNO6 |
+-------+-------+-------+
|   7   |   8   |   9   |
| PQRS7 |  TUV8 | WXYZ9 |
+-------+-------+-------+
|   *   |   0   |   #   |
|   ←   |SPACE 0|   →   |
+-------+-------+-------+

```

`*` is backspace, `0` is a space (`' '`) or the number `0`, and `#` confirms the current character. For the sake of simplicity, all characters are uppercase.

When you pressed a key multiple times, the selected character cycles through the possible characters for that key: `2 -> A`, `22 -> B`, `222 -> C`, `2222 -> 2`, `22222 -> A`, and so on. Note that, since `*` only has one option, pressing it repeatedly causes multiple backspaces to be entered. Pressing `#` multiple times in a row has no effect. A trailing `#` is unnecessary.

Additionally, if a different key is pressed immediately after pressing a key, the previous keypress is automatically confirmed. Thus, `223` is functionally identical to `22#3`.

Your challenge is to translate a series of keypresses into the corresponding string a cell phone would display.

## Examples

```
8#99999#055#33#999#22#666#2#777#3#1 -> T9 KEYBOARD
4433555#55566609666666677755533*3111 -> HELLO WORLD!
7##222#222**7#222#4 -> PPCG
00#0#00 -> 0 0

```

## Rules

* This is , so the shortest correct solution (in bytes) wins
* The winning answer will be chosen in one week
* Standard loopholes are forbidden
* Your answer may be in the form of a full program, a named function, or an anonymous function, taking input and producing output in one of the standard methods

# Leaderboard

The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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

```
## Language Name, N bytes

```

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

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

```

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

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

```

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

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

```

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 61545; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
# K5, 112 bytes

```
{(20#'((" ";".?!"),((3*!6),19 22)_`c$65+!26),'$!10)[.*x]20!#1_x}'(){$[42=*y;(-#y)_x;35=*y;x;x,,y]}/{(&~0=':x)_x}

```

This one is really a mess, but I think there's a fair amount of room to golf it down.

First we need to construct a lookup table for the keymap. There are keys with 2, 4 and 5 characters mapped to them, so padding every entry out to 20 simplifies the process of cyclically indexing this table later:

```
  (20#'((" ";".?!"),((3*!6),19 22)_`c$65+!26),'$!10)
(" 0 0 0 0 0 0 0 0 0 0"
 ".?!1.?!1.?!1.?!1.?!1"
 "ABC2ABC2ABC2ABC2ABC2"
 "DEF3DEF3DEF3DEF3DEF3"
 "GHI4GHI4GHI4GHI4GHI4"
 "JKL5JKL5JKL5JKL5JKL5"
 "MNO6MNO6MNO6MNO6MNO6"
 "PQRS7PQRS7PQRS7PQRS7"
 "TUV8TUV8TUV8TUV8TUV8"
 "WXYZ9WXYZ9WXYZ9WXYZ9")

```

Then I split the input into runs:

```
 {(&~0=':x)_x}"8#99999#055#33#999"
(,"8"
 ,"#"
 "99999"
 ,"#"
 ,"0"
 "55"
 ,"#"
 "33"
 ,"#"
 "999")

```

Drop any # runs and strip trailing runs every time I encounter a \*:

```
  (){$[42=*y;(-#y)_x;35=*y;x;x,,y]}/{(&~0=':x)_x}"8#99999#055#33#999"
(,"8"
 "99999"
 ,"0"
 "55"
 "33"
 "999")

```

And then I'm ready to simply index into that lookup table based on the length and first element of each run.

All together:

```
  {(20#'((" ";".?!"),((3*!6),19 22)_`c$65+!26),'$!10)[.*x]20!#1_x}'(){$[42=*y;(-#y)_x;35=*y;x;x,,y]}/{(&~0=':x)_x}"4433555#55566609666666677755533*3111"
"HELLO WORLD!"

```

## Edit:

Save 5 bytes:

```
0 3 6 9 12 15 19 22
((3*!6),19 22)

```
> 2 votes

# Answer
# JavaScript, ~~214~~ ~~184~~ ~~168~~ 162 bytes

```
x=>(x.match(/(.)\1*/g,f='').map(a=>f=(l=a.length,v=' 0#.?!1#ABC2#DEF3#GHI4#JKL5#MNO6#PQRS7#TUV8#WXYZ9'.split`#`[a[0]])?f+v[--l%v.length]:a<'*'?f:f.slice(0,-l)),f)

```

This can probably be made a little smaller, but I'm pretty happy with the result. Splits characters into repeated groups of one or more, then steps through the array, mapping each character to it's value in the hash and adding it onto the final string. If it comes across any number of '#', it ignores it. If it comes across any '\*', it removes that number of them from the end of the final string.
> 2 votes

# Answer
# Python 2, ~~230~~ 206 bytes

```
import re
f=lambda a,b=dict(zip("0123456789*#"," 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9~\b~".split("~"))):"".join([j and b[j][(len(i)-1)%len(b[j])]or b[i]for i,j in re.findall(r"((\d)\2*|.)",a)])

```

This one creates a function **f** which takes a string of keypresses as argument and returns the corresponding string a cell phone would display. It also happens to take an optional second argument as a dictionary mapping keys to their corresponding characters, eg **{"0": " 0", "1": ".?!1", ...}**.

First, the string of keypresses is grouped by repeating characters, eg **\["8", "#", "99999", "#", ...\]**. Then, the first character of each group is mapped in the dictionary passed as second argument, eg **9** maps to **WXYZ9**. Finally, the length of the group is used as offset in the value from the dictionary.

Note that the offset must use modulo on the length of the group of repeating characters because keypresses might cycle. Also note that the **#** character is mapped to **\0** and only removed at the end because **99#99** is not the same as **9999**.

Here is the output of the function for each of the examples in the question:

```
>>> print f("8#99999#055#33#999#22#666#2#777#3#1")
T9 KEYBOARD.
>>> print f("4433555#55566609666666677755533*3111")
HELLO WORLD!
>>> print f("7##222#222**7#222#4")
PPCG
>>> print f("00#0#00")
0 0

```
> 2 votes

# Answer
# Python 2, 265 bytes

It's way too long. IO: stdin, stdout.

```
a=reduce(lambda q,w:q+" "+[w,""][w=="#"]if q[-1]!=w else q+w,raw_input()).split()
while "*" in a:del a[a.index("*")-1:a.index("*")+1]
print"".join([(lambda a:a[len(q)%len(a)-1])(" 0:.?!1:ABC2:DEF3:GHI4:JKL5:MNO6:PQRS7:TUV8:WXYZ9".split(":")[int(q[0])])for q in a])

```
> 0 votes

# Answer
# Python 2, 237 bytes

Using cr3's dictionary, but without re.

```
def f(i):
 d=dict(zip("0123456789"," 0|.?!1|ABC2|DEF3|GHI4|JKL5|MNO6|PQRS7|TUV8|WXYZ9".split("|")))
 s,x,j='',i[0],0
 for c in i[1:]+'#':
  if c==x:j+=1
  else:
   if x>'/':s+=d[x][j%len(d[x])]
   j=0
  if c=='*':s=s[:-1]
  x=c
 return s

```
> 0 votes

---
Tags: code-golf, string, keyboard
---


title: Beta's Snowflake

text:
# Question
Title: Beta's Snowflake
## Challenge

Winter is fast approaching with many places receiving the first layers of snow for the 15/16 season, so why don't we break out the snow machines and code ourselves some snow?

Given a integer `n` via STDIN, output an ASCII representation Beta's snowflake (as described below) at level `n`.

## Beta's Snowflake

The snowflake starts off at level 0 with a single x:

```
x

```

Then, on each corner you add one of these shapes:

```
x
xx

```

You add the above shape to a top right corner. For a bottom right corner, rotate it 90° clockwise, for bottom left, 180° clockwise and for top left, 270° clockwise.

If you do that, you get the following shape:

```
 x x
xx xx
  x
xx xx
 x x

```

Take note of the orientation of the shapes. Carrying on we add more of the shapes to each corner, using the orientation rules described above, to the diagram to get level 2:

```
  x x x
 xxxxxxx
xx x x xx
 xxx xxx
xx  x  xx
 xxx xxx
xx x x xx
 xxxxxxx
  x x x

```

Note that the shapes are only added to `x`s with two or more exposed sides (which is referred to as a corner above).

The L-shapes may and will overlap for values of `n` greater than 1. For example:

If level 0 is:

```
x x

```

Then there must be overlaps in level 1 (indicated with an `o`, do not include the `o` in your output):

```
 x o x
xxxoxxx
  x x
xxxoxxx
 x o x

```

Your task is to output this ASCII representation of Beta's snowflake.

## Bonus

There will be a 50 rep bonus for the shortest program which, when `n` is negative, outputs the snowflake (at level `n*-1`) as an image or graphically to the screen.

You may have a separate programs for the bounty and the main task.

## Winning

The shortest program in bytes wins.

# Answer
> 8 votes
# CJam, ~~88~~ ~~83~~ 82 bytes

```
1]]{{0f+zW%}8*{YYb_m*{~W$m>fm>}%z:z8Ybff=__1m>\1fm>]:zWf%(\:..|}4*..|}q~*" x"ff=N*

```

Test it here.

I think I can save a lot in how I detect where the corners are. But at least I finally know what the next iterations look like:

**N = 3**:

```
   x x x x
  xxxxxxxxx
 xx x x x xx
xx xxxxxxx xx
 xxx x x xxx
xx xxx xxx xx
 xxx  x  xxx
xx xxx xxx xx
 xxx x x xxx
xx xxxxxxx xx
 xx x x x xx
  xxxxxxxxx
   x x x x

```

**N = 4:**

```
    x x x x x
   xxxxxxxxxxx
  xx x x x x xx
 xx xxxxxxxxx xx
xx xx x x x xx xx
 xxx xxxxxxx xxx
xx xxx x x xxx xx
 xxx xxx xxx xxx
xx xxx  x  xxx xx
 xxx xxx xxx xxx
xx xxx x x xxx xx
 xxx xxxxxxx xxx
xx xx x x x xx xx
 xx xxxxxxxxx xx
  xx x x x x xx
   xxxxxxxxxxx
    x x x x x

```

Looking at these, they seem to be a lot more regular than I expected, and some sort of analytic solution which generates them directly might be much shorter.

# Answer
> 1 votes
# Python 2, 269 bytes

Doesn't place the shapes at each corner, but determines whether a character is in the snowflake based on the coordinates.

First one corner is generated, and then mirrored around to the full snowflake.

```
i=input()
d=2*i+1
s=[x[:]for x in[[0]*d]*d]
s[0][0]=1
if i:s[1][1]=1
for j in range(2,d):
 for v in range(j+1):s[j][v]=s[v][j]=(j+v)%3!=1and j+v<d+i if v>j/2 else j%2==1or j%4+v%2in[0,3]
for l in[l[:0:-1]+l for l in s[:0:-1]+s]:print''.join(['X'if n else' 'for n in l])

```

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


title: A regexp that does not match itself

text:
# Question
Title: A regexp that does not match itself
Can you think of a regular expression that does not match itself?

# Answer
> 4 votes
A few on 2 chars

```
^$

\s

\d

\n

\t

\r

```

And many more consisting of a \ and a lowercase character.

---
Tags: regular-expression
---