arr[i] = arr[arr[i]] in place
namespace arrOfIEqualsArrOfArrOfI
{
class Program
{
/*Logic used here is if X = X + ((Y % arr.length) * arr.length).
*Then X % arr.length would give you X and
*X / arr.length would give you Y.
*/
static void relocate(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
arr[i] += (arr[arr[i]] % arr.Length) * arr.Length;
}
for (int i = 0; i < arr.Length; i++)
{
arr[i] /= arr.Length;
}
}
static void Main(string[] args)
{
int[] arr = { 3,0,1,2 };
relocate(arr);
foreach (int a in arr)
{
Console.WriteLine(a);
}
}
}
}
No comments:
Post a Comment