Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace ShuffleCharacters
- {
- public static class StringExtension
- {
- /// <summary>
- /// Shuffles characters in source string according some rule.
- /// </summary>
- /// <param name="source">The source string.</param>
- /// <param name="count">The count of iterations.</param>
- /// <returns>Result string.</returns>
- /// <exception cref="ArgumentException">Source string is null or empty or white spaces.</exception>
- /// <exception cref="ArgumentException">Count of iterations is less than 0.</exception>
- public static string ShuffleChars(string source, int count)
- {
- if (string.IsNullOrWhiteSpace(source))
- {
- throw new ArgumentException("Source string is null or empty or white spaces.", nameof(source));
- }
- if (count < 0)
- {
- throw new ArgumentException("Count of iterations is less than 0", nameof(count));
- }
- bool SequenceEqual(char[] a, char[] b)
- {
- for (int i = 0; i < a.Length; i++)
- {
- if (a[i] != b[i])
- {
- return false;
- }
- }
- return true;
- }
- char[] result = source.ToCharArray();
- char[] array = new char[source.Length];
- char[] start = new char[source.Length];
- Array.Copy(result, start, result.Length);
- int t = 0;
- int middle = (source.Length / 2) + (source.Length % 2);
- for (int i = 0; i < count; i++)
- {
- (array, result) = (result, array);
- for (int j = 0; j < middle; j++)
- {
- result[j] = array[j * 2];
- }
- for (int j = middle, k = 1; j < source.Length; j++, k += 2)
- {
- result[j] = array[k];
- }
- t++;
- if (SequenceEqual(result, start))
- {
- while (count > i + t)
- {
- count -= t;
- }
- }
- }
- return new string(result);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement