Sha256: 5557c0f891385636e9c78ceb5d417df63b1736d9120b41cfb8be1d7f2091cb67

Contents?: true

Size: 1.18 KB

Versions: 396

Compression:

Stored size: 1.18 KB

Contents

using System;
using System.Linq;

public class RailFenceCipher
{
    private readonly int _rails;
    private readonly int _size;

    public RailFenceCipher(int rails)
    {
        _rails = rails;
        _size = rails * 2 - 2;
    }

    public string Encode(string input)
    {
        return input
            .Select((c, i) => Tuple.Create(Track(i), c))
            .GroupBy(x => x.Item1)
            .Select(x => new string(x.Select(y => y.Item2).ToArray()))
            .Aggregate("", (acc, x) => acc + x);
    }

    public string Decode(string input)
    {
        return Enumerable.Range(0, input.Length)
            .GroupBy(Track)
            .SelectMany(x => x)
            .Zip(input, Tuple.Create)
            .OrderBy(x => x.Item1)
            .Aggregate("", (s, tuple) => s + tuple.Item2);
    }

    private int Track(int index)
    {
        if (IsCorrect(index))
        {
            return 0;
        }

        if (IsCorrect(index - _rails + 1))
        {
            return _rails - 1;
        }

        return Enumerable.Range(1, _rails - 1).First(i => IsCorrect(index - i) || IsCorrect(index - _size + i));
    }

    private bool IsCorrect(int index) => index % _size == 0;
}

Version data entries

396 entries across 396 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.179 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.178 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.177 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.176 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.175 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.174 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.173 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.172 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.171 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.170 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.169 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.167 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.166 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.165 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.164 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.163 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.162 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.161 tracks/csharp/exercises/rail-fence-cipher/Example.cs
trackler-2.2.1.160 tracks/csharp/exercises/rail-fence-cipher/Example.cs