Skip to main content
1 of 4
VisualMelon
  • 3.9k
  • 18
  • 39

C# 433

Quick job hopefully making good use of LINQ

using C=System.Console;using System.Linq;class P{static void Main(){var D=("\n"+C.In.ReadToEnd()+"\n").Split('\n');var E=D.Select(l=>(" "+l.PadRight(D.Max(m=>m.Length+1))).ToCharArray()).ToArray();int L=E.Length,i=L,j,I,J,k,d,c=0;for(;i-->0;)for(j=E[i].Length;j-->0;)if(E[I=i][J=j]==43){d=0;for(c++;(k=E[I+=((d&2)-1)*(d&1)][J+=((d&2)-1)*(~d&1)])>32;)if(k<44){E[I][J]=' ';d=d%2<1?E[I-1][J]<99?3:1:E[I][J-1]!=45?2:0;}}C.WriteLine(c);}}

First it reads in the input, and makes it nice and rectangular, with a " " border so we don't have to do any bounds checking. Then it looks back through the rectangle, so it always hits a right-bottom corner. When it hits one of these, it directs itself up, following any +s it meets, and clearing them as it goes (with a space). It stops following when it meets a space. Tested on the five given examples.

using C=System.Console;
using System.Linq;

class P
{
    // this is far too LINQy
    static void Main()
    {
        // 43  + 00101011
        // 45  - 00101101
        // 124 | 01111100
        
        // read in
        var D=("\n"+C.In.ReadToEnd()+"\n").Split('\n'); // say no to verticle bounds checking
        // max all the lines the same length
        var E=D.Select(l=>(" "+l.PadRight(D.Max(m=>m.Length+1))).ToCharArray()).ToArray(); // say no to horizontal bounds checking
        
        // consume +s
        int L=E.Length,i=L,j,I,J,k,
        d, // d is direction of travel (1 == vertical?, 2 == down/right?)
        c=0; // c is loop count
        for(;i-->0;)
            for(j=E[i].Length;j-->0;)
                if(E[I=i][J=j]==43) // right-most lower-most +
                {
                    // use I and J in here
                    d=0; // go up
                    
                    for(c++; // increment counter
                        (k=E[I+=((d&2)-1)*(d&1)][J+=((d&2)-1)*(~d&1)])>32 // move I and J, then check we havn't hit a space
                        ;)
                        if(k<44) // +
                        {
                            E[I][J]=' '; // toodles
                            
                            d=
                                d%2<1? // currently horizontal, must go vertical
                                    E[I-1][J]<99?3 // can't go up, must go down
                                    :1 // can go up, go up
                                : // currently verticle, must go horizontal
                                    E[I][J-1]!=45?2 // can't go left, must go right
                                    :0 // can go left, go left
                                ;
                        }
                    }
        
        // output result
        C.WriteLine(c);
    }
}
VisualMelon
  • 3.9k
  • 18
  • 39