Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace ShiftArrayElements
- {
- public static class Shifter
- {
- /// <summary>
- /// Shifts elements in a <see cref="source"/> array using <see cref="iterations"/> array for getting directions and iterations (see README.md for detailed instructions).
- /// </summary>
- /// <param name="source">A source array.</param>
- /// <param name="iterations">An array with iterations.</param>
- /// <returns>An array with shifted elements.</returns>
- /// <exception cref="ArgumentNullException">source array is null.</exception>
- /// <exception cref="ArgumentNullException">iterations array is null.</exception>
- public static int[] Shift(int[] source, int[] iterations)
- {
- // #2. Implement the method using "for" statements and Array.Copy method.
- if (source is null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (iterations is null)
- {
- throw new ArgumentNullException(nameof(iterations));
- }
- int sumEven = 0;
- int sumOdd = 0;
- for (int i = 0; i < iterations.Length; i += 2)
- {
- sumEven += iterations[i];
- }
- for (int i = 1; i < iterations.Length; i += 2)
- {
- sumOdd += iterations[i];
- }
- int iteration;
- if (sumEven > sumOdd)
- {
- iteration = sumEven - sumOdd;
- ShiftLeft(source, iteration);
- }
- else if (sumEven == sumOdd)
- {
- return source;
- }
- else
- {
- iteration = sumOdd - sumEven;
- ShiftRight(source, iteration);
- }
- return source;
- }
- private static void ShiftLeft(int[] array, int iterations = 1)
- {
- for (int i = 0; i < iterations; i++)
- {
- int firstElemen = array[0];
- for (int k = 0; k < array.Length - 1; k++)
- {
- array[k] = array[k + 1];
- }
- array[^1] = firstElemen;
- }
- }
- private static void ShiftRight(int[] array, int iterations = 1)
- {
- for (int i = 0; i < iterations; i++)
- {
- int lastElement = array[^1];
- for (int k = array.Length - 1; k > 0; k--)
- {
- array[k] = array[k - 1];
- }
- array[0] = lastElement;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement