Okay so this is something that is more of me being a developer over time and solving HackerRank problems usually of the data nature more than the pure mathmatical nature faster. The problem is here: https://www.hackerrank.com/challenges/larrys-array/problem
I had an original bit of code similar to: (it is messy because I encapsulated it more once I got further but it passed all their examples)
public static string LarrysArray(List list)
{
var cnt = list.Count;
var result = "No";
for (int i = 0; i < cnt-3; i++)
{
if (i == 0 && list[0] != 1)
{
list = RotateList(list);
if (CheckThree(list))
{
result = "Yes";
continue;
}
list = RotateList(list);
if (CheckThree(list))
{
result = "Yes";
continue;
}
else
{
result = "No";
}
}
else
{
list = list.Skip(1).ToList();
if (CheckThree(list))
{
result = "Yes";
continue;
}
else
{
list = RotateList(list);
if (CheckThree(list))
{
result = "Yes";
continue;
}
list = RotateList(list);
if (CheckThree(list))
{
result = "Yes";
continue;
}
else
{
result = "No";
}
}
}
}
return result;
}
public static List RotateList(List list) => new List { list[1], list[2], list[0] }.Concat(list.Skip(3)).ToList();
public static bool CheckThree(List list) => list[0] + 1 == list[1] && list[1] +1 == list[2];
But then it failed on this test:
{17, 21, 2, 1, 16, 9, 12, 11, 6, 18, 20, 7, 14, 8, 19, 10, 3, 4, 13, 5, 15}
So I looked online and was like okay who did this challenge in less code and faster and I see this:
public static string LarrysArray(List A)
{
int count = 0;
for(int i = 0; i < A.Count - 1; i++)
{
for (int j = i + 1; j < A.Count; j++)
{
Console.WriteLine($"{A[i]} {A[j]}");
if (A[i] > A[j])
{
count++;
}
}
}
return (count % 2 == 0) ? "YES" : "NO";
}
So first off I don't get mathematics enough to think in pure functions. But my programming brain just goes: "Oh I have to do a sequence, rotate three ONLY at a time if they don't match. If the rotation fails return." So when I see a function of essentially: "Two loops, first loop is the number you are on, second loop is ANY NUMBER after it. If there is any number after the first loop, count up. If the count is divisible by two you succeeded" WTH? Really.
So first off just tell me:
If '1' is in the fourth position how can it ever be before 21 or 17 if I can only rotate three at a time? Or if I missed something in the question and I can go descending somehow. How can 20 get near the 2nd position when it's further down.
I really just want to understand this further as I consider myself a senior full stack developer but this question I just could not get in my brain. Someone that is more C++ or Python and algorithms probably deals with these functional problems more and can see it quickly. I just need to see rotation at a time why this works. Because to me rotating by three indexes, versus just seeing what is larger ahead are two entirely different things.