I have six different arrays each with the same amount of elements in them, my question is, if I want to view the line that says 'test' and it happens to be the 22nd line, is there a way so that I can view the 22nd of all the arrays at the same time and then print them to the console, is it possible to do that?
e.g. I want to search through one array and then when it finds 'test' it prints out the same index of all arrays, including the one which 'test' was contained in.
Could a Binary Search be used here?
Thanks.
Yes you can.
Simply iterate through the first array until you find the string you are looking for, then use the counter to access the remaining arrays. Your code should look something like this:
for (int counter = 0; counter < Array1.Length; counter++)
{
if (Array1[counter] == "your string here")
{
//Print same line on remaining arrays, eg:
Console.WriteLine(Array2[counter]);
Console.WriteLine(Array3[counter]);
//Then you can break out of the loop
break;
}
}
If those are arrays, i can't see any problem doing this:
string[] array1, array2, array3..// etc
...
var stringToSearch = "someValue";
...
int matchPosition = Array.IndexOf(array1, stringToSearch);
if(matchPosition != -1)
{
// just sample of usage - access string by array2[matchPosition]
Console.WriteLine(array2[matchPosition]);
Console.WriteLine(array3[matchPosition]);
}
Related
I am taking a class in c# programming and cannot figure out how to do the following. I have spent hours researching and nobody else seems to have the same issues.
The question is:
Write a function named, evenOrOdd, that will accept three parameters. The first parameter is the integer array used in the above function. The second parameter is the string array from step 2 and the third parameter is an integer indicating the size of the two arrays. This function will perform the following tasks:
This function will loop through the first array, checking each value to see if it is even or odd.
For each item in the integer array, the function will then place the appropriate value, “even” or “odd”, in the corresponding position of the string array.
Hint: Using the modulus operator, (also called the modulo), to divide the number by 2 will result in either a remainder of 0 or 1. A remainder of 0 indicates an even number and a remainder of 1 indicates an odd number. The modulus operator for all of the languages in this class is %.
After calling both functions, print the maximum number determined by findMax as well as the array index position of the largest number. Next, the program will loop through the two arrays and print the integer from integer array followed by the corresponding “even” or “odd” value from the string array
I do not understand how to populate the second string array with "even" or "odd".
The two arrays should be something like this:
array1 [1,2,3,4,5,6,7,8,9,10]
then run through a loop to determine if the values are even or odd and then assign the values to the second array so it is something like this:
array2 [odd,even,odd,even,odd,even,odd,even,odd,even]
I am confused how I "link" these two arrays together so that it know index of array 1=index of array 2.
You don't have to "link" the arrays together. You can use a variable which contains the current index and use it for both arrays. Like this:
for (int i = 0; i < array1.Length; i++){
//array1[i]...
//array2[i] = ...
}
This way, you can check if the number at index i in array 1 is even or odd and then modify the index i of array 2 accordingly.
Instead of array1.Length, you can also use the third argument of the method.
It looks like a code challenge. I highly recommend you find your own way to understand and solve this kind of problem and the fundamental concepts behind it as well.
One way to code the EvenOrOdd method:
public void EvenOrOdd(int[] numbers,
string[] natures, int size)
{
for(int i=0; i < size; i++)
if(numbers[i] % 2 == 0)
natures[i] = "even";
else
natures[i] = "odd";
}
One wat to code FindMax Function:
public static (int MaxValue, int MaxIndex) FindMax(int[] numbers)
{
int major = int.MinValue;
int majorIndex = -1;
for(int i=0; i < numbers.Length; i++)
if(numbers[i] > major)
{
major = numbers[i];
majorIndex = i;
}
return (major, majorIndex);
}
Check it in dotnetFiddle
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 have a multi-dimensional array in a text file:
a,1,2,3
b,4,5,6
c,7,8,9
d,10,11,12
I want to input one of the numbers, search the array, and display the corresponding letter for the row the number appears in.
Any help would be greatly appreciated.
Edit:
I have a csv file containing the information given above.
So far I have:
1. Created an array to store the read all the lines in the file
2. Created a second array to store the final array values
3. Created a third array to store the line splits at , and place values back into second array.
This is the code:
string[] as_FirstArray = System.IO.File.ReadAllLines("PartNumbersFile.csv");
string[,] as_SecondArray = new string[4, as_FirstArray.Length];
string[] as_ThirdArray;
string s_Input = Console.ReadLine();
for (int i_Count1 = 0; i_Count1 < as_FirstArray.Length; i_Count1++)
{
as_ThirdArray = as_FirstArray[i_Count1].Split(',');
as_SecondArray[0, i_Count1] = as_ThirdArray[0];
as_SecondArray[1, i_Count1] = as_ThirdArray[1];
as_SecondArray[2, i_Count1] = as_ThirdArray[2];
as_SecondArray[3, i_Count1] = as_ThirdArray[3];
}
And now I'm totally stuck. I have been told that, from here, I need to:
1. use a for loop on as_SecondArray index[1] from first row to last row.
2. use an if statement to determine if userinput is found in index[1] and, if so, store the loop count number. (Here, if no match is found, I will repeat for index[2] and again, if no match found, repeat for index[3].)
3. use another for loop and if statement on index[0] to match the count number from the found match, and display the corresponding entry. (I can do this step but that's hopeless without knowing how to do steps 1 and 2.)
I don't how to specify a particular index as the loop target. Or where I place the loop in relation to the loop I already have - inside it or not.
Edit:
THANK YOU TO WHOEVER EDITED MY POST AND I HAVE NOW DELETED MY ANSWER :-)
After A LOT more time I have made a little progress. I have figured out how to loop a particular index and identify if userinput is found in that index:
for (int i_Count2 = 0; i_Count2 < as_SecondArray.GetLength(1); i_Count2++)
{
for (int i_Count3 = 0; i_Count3 < as_SecondArray.GetLength(0); i_Count3++)
{
if (as_SecondArray[1, i_Count3].Equals(s_Input))
{
s_Found = as_SecondArray[1, i_Count3];
}
else { lblOutput.Text = "not found"; }
}
}
But I am stuck at how to retrieve the i_Count3 loop number.
Don't create multidimensional array instead create a Dictionary or Hashtable where key will be the number and value will be the letter. Now you can easily search the number and find associated letter with the search time of O(1).
I'm trying to find, in an array of strings, which one starts with a particular substring. One of the strings in the array is guaranteed to start with the particular substring.
I tried to use:
int index = Array.BinarySearch (lines, "^"+subString);
Where lines is the array of strings and I'm looking for the index of the array that starts with subString. However, I'm either using regex improperly or there's a much better way to go about this?
BinarySearch can be used only to find a complete string, so you cannot use it for a substring match. You also have to ensure that the array is ordered in the first place to use BinarySearch.
You can use Array.FindIndex:
int index = Array.FindIndex(lines, line => line.TrimStart().StartsWith(subString));
Do you need to find the index of the (first) occurence, or do you need to find the actual strings that match that criterium?
myString.StartsWith(myPrefix); //returns bool
That should do the trick. Or a little more verbose:
var matchedLines = lines.Where(line => line.StartsWith(substring)).ToList();
If you need the index of the first occurence, I'd address it as an array:
var firstOccurence = String.Empty;
var firstOccurenceIndex = -1;
for(int i = 0; i < lines.Length; i++)
{
if(lines[i].StartsWith(substring))
{
firstOccurence = lines[i];
firstOccurenceIndex = i;
break;
}
}
Note: you don't HAVE to use an array. It could just as well have been done with a foreach, manual counter incrementor and a break statement. I just prefer to work with arrays if I'm looking for an index.
Yet, another solution:
int index = lines.ToList().FindIndex(line => line.TrimStart().StartsWith(subString));
Let's say I know how many numbers will user put in. I have an int array and I want to fill it with integers user put in devided by particular character, for example space. I managed to solve it this way.
int[] numbers = new int[5];
string[] input = Console.ReadLine().Split(' ');
for (int i = 0; i < numbers.Length; ++i)
numbers[i] = int.Parse(input[i]);
I want to ask you, is there any other, better way to do this?
You could use Linq:
var numbers = Console.ReadLine().Split(' ').Select(token => int.Parse(token));
// if you must have it as an array...
int[] arr = numbers.ToArray();
This basically does the same thing as your code, it's just more concise.
You could also make your code more robust by handling cases where the user inputs something that's not a number (which would cause int.Parse() to throw an exception).
Suggestion 1: if you would like to read all values from single line delimited by space, then i would suggest you to use command line arguments. so that you can atleast avoid using String array in your program as command line arguments are stored into the Main() method String array argument.
Suggestion 2: while parsing the values into Int it would be nice to check wether parsing is successfull or not, so that if the parsing failes(due to invalid integer) then we can store zero or some default value.
Int32.TryParse() allows you to let you know wether parsing is sucessfull or not.
Try This:
static void Main(string[] args)
{
int[] numbers = new int[args.Length];
int temp;
for(int i=0;i<args.Length;i++)
{
if (Int32.TryParse(args[i],out temp))
{
numbers[i] = temp;
}
else
{
numbers[i] = 0;
}
}
}
Let me try, just read console line and split by space. use ConvertAll method fro Array class.
int[] myArray = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
Even though the return value from Console.Read() returns an integer, it isn't quite that simple. It will return the integer representation of the characters you type in.
In order to retrieve the number of elements, as your code attempts to do. You should refactor a small portion into this:
Console.WriteLine("enter no of elements");
c = int.Parse(Console.ReadLine());
Please note that this piece of code can throw exceptions if what you type in isn't a number
You can use StringTokenizer to tokenize the whole line and then use parseInt().