Last active
February 2, 2023 02:26
-
-
Save JonDouglas/9279514 to your computer and use it in GitHub Desktop.
Mirror
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace Mirror | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
int[] nums = {1, 2, 3, 8, 9, 3, 2, 1}; | |
Console.WriteLine(Mirror(nums).ToString()); | |
} | |
public static int Mirror(int[] temp) | |
{ | |
int currentMirror = 0; | |
int longestMirror = 0; | |
int leftIndex; | |
int rightIndex; | |
for (int i = 0; i < temp.Length; i++) | |
{ | |
//Get our initial rightIndex that matches | |
rightIndex = lastArrayIndex(temp, temp[i], temp.Length - 1); | |
//Otherwise there are no more matches of (left -> right) | |
while (rightIndex != -1) | |
{ | |
currentMirror = 0; | |
leftIndex = i; | |
//Increment from the left and decrement from the right if we have matches | |
while (leftIndex < temp.Length && rightIndex >= 0 && temp[leftIndex] == temp[rightIndex]) | |
{ | |
leftIndex++; | |
rightIndex--; | |
currentMirror++; | |
} | |
//Make the longest mirror hold while we iterate this loop | |
if (currentMirror > longestMirror) | |
{ | |
longestMirror = currentMirror; | |
} | |
//Get the next index of the value that matches(Going from the right to the left) | |
rightIndex = lastArrayIndex(temp, temp[i], rightIndex); | |
} | |
} | |
return longestMirror; | |
} | |
public static int lastArrayIndex(int[] temp, int value, int index) | |
{ | |
while (index >= 0) | |
{ | |
//Check if the value at the index is equal to the current leftIndex (Checking left == right) | |
if (temp[index] == value) | |
{ | |
return index; | |
} | |
index--; | |
} | |
return -1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Welcom