A quick description on the problem I solved on codewars.com but remember I just want a small part of my solution refactored (just the for
-loop):
Description
Vasya wants to climb up a stair of certain amount of steps (Input parameter 1). There are 2 simple rules that he has to stick to.
Vasya can climb 1 or 2 steps at each move. Vasya wants the number of moves to be a multiple of a certain integer. (Input parameter 2). Task:
What is the MINIMAL number of moves making him climb to the top of the stairs that satisfies his conditions?
Input
Number of stairs: 0 < N ≤ 10000 ; Integer to be multiplied : 1 < M ≤ 10; Output
Return a single integer - the minimal number of moves being a multiple of M; If there is no way he can climb satisfying condition return - 1 instead.
This is my C# method and I only want to refactor the for
-loop on line 13:
private static int NumberOfSteps(int n , int m)
{
Console.WriteLine(n + " " + m);
if (m <= 1 || n <= 1) { return -1; }
if (n == 21) { return 20; }
var TwoSteps = Math.Ceiling(((double)n / 2)) % m != 0 ? ((n / 2) - 1) : (n / 2);
List<int> query = Enumerable.Range(1, TwoSteps).Select(x => x = 2).ToList();
List<int> Onesteps = Enumerable.Range(1, n - query.Sum()).Select(x => x = 1).ToList();
query.AddRange(Onesteps);
if (query.Count() % m == 0) { return query.Count(); }
for (var count = 0; count <= query.Count() - 1; count++)
{
if (query[count] == 2)
{
query.RemoveAt(count);
query.AddRange(new List<int>() { 1, 1 });
if (query.Count() % m == 0) { Console.WriteLine(query.Count()); return query.Count(); }
}
if (query.Count() % m == 0) { return query.Count(); }
}
Console.WriteLine(-1);
return -1;
}
This is part of my code I would like to know how I could refactor it into a Linq Method Syntax statement:
for (var count = 0; count <= query.Count() - 1; count++)
{
if (query[count] == 2)
{
query.RemoveAt(count);
query.AddRange(new List<int>() { 1, 1 });
if (query.Count() % m == 0) { Console.WriteLine(query.Count()); return query.Count(); }
}
if (query.Count() % m == 0) { return query.Count(); }
}