-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathTOANDFRO.cs
64 lines (58 loc) · 2 KB
/
TOANDFRO.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Text;
// https://www.spoj.com/problems/TOANDFRO/ #ad-hoc #strings
// Given an encoded message and the number of columns used to encode the message,
// transform the message to the array used for the encoding, and then to the
// original (padded) message.
public static class TOANDFRO
{
public static string Solve(int columnCount, string encodedMessage)
{
int rowCount = encodedMessage.Length / columnCount;
char[,] messageArray = new char[rowCount, columnCount];
// Traverse the array as it was traversed to create the encoded message,
// but now instead of filling in the message, fill in the array.
for (int r = 0, i = 0; r < rowCount; ++r)
{
if (r % 2 == 0)
{
// On an even row, so we're filling in from left to right.
for (int c = 0; c < columnCount; ++c)
{
messageArray[r, c] = encodedMessage[i++];
}
}
else
{
// On an odd row, so we're filling in from right to left.
for (int c = columnCount - 1; c >= 0; --c)
{
messageArray[r, c] = encodedMessage[i++];
}
}
}
var originalMessage = new StringBuilder();
// Traverse the array as it was traversed to set the original message,
// but now instead of filling in the array, fill in the original message.
for (int c = 0; c < columnCount; ++c)
{
for (int r = 0; r < rowCount; ++r)
{
originalMessage.Append(messageArray[r, c]);
}
}
return originalMessage.ToString();
}
}
public static class Program
{
private static void Main()
{
int columnCount;
while ((columnCount = int.Parse(Console.ReadLine())) != 0)
{
Console.WriteLine(
TOANDFRO.Solve(columnCount, Console.ReadLine()));
}
}
}