How many of the same

Find how many of the same value in an ArrayList

Page 1 of 1

12 Replies - 1747 Views - Last Post: 28 June 2008 - 03:44 AM Rate Topic: -----

#1 djevertrue  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 18-June 08

How many of the same

Post icon  Posted 18 June 2008 - 07:53 PM

Hi all,

I am trying to find the same value in an ArrayList.

For example if the user entered
1
1
1
2
2
3
4
5

I want the output to be like:

There are 3 1's
There are 2 2's
There is 1 3
There is 1 4

and so on.

This is what I have so far. Also I am not worrying about the output as far as "There are" or "There is" yet I just want to count the same values in the array elements.

using System;
using System.Collections;
using System.Text;

namespace Count_How_Many_values
{
	class Program
	{
		static void Main(string[] args)
		{
			// Declare Variables
			int intUserInputNumbers;
			string strContinue;

			ArrayList Numbers = new ArrayList();

			do
			{
			   Console.WriteLine("Please Enter Numbers 0 through 10");
			   intUserInputNumbers = Convert.ToInt32(Console.ReadLine());
			
			   if((intUserInputNumbers > 0) && (intUserInputNumbers < 11))
			   {
					Numbers.Add(intUserInputNumbers);

					Console.WriteLine("Press 'C' to continue");
					strContinue = Console.ReadLine().ToUpper();
				   
			   }
			   else
			   {
					Console.WriteLine("Number was eithier below 0 or bigger then 10");
					Console.WriteLine("");
					Console.WriteLine("Press 'C' to continue");
					strContinue = Console.ReadLine().ToUpper();
			   }
			} while (strContinue == "C");

			Console.Write("There are {0} ", Numbers.Count);
			Console.WriteLine("numbers in our array");

			Numbers.Sort();


			DisplayArray(Numbers);
			
		}

		static void DisplayArray(ArrayList Numbers)
		{
			int intCounter;
			int HowManyTimes;

			for (intCounter = 0; intCounter < Numbers.Count; intCounter++)
				
				  
				Console.WriteLine(Numbers[intCounter]);
				Console.WriteLine("");
				

		}
	}
}



Now I know I need to use 2 for loops in the DisplayArray Method
to do this. I need to find the value , count it and then flag it as already counted, but I have no idea how to do this.

Can anyone help me out?

Thanks in advance

Is This A Good Question/Topic? 0
  • +

Replies To: How many of the same

#2 OliveOyl3471  Icon User is offline

  • Everybody's crazy but me!
  • member icon

Reputation: 134
  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Re: How many of the same

Posted 19 June 2008 - 06:00 PM

Hi.
I'm kinda new at this. I haven't figured out how to count the number of times each number appears in the array, but
this code will find your numbers for you. If there are any 4's, or if there are hundreds of 4's, it will display "there is a 4..."
etc. You can continue your sentence without adding another Console.Write command.

Maybe if you know how to find the values, you can figure out how to count up the number of times each one occurs in the array.
I included some of your code so you will know where I added this.

            Numbers.Sort();

            CountNums(Numbers);

            DisplayArray(Numbers);
            Console.ReadLine();//pause so we can read output   
        }
        public static void CountNums(ArrayList Numbers)
        {
            for(int x=0; x<10;x++)
            {    
                if(Numbers.Contains(x))
                {
                Console.WriteLine("There is a {0} in our array.",x);
                }
                         
            }                  

        }
        static void DisplayArray(ArrayList Numbers)



I also tried if (Numbers[i].Equals(x))

That way you will have both i and x to display your counts, when you figure out how to count them.
Something like this:
Console.WriteLine("There are {0} {1}'s in the array.", i, x);

You might also try a foreach, to loop through your array, instead of a for loop:

foreach(int x in Numbers)

When you find the answer please post it, as I would like to know! :D

edit--didn't need to quote you, lol

This post has been edited by OliveOyl3471: 19 June 2008 - 06:06 PM

Was This Post Helpful? 0
  • +
  • -

#3 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5943
  • View blog
  • Posts: 12,871
  • Joined: 16-October 07

Re: How many of the same

Posted 19 June 2008 - 06:21 PM

I wouldn't bother with an array, actually. You want a dictionary. A dictionary has a unique key and an associated value. In this case, the key is the number and the value is the count. Each time a value is entered, you check to see if the key is in your dictionary. If it is, just increment the count. If not, add it with a count of 1.
Was This Post Helpful? 0
  • +
  • -

#4 OliveOyl3471  Icon User is offline

  • Everybody's crazy but me!
  • member icon

Reputation: 134
  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Re: How many of the same

Posted 19 June 2008 - 07:37 PM

View Postbaavgai, on 19 Jun, 2008 - 08:21 PM, said:

I wouldn't bother with an array, actually. You want a dictionary. A dictionary has a unique key and an associated value. In this case, the key is the number and the value is the count. Each time a value is entered, you check to see if the key is in your dictionary. If it is, just increment the count. If not, add it with a count of 1.


Do you mean that it can't be done with an array, or it shouldn't be done with an array?

This post has been edited by OliveOyl3471: 19 June 2008 - 08:19 PM

Was This Post Helpful? 0
  • +
  • -

#5 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5943
  • View blog
  • Posts: 12,871
  • Joined: 16-October 07

Re: How many of the same

Posted 20 June 2008 - 05:35 AM

View PostOliveOyl3471, on 19 Jun, 2008 - 10:37 PM, said:

Do you mean that it can't be done with an array, or it shouldn't be done with an array?


Appologies. Looking back at the problem, it's a closed set. "Please Enter Numbers 0 through 10" In this case, not only is an array possible, but preferable.

The solution would be to create an array, not an array list. e.g.
int[] count = new int[11];
for (int i = 0; i < count.Length; i++) { count[i] = 0; }



After that, each entry is an increment, e.g. count[intUserInputNumbers]++;.

The previous method I offered is for when the extent of the set is unknown, which is usually the case in the real world.
Was This Post Helpful? 0
  • +
  • -

#6 OliveOyl3471  Icon User is offline

  • Everybody's crazy but me!
  • member icon

Reputation: 134
  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Re: How many of the same

Posted 23 June 2008 - 09:27 AM

View Postbaavgai, on 20 Jun, 2008 - 07:35 AM, said:

Appologies. Looking back at the problem, it's a closed set. "Please Enter Numbers 0 through 10" In this case, not only is an array possible, but preferable.

The solution would be to create an array, not an array list. e.g.
int[] count = new int[11];
for (int i = 0; i < count.Length; i++) { count[i] = 0; }



After that, each entry is an increment, e.g. count[intUserInputNumbers]++;.

The previous method I offered is for when the extent of the set is unknown, which is usually the case in the real world.


I didn't want to hijack this thread, but apparently the OP aint coming back.

You wouldn't actually use this type of problem very much, huh?

Can you give an example of the proper way to use a dictionary?

(Or a link to anywhere that shows how to do it)

Please. :)
Was This Post Helpful? 0
  • +
  • -

#8 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5943
  • View blog
  • Posts: 12,871
  • Joined: 16-October 07

Re: How many of the same

Posted 23 June 2008 - 01:54 PM

View PostOliveOyl3471, on 23 Jun, 2008 - 12:27 PM, said:

Can you give an example of the proper way to use a dictionary?


Sure, why not? :)

Most times, when you want to find or count duplicates in a list, there is no known limit to the set size. For example, number of distinct titles used in an employee list, last names, salaries, etc. You ask this question all the time of RDBMS' where you'd do something like [li]select name, count(*) from table group by name[/li]. However, if you don't happen to have your list in a databse, C# is fun too.


The basic form is this:
// create a dictionary, the key is the item type, the value is int
Dictionary<int, int> dict = new Dictionary<int, int>();

// loop through the list
foreach (int item in list) {
	if (dict.ContainsKey(item)) {
		// if we have the key, increment by one
		dict[item]++;
	 } else {
		// otherwise, add it to the list, with a count of one
		dict.Add(item, 1);
	 }
}




Here's a program showing it in action.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;

namespace ConsoleApplication1 {
    class Program {
        Dictionary<int, int> GetCount(int[] list) {
            // create a dictionary, the key is the item type, the value is int
            Dictionary<int, int> dict = new Dictionary<int, int>();

            // loop through the list
            foreach (int item in list) {
                if (dict.ContainsKey(item)) {
                    // if we have the key, increment by one
                    dict[item]++;
                } else {
                    // other wise, add it to the list, with a count of one
                    dict.Add(item, 1);
                }
            }
            return dict;
        }


        int [] GenerateRandomList(int size, int range) {
            Random rnd = new Random();
            int[] list = new int[size];
            for (int i = 0; i < size; i++) {
                list[i] = rnd.Next(range);
            }
            return list;
        }

        void DumpList(int[] list) {
            foreach (int item in list) {
                Debug.Write(item + " ");
            }
            Debug.WriteLine("");
        }


        void ShowCounts(Dictionary<int, int> dict) {
            // order our keys
            // ordered lists make people happy
            int [] keys = new int[dict.Keys.Count];
            dict.Keys.CopyTo(keys, 0);
            Array.Sort(keys);

            // display results
            foreach (int item in keys) {
                int count = dict[item];
                Debug.WriteLine(item + " : " + count + " item" + ((count>1) ? "s":""));
            }
        }

        public void RunTest(int size, int range) {
            int[] list = GenerateRandomList(size, range);
            DumpList(list);
            Dictionary<int, int> counts = GetCount(list);
            ShowCounts(counts);
        }


        static void Main(string[] args) {
            new Program().RunTest(100, 20);
        }
    }
}



Enjoy.
Was This Post Helpful? 1
  • +
  • -

#9 OliveOyl3471  Icon User is offline

  • Everybody's crazy but me!
  • member icon

Reputation: 134
  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Re: How many of the same

Posted 24 June 2008 - 08:21 PM

If I understand it correctly, this program should:

1. Create an array called list, populate it with a list of 100 random numbers between one and twenty
2. Print each number in the list, in whatever order they appear, each on a separate line
3. Create a dictionary to hold each number in the list and how many of each
4. Loop through list, counting up how many of each number is in the list and adding to the dictionary
5. Put the keys (each key will be a number in the list) in numeric order by
copying them to an array called keys and sorting them. We don't know how many of
these there will be, since we don't know how many times each number occurs in the list
6. print each key and how many of each appears in our list, in this format (if there are three 2's in the list):

2 : 3 2s



Is that right?

Is a dictionary like a two dimensional array? Or like parallel arrays? Please forgive my
ignorance, but I had never heard of a dictionary (in programming) until you mentioned it.

I like this program because it's versatile. If I am not mistaken, you could put any numbers in RunTest();
and it would work.

Except that it doesn't. Not for me, anyway. The result is simply a blank screen. It generates no errors, though.
I added Console.ReadLine(); in order to see the screen, but the program doesn't appear to do anything.

Any idea why?

The code looks like it should run perfectly.
But what do I know?
Was This Post Helpful? 0
  • +
  • -

#10 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5943
  • View blog
  • Posts: 12,871
  • Joined: 16-October 07

Re: How many of the same

Posted 25 June 2008 - 04:51 AM

View PostOliveOyl3471, on 24 Jun, 2008 - 11:21 PM, said:

If I understand it correctly, this program should...


OMG, questions! :P Rather than using a ton of bulky quote blocks, I'll just condence this response:

> 1. Create an array called list, populate it with a list of 100 random numbers between one and twenty
Yep.

> 2. Print each number in the list, in whatever order they appear, each on a separate line
Sort of. All on the same line, with a new line at the end. Write as opposted to WriteLine.

> 3. Create a dictionary to hold each number in the list and how many of each
Yes.

> 4. Loop through list, counting up how many of each number is in the list and adding to the dictionary
Sort of. We're not quite counting and adding. Rather, we're checking for existence, incrementing our count by one if found, or adding a new entry with a value of one if not.

> 5. Put the keys (each key will be a number in the list) in numeric order by
> copying them to an array called keys and sorting them. We don't know how many of
> these there will be, since we don't know how many times each number occurs in the list
At this point, our counting is done. We have filled dictionary object, so we know how many keys we have. You could actually sort by count, but that's a little tricky and probably confusing. Sorting here is just to make pretty output.

6. print each key and how many of each appears in our list, in this format (if there are three 2's in the list):
> Yes.



> Is a dictionary like a two dimensional array?
Not really, though it can almost be. Think of it as a normal array of an object type that contains two values...

It is a form of HashTable, though the name dictionary makes a little more sense, depending on how you look at it. It's composed of Keys and Values. The Key is unique, the Value is just the data associated with the Key. It's called a dictionary because if you have a single value, a term, you can look it up in a large collection of information and find only what's associated with that term; like in Webster's. For hashtable, the key is thought of as a "hash" value, but it's the same idea.

In practice, it's an array of key-value pairs, where the key is unique in the array. Because of this, methods like dict[key] and dict.ContainsKey(key) make sense.

> If I am not mistaken, you could put any numbers in RunTest(); and it would work.
With little change, you can have this count anything. The number of words occorances, for example, is just Dictionary<string, int> and string[]. I thought about writing a completely generic version of this, but it could have been extra confusing. Random numbers are the easiest seed data in the world, so it was a good place to start.

> The result is simply a blank screen. ... Any idea why?
LOL, sorry, my bad. All the output is handled in Diagnostics. That is, it's printed directly to the Output window in the Visual Studio enviroment. As you noted, for a console app you need to add a Console.ReadLine(); to see what's going on. You then have to hit enter, which I find a bother. The Debug writer sends output to where I can find it when the program stops running, so I usually use that. Plus, it's what you use in GUI programs to track changes. Everywhere you see Debug. change it to Console. and see how far you get.

Hope this helps.
Was This Post Helpful? 0
  • +
  • -

#11 OliveOyl3471  Icon User is offline

  • Everybody's crazy but me!
  • member icon

Reputation: 134
  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Re: How many of the same

Posted 25 June 2008 - 07:40 AM

View Postbaavgai, on 25 Jun, 2008 - 06:51 AM, said:

Hope this helps.


Of course it helps. :)

I was just waking up and the thought occurred to me, "Change Debug to Console, Dummy."

:P

edit--The range apparently is 0 to 19, not 1 to 20. I was wrong about the format, too. It's:

9 : 3 items

This post has been edited by OliveOyl3471: 25 June 2008 - 07:45 AM

Was This Post Helpful? 0
  • +
  • -

#12 OliveOyl3471  Icon User is offline

  • Everybody's crazy but me!
  • member icon

Reputation: 134
  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Re: How many of the same

Posted 25 June 2008 - 07:55 AM

View Postbaavgai, on 25 Jun, 2008 - 06:51 AM, said:

a normal array of an object type that contains two values...


Are there always two values, or can there be more?

edit--Upon rereading...duh. You already answered that. "it's an array of key-value pairs"

This post has been edited by OliveOyl3471: 25 June 2008 - 11:02 AM

Was This Post Helpful? 0
  • +
  • -

#13 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5943
  • View blog
  • Posts: 12,871
  • Joined: 16-October 07

Re: How many of the same

Posted 25 June 2008 - 10:10 AM

View PostOliveOyl3471, on 25 Jun, 2008 - 10:55 AM, said:

Are there always two values, or can there be more?


Keep in mind, those values can be anything. All objects implement equality, so a key can be anything. Your value could be a string, an array, another dictionary, whatever. Value pairs are so useful that they are actually a fundamental feature in some languages. Another name for dictionary, tough it may not enforce uniqueness, is associate array. The key value pair is a form of categorical monad and with enough of them, and the right associations, there's nothing that can't be described.
Was This Post Helpful? 0
  • +
  • -

#14 Footsie  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 24
  • View blog
  • Posts: 370
  • Joined: 20-September 07

Re: How many of the same

Posted 28 June 2008 - 03:44 AM

baavgai and OliveOyl -
Thanks for the input into this thread/problem.
I've followed through it myself and learned a lot from it.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1