My method has a parameter, I have to use that in my For loop to iterate.
For example, I have a text file with 4 lines.
If the Param is 1, the for loop must iterate through the last three lines
If the Param is 2, the for loop must iterate through the last two lines
If the Param is 3, the for loop must iterate through the last one line
How can i pass this param in my For loop to achieve all the three scenarios stated above ?
for(int i = param; i < lines.Count ; i++) {...}
or with LINQ:
foreach(var line in lines.Skip(lines.Count - param)) {...}
You should try something like
for (int i = param; i < whateverCount; i++)
{
// do something
}
Where param would be the item to start from. Just remember that MOST arrays/list are zero based, but there are cases where they are 1 based.
private void YourFunction(int value)
{
for(int x=0;x<4-value;x++)
{
//loop will happen 4 - value times, 4-3 = 1, 4-2 =2, 4-1 = 3 times
}
}
Related
I have a recursion assignment where I have to input into console the following data:
On the first line a natural number equal with the number of tiles I have to input on the following lines (in my example the first number is 6).
On the following lines the domino tiles in the following order:
1 2
1 3
3 4
2 3
3 5
4 5
On the last line another number representing the number of tiles that needs to be returned on each separate line (in my example the number is equal with 3).
With this data I have to display all possible combinations of pairs. For each separate line the number the second number from the first pair has to be equal with the first number of the following pair and so on. I had a hint for this assignment where I have to declare an intermediary list that is equal with the function (using recursion from the start) but when I'm trying to run the code it gives me a null exception for the intermediaryList.
In the first instance I read the data as a 2d array but settled with a simple string array where.
This is my code so far, could you help me with a suggestion, how to avoid the null exception?
(sorry if I missed something from the explanation, this is my second post here so far and thank you in advance). Also I have to mention that I'm allowed to use just "using System;" Not allowed to use Linq or anything else.
enter code here
static string[] ReadDominoTiles(int n)
{
string[] input = new string[n];
for (int i = 0; i < n; i++)
{
input[i] = Console.ReadLine();
}
return input;
}
static string[] DominoSolution(string[] dominoTiles, int numberOfPairs)
{
string[] finalList = new string[numberOfPairs];
if (numberOfPairs == 1)
{
return finalList;
}
string[] intermediaryList = DominoSolution(dominoTiles, numberOfPairs - 1);
for (int i = 0; i < intermediaryList.Length; i++)
{
for (int j = 0; j < dominoTiles.Length; j++)
{
// This is where I get the nullref exception, every value from intermediaryList is null
if (intermediaryList[i] != dominoTiles[j] && intermediaryList[j][1] == dominoTiles[j][0])
{
finalList[j] += intermediaryList[j] + " " + dominoTiles[j];
}
}
}
return finalList;
}
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
string[] dominoTiles = ReadDominoTiles(n);
int numberOfPairs = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(DominoSolution(dominoTiles, numberOfPairs));
}
This is where I get the nullref exception, every value from intermediaryList is null
That's correct, you call the function recursively after doing exactly zero work, besides adding a recursion termination condition which returns an array of nulls. So the first time you come out of your recursion you have in intermediaryList a number of null elements, so when you pretend they're strings and try to get intermediaryList[j][1] you'll get a null reference exception.
As to the solution, it's not exactly clear what's with all the arrays you're allocating. Use a List<> with an actual type and do your work properly. Though I hate to break it to you but if I understand your assignment correctly the solution will use backtracking and combinatorics, which is much more code and much better structured than what you have here.
I am trying to filter a list of int based on multiples of a specific number, but I am not sure how to do this. I have searched this forum and found nothing related, but apologies in advance if I'm wrong.
Here is my code:
int val = 28;
List<int> divisible = new List<int>();
for (int i = 1; i <= val; i++) {
divisible.Add(i);
}
foreach(var d in divisible)
{
if(val % d == 0)
{
// do something
}
else
{
// get rid of all multiples of the number that "val" is not divisible by
}
}
Basically, this code should create a divisible list from 1 to 28. If val is divisible by one of the numbers in the list, thats fine, but if it falls into else, I want to be able to filter out all multiples of that number out of the current list we are looping through.
The next number that wouldn't be divisible would be 3 in this example, so in the else get rid of 6, 9, 12, ... etc.
Your code is fine, but you're just missing the actual code to remove the item. But there is a caveat: You cannot modify a list when you are looping through it using foreach. There are a couple ways to handle that:
Depending on your requirements, maybe just don't add them in the first place. Move your val % d == 0 condition into the for loop that adds the values, and just don't add the values that are divisible by d.
Make a new list (List<int> toRemove) where you keep track of all the values you need to remove. After you're done the foreach loop, loop through your toRemove list and use divisible.Remove(value) to remove those.
Change your foreach to a for loop, which will allow you to use divisible.RemoveAt(i). But you will have to make sure you don't skip a value on the next iteration of the for loop (since removing a value changes the size of the list).
I agree with Gabriel. You cannot alter a underlying enumeration while traversing it with with foreach. The easiest thing to do would be to convert it to a for loop.
Also in the initial population of your list try using the newer way
var divisible = Enumerable.Range(1, val).ToList();
then do
for(int 0 = 1; i < val; i++)
{
if(val % d == 0)
{
// do something
}
else
{
divisible.RemoveAt(i);
}
}
Hi I have been told to "Write code that determines if a value, say “5”, is contained in the array from task 7(a random array) by going backwards through the array starting at the end and comparing the search value with the values in the array. After the search, if the value is found print “The value has been found” otherwise print “The value has not been found”."
I understand the creation of the random array but I am stuck on how to work backwards through it and locate the specific value.
Here is the code so far
class Program
{
static void Main(string[] args)
{
int[] myArray = new int[10];
Random rand = new Random();
for (int i = 0; i < myArray.Length; i++)
{
myArray[i] = rand.Next(19);
}
}
}
}
Use the loop starting from largest to smallest index.
bool found = false;
for (int i = myArray.Length - 1; i >=0 ; i--)
if(myArray[i] == 5)
found = true;
if(found)
{
}
else
{
}
To go backward just use a for loop with the iterator to i--.
for (int i = myArray.Length - 1; i >= 0; i---)
{
if(// Check if myArray[i] equals the value to find)
{
// If it is the case, you can get out from the for loop with break
break;
}
}
The for loop is splitted in 4 parts:
for (initializer; condition; iterator)
body
The initializer is executed before the first iteration in the loop (here you want to start at the last index in the array : myArray.Length - 1)
The condition is evaluated for each iteration, if this condition is true then it goes to 3 (you want to stay in the for loop while i >= 0) otherwise it quit the for loop
The body is executed for each iteration that satisfy the condition
The iterator is executed (here as you want to go backward you want to decrease i)
Then it go back to 2
I am using an int array to hold a long list of integers. For each element of this array I want to check if it is 1, if so do stuff relevant to 1 only, else if it is a 2, do other stuff relevant to 2, and so forth for each value stored in the array. I came up with the code below but it isn't working as expected, is there something I am missing? What is happening is that only the first value of the array is being considered.
int[] variable1 = MyClass1.ArrayWorkings();
foreach (int i in variable1)
{
if (variable1[i] == 1)
{
// arbitrary stuff
}
else if (variable1[i] ==2)
{
//arbitrary stuff
}
}
The i in your foreach loop holds the actual element value from the array in each iteration, not the index. In your particular code sample, your array probably holds only zeroes, which is why you're only getting the first element (you're always using index 0). Hence, you should check i rather than variable1[i].
If you are going to check against various integer constants, a switch expression is more suitable, BTW:
foreach (int i in variable1) {
switch (i) {
case 1:
// arbitrary stuff
break;
case 2:
// arbitrary stuff
break;
}
}
switch/case saves you some writing; if you ever pull your values from anywhere else than from i, you can simply change the (i) part in the switch statement, and moreover, switch might be evaluated by the compiler more efficiently than the chained if-else statements.
Note: You will not be able to directly change array values in the foreach loop, as you cannot assign anything to i. If you need to assign new array values, you'll have to
count yourself with an additional variable while still using foreach or
use another loop such as for and retrieve the item at the current index yourself.
You're trying to do something that doesn't make sense. To see how it works, take a simple example, an array with values: 9, 4, 1.
If you try to run your code on this sample array, you'll get an error:
foreach (int i in variable1)
{
if (variable1[i] == 1) // the item i is 9.
// But variable[i] means, get the value at position #9 in the array
// Since there are only 3 items in the array, you get an Out Of Range Exception
{
// arbitrary stuff
}
{
Instead, this is what you need:
foreach (int i in variable1) // i will be 9, then 4, then 1)
{
if (i == 1)
{
// arbitrary stuff
}
// ... etc
}
The alternative is to use a for loop, which would give you the indices 0, 1, and 2, like this:
for (int i=0 ; i<=variable1.Length ; i++) // i will be 0, 1, 2
// variable[i] will be 9, 4, 1
{
if (variable1[i] == 1)
{
// stuff
}
// ... etc
}
Write like this instead:
foreach (int i in variable1) {
if (i == 1) {
....
The i you fetched is not the index but the value. So check i with 1 or 2.
If you were using for loop then your inner code would have worked perfectly.
int[] variable1 = MyClass1.ArrayWorkings();
foreach (int i in variable1)
{
switch(i)
{
case 1:
// arbitrary stuff
break;
case 2:
//arbitrary stuff
break;
}
}
Try using switch case. Much faster than normal if-else.
I have custom class that implement IEnumerable<int[]> interface and save current Enumerator. When added new element I need set enumerator to last element.
Sample code for set enumerator to end:
IEnumerable<int> seq = ...
seq.Reset();
for (int i = 0; i < seq.Count; i++)
{
seq.MoveNext();
}
How do this faster?
(Can I go to the end can't not scroll all sequence elements?)
if faster means less code (another alternative is),
IEnumerable<int> seq = ...
while (seq.MoveNext())
{
var item = seq.Current;
}
EDIT
you want seq.Last()
It is an extension method and has code similar to above.
EDIT2
i need seq.Current=seq.Last();
your code is similar to
IEnumerable<int> seq = ...
int count=0;
//Following while is equivalent to seq.Count
while (seq.MoveNext())
{
count++;
}
int i=0;
while (i<count)
{
seq.MoveNext();
}
Using IEnumerator only it is not possible to set seq.Current to Last in one iteration as you never know where to stop.
The for statement will iterate from x to y, with a pre-defined increment, like so:
for (`start`; `until`; `increment`)
e.g. If we wanted to loop from 0 to 9, with an increment of 1, we would write
for (int i = 0; i < 10; i++)
If you have an object that implements a next type method, you may want to use a while loop.
while (seq.CurrentItem != null)
{
// do something with the current item and move to next
seq.Next();
}
I would recommend reading up about loops in C#.