Skip to content

Instantly share code, notes, and snippets.

@sholfen
Created November 9, 2015 03:59
Show Gist options
  • Save sholfen/6fe45f20143d2e51a145 to your computer and use it in GitHub Desktop.
Save sholfen/6fe45f20143d2e51a145 to your computer and use it in GitHub Desktop.
for Codility PermMissingElem
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PermMissingElem
{
class Program
{
static void Main(string[] args)
{
int[] A = { 2, 3, 5, 4 };
Solution sol = new Solution();
int result = sol.solution(A);
Console.WriteLine("result is: " + result.ToString());
}
}
public class Solution
{
public int lastElement = -1;
public int solution(int[] input)
{
if(input.Length==0)
{
return 1;
}
int arraySize = input.Length;
int missedElement = -1;
for (int i = 0; i < arraySize; i++)
{
if (input[i] - 1 == arraySize)
{
input[i] = -1;
lastElement = arraySize;
}
else if (input[i] - 1 != i)
{
MoveELement(input, i);
}
}
Console.WriteLine("print array");
for (int i = 0; i < arraySize; i++)
{
if (input[i] == -1)
{
missedElement = i + 1;
}
Console.WriteLine(input[i]);
}
if (missedElement == -1)
{
missedElement = arraySize + 1;
}
return missedElement;
}
public void MoveELement(int[] input, int index)
{
bool stopFlag = false;
int currentValue = input[index];
input[index] = -1;
while (!stopFlag)
{
if (currentValue - 1 == input.Length)
{
lastElement = currentValue;
stopFlag = true;
Console.WriteLine("assign to last element");
}
else if (input[currentValue - 1] == -1)
{
input[currentValue - 1] = currentValue;
stopFlag = true;
}
else
{
int temp = input[currentValue - 1];
input[currentValue - 1] = currentValue;
currentValue = temp;
Console.WriteLine("not current value is " + currentValue.ToString());
}
Console.WriteLine("stop flag is " + stopFlag.ToString());
//System.Threading.Thread.Sleep(1000);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment