Pulling info from arrays
-
I'm new at this and am having a problem. I have a one dimensional array with a group of fields filled and need to extract the information in them and list how many times they were used. :confused: Example 1: int[] numbers = new int[30] {1, 3, 5, 2, 4, 6, 6, 4, 9, 1, 5, 5, 3} I need to be able to do the following: Numb // Amount used: // used: 1 // 2 2 // 1 3 // 2 4 // 2 5 // 3 6 // 2 9 // 1 Can anyone point me in the right direction for the information on how to do this. Any and All help will be appreciated. :) :rose:
-
I'm new at this and am having a problem. I have a one dimensional array with a group of fields filled and need to extract the information in them and list how many times they were used. :confused: Example 1: int[] numbers = new int[30] {1, 3, 5, 2, 4, 6, 6, 4, 9, 1, 5, 5, 3} I need to be able to do the following: Numb // Amount used: // used: 1 // 2 2 // 1 3 // 2 4 // 2 5 // 3 6 // 2 9 // 1 Can anyone point me in the right direction for the information on how to do this. Any and All help will be appreciated. :) :rose:
OK, I guess the way to do this, is to use for each to step over your array, and set up a counter for each number you want to track. There are a few ways of doing this, they would include: create a new array that has the number of elements equal to the highest number in your list, it's an array of numbers, and you set them to 0, and for example, if you find the number 5, you set newArray[5] to be one greater than it was. Create a struct like this struct numbers { int value; int times; } Then, you create an array of these structs and you find the right one to increment times by. ( the next one is the best ) Dictionary<int, int> times = new Dictionary<int, int>(); // A dictionary is an associative array, we are using numbers, but we can store anything foreach(int n in numbers) { if (!times.KeyExists(n)) { // Add a key to the dictionary times[n] = 0; } ++times[n]; } Then you can iterate over the keys and use the values to see how many times each one exists. I suspect this is homework. If it is, then you should do some reading on how the dictionary container works, so you fully understand it. Otherwise, you won't be able to turn the above into code that fully works, nor will you be able to withstand the scrutiny of your teacher when she asks why you did it this way. -- modified at 18:59 Monday 2nd April, 2007
Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )