Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace ShiftArrayElements
- {
- public static class EnumShifter
- {
- /// <summary>
- /// Shifts elements in a <see cref="source"/> array using directions from <see cref="directions"/> array, one element shift per each direction array element.
- /// </summary>
- /// <param name="source">A source array.</param>
- /// <param name="directions">An array with directions.</param>
- /// <returns>An array with shifted elements.</returns>
- /// <exception cref="ArgumentNullException">source array is null.</exception>
- /// <exception cref="ArgumentNullException">directions array is null.</exception>
- /// <exception cref="InvalidOperationException">direction array contains an element that is not <see cref="Direction.Left"/> or <see cref="Direction.Right"/>.</exception>
- public static int[] Shift(int[] source, Direction[] directions)
- {
- // #1. Implement the method using "for" statements and indexers only (don't use Array.Copy method here).
- if (source is null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (directions is null)
- {
- throw new ArgumentNullException(nameof(directions));
- }
- for (int i = 0; i < directions.Length; i++)
- {
- switch (directions[i])
- {
- case Direction.Left:
- {
- int firstElemen = source[0];
- for (int k = 0; k < source.Length - 1; k++)
- {
- source[k] = source[k + 1];
- }
- source[^1] = firstElemen;
- break;
- }
- case Direction.Right:
- {
- int lastElement = source[^1];
- for (int k = source.Length - 1; k > 0; k--)
- {
- source[k] = source[k - 1];
- }
- source[0] = lastElement;
- break;
- }
- default:
- throw new InvalidOperationException($"Incorrect {directions} enum value.");
- }
- }
- return source;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement