Created
July 7, 2009 08:39
-
-
Save dazza/141964 to your computer and use it in GitHub Desktop.
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.Text; | |
namespace MyClass | |
{ | |
class StepperMotor | |
{ | |
public int rotateToNearest(int n, int current, int[] target) | |
{ | |
current %= n; | |
if (current > n / 2) | |
{ | |
current -= n / 2; | |
} | |
for (int i = 0; i < target.Length; ++i) | |
{ | |
target[i] %= n; | |
if(target[i] > n/2) | |
{ | |
target[i] -= n; | |
} | |
} | |
int MinDist = 2147483647; | |
int MinTarget = -1; | |
for (int i = 0; i < target.Length; ++i) | |
{ | |
int dist = Math.Abs(target[i] - current); | |
if ((dist < MinDist) || (dist == MinDist && target[i] > MinTarget)) | |
{ | |
MinDist = dist; | |
MinTarget = i; | |
} | |
} | |
if (target[MinTarget] < current) | |
{ | |
if (current - target[MinTarget] < n - current + target[MinTarget]) | |
{ | |
return target[MinTarget] - current; | |
} | |
else | |
{ | |
return n - current + target[MinTarget]; | |
} | |
} | |
else | |
{ | |
if (-current + target[MinTarget] < n + current - target[MinTarget]) | |
{ | |
return target[MinTarget] - current; | |
} | |
else | |
{ | |
return -(n + current - target[MinTarget]); | |
} | |
} | |
} | |
} | |
class Tester | |
{ | |
static void Main() | |
{ | |
string str; | |
str = Console.ReadLine(); | |
while (!string.IsNullOrEmpty(str)) | |
{ | |
int n; | |
int.TryParse(str, out n); | |
str = Console.ReadLine(); | |
int current; | |
int.TryParse(str, out current); | |
bool isLastLine = false; | |
List<int> list = new List<int>(); | |
while(!isLastLine) | |
{ | |
str = Console.ReadLine(); | |
if(str[0]=='{') | |
{ | |
str = str.Remove(0, 1); | |
} | |
if(str[str.Length-1]=='}') | |
{ | |
str = str.Remove(str.Length - 1, 1); | |
isLastLine = true; | |
} | |
string[] value = str.Split(','); | |
for (int i = 0; i < value.Length; ++i) | |
{ | |
int item; | |
if (value[i] != "") | |
{ | |
bool re = int.TryParse(value[i], out item); | |
list.Add(item); | |
} | |
} | |
} | |
int[] target = list.ToArray(); | |
StepperMotor sm = new StepperMotor(); | |
int returnVal = sm.rotateToNearest(n, current, target); | |
Console.WriteLine(returnVal); | |
str = Console.ReadLine(); | |
} | |
}//end of Main() | |
}//end of tester | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment