Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Making a count of unique elements in an array

Making a count of unique elements in an array

Scheduled Pinned Locked Moved C#
data-structures
7 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T Offline
    T Offline
    TrooperIronMan
    wrote on last edited by
    #1

    For given array of objects, I need to produce a another list or two-dimensional resulting array or something where each pair of values consists of a one unique element from the original array and the number of times that element appears in original array. Tried google, but as usual... of about 100 results none is even close to what I need. I know this is trivial... but again... I'm trying it for 3 hours and no solution...

    L 1 Reply Last reply
    0
    • T TrooperIronMan

      For given array of objects, I need to produce a another list or two-dimensional resulting array or something where each pair of values consists of a one unique element from the original array and the number of times that element appears in original array. Tried google, but as usual... of about 100 results none is even close to what I need. I know this is trivial... but again... I'm trying it for 3 hours and no solution...

      L Offline
      L Offline
      Luc Pattyn
      wrote on last edited by
      #2

      Hi, you could create an empty hash table and enumerate your collection: - use your item as a key - first test if the key already exists in the hash table - if not, add a (key,value) pair with value=1 - if yes, modify the entry with that key to become (key, old value + 1) Et voila. :)

      Luc Pattyn

      T 1 Reply Last reply
      0
      • L Luc Pattyn

        Hi, you could create an empty hash table and enumerate your collection: - use your item as a key - first test if the key already exists in the hash table - if not, add a (key,value) pair with value=1 - if yes, modify the entry with that key to become (key, old value + 1) Et voila. :)

        Luc Pattyn

        T Offline
        T Offline
        TrooperIronMan
        wrote on last edited by
        #3

        Great, got some solution on my own finally... though this sound better... I'll post mine in a so you can laugh bit... :D ;P but it does work... class Program { static void Main(string[] args) { ArrayList ResultList = new ArrayList(); int[] repeatCount = new int[5]; object[] originalObjectArray = new object[5]; Console.WriteLine("Enter array"); for (int i = 0; i < 5; i++) originalObjectArray[i] = Console.ReadLine(); ResultList.Add(originalObjectArray[0]); repeatCount[0] = 1; int passCount = 0; foreach (object o in originalObjectArray) { if (passCount > 0) { bool upis = true; for (int i = 0; i < ResultList.Count; i++) { if (ResultList[i].Equals(o)) { repeatCount[i] += 1; upis = false; } } if (upis == true) { ResultList.Add(o); repeatCount[ResultList.Count - 1] = 1; } } passCount++; } for (int l = 0; l BTW how do I test if key is already in Hashtable?

        L G 2 Replies Last reply
        0
        • T TrooperIronMan

          Great, got some solution on my own finally... though this sound better... I'll post mine in a so you can laugh bit... :D ;P but it does work... class Program { static void Main(string[] args) { ArrayList ResultList = new ArrayList(); int[] repeatCount = new int[5]; object[] originalObjectArray = new object[5]; Console.WriteLine("Enter array"); for (int i = 0; i < 5; i++) originalObjectArray[i] = Console.ReadLine(); ResultList.Add(originalObjectArray[0]); repeatCount[0] = 1; int passCount = 0; foreach (object o in originalObjectArray) { if (passCount > 0) { bool upis = true; for (int i = 0; i < ResultList.Count; i++) { if (ResultList[i].Equals(o)) { repeatCount[i] += 1; upis = false; } } if (upis == true) { ResultList.Add(o); repeatCount[ResultList.Count - 1] = 1; } } passCount++; } for (int l = 0; l BTW how do I test if key is already in Hashtable?

          L Offline
          L Offline
          Luc Pattyn
          wrote on last edited by
          #4

          Hi, I did not laugh, but I was amazed about the complexity you introduced. Will you ever feel sure this is correct ?? Some detailed remarks: 1) your code can handle no more than 5 objects, there is no need for such a limitation 2) I did not like the name "o" for one of the objects; I avoid single-character names except maybe for local int counters; for real objects, I use real names. 3) you did the first object outside the for loop, then needed extra stuff (passcount>0) to skip it inside the loop; better do everything inside the loop But in the end, you followed the approach I suggested. Did you realize you are relying on the fact that ArrayList preserves the order of the elements added (unless you instruct it otherwise, e.g. Sort) ? When using a hashtable, you dont need such assumption: it is intended to keep key,value pairs together (as opposed to your code trying to keep an ArrayList and an int array in the same order). The test you need is Hashtable.Contains() May I suggest you take some time to read up on collections (mainly ArrayList and Hashtable). They are powerful tools that can be applied on many occasions, requiring less code (and hence offering less room for bugs). Regards.

          Luc Pattyn

          T 1 Reply Last reply
          0
          • T TrooperIronMan

            Great, got some solution on my own finally... though this sound better... I'll post mine in a so you can laugh bit... :D ;P but it does work... class Program { static void Main(string[] args) { ArrayList ResultList = new ArrayList(); int[] repeatCount = new int[5]; object[] originalObjectArray = new object[5]; Console.WriteLine("Enter array"); for (int i = 0; i < 5; i++) originalObjectArray[i] = Console.ReadLine(); ResultList.Add(originalObjectArray[0]); repeatCount[0] = 1; int passCount = 0; foreach (object o in originalObjectArray) { if (passCount > 0) { bool upis = true; for (int i = 0; i < ResultList.Count; i++) { if (ResultList[i].Equals(o)) { repeatCount[i] += 1; upis = false; } } if (upis == true) { ResultList.Add(o); repeatCount[ResultList.Count - 1] = 1; } } passCount++; } for (int l = 0; l BTW how do I test if key is already in Hashtable?

            G Offline
            G Offline
            Guffa
            wrote on last edited by
            #5

            I like generics. :)

            Dictionary<string, int> words = new Dictionary<string, int>();
            string word;
            while ((word = Console.ReadLine()).Length > 0) {
            if (words.ContainsKey(word) {
            words[word] = words[word] + 1;
            } else {
            words.Add(word, 1);
            }
            }
            foreach (KeyValuePair<string, int> pair in words) {
            Console.WriteLine(pair.Key + " : " + pair.Value.ToString());
            }

            --- single minded; short sighted; long gone;

            T 1 Reply Last reply
            0
            • L Luc Pattyn

              Hi, I did not laugh, but I was amazed about the complexity you introduced. Will you ever feel sure this is correct ?? Some detailed remarks: 1) your code can handle no more than 5 objects, there is no need for such a limitation 2) I did not like the name "o" for one of the objects; I avoid single-character names except maybe for local int counters; for real objects, I use real names. 3) you did the first object outside the for loop, then needed extra stuff (passcount>0) to skip it inside the loop; better do everything inside the loop But in the end, you followed the approach I suggested. Did you realize you are relying on the fact that ArrayList preserves the order of the elements added (unless you instruct it otherwise, e.g. Sort) ? When using a hashtable, you dont need such assumption: it is intended to keep key,value pairs together (as opposed to your code trying to keep an ArrayList and an int array in the same order). The test you need is Hashtable.Contains() May I suggest you take some time to read up on collections (mainly ArrayList and Hashtable). They are powerful tools that can be applied on many occasions, requiring less code (and hence offering less room for bugs). Regards.

              Luc Pattyn

              T Offline
              T Offline
              TrooperIronMan
              wrote on last edited by
              #6

              I was aware I can only take 5 elements... indeed it was only prototype I built before you gave me idea I should use hashtable... regular usage of this wouldn't be user input 5 strings from console... nor it should be in main at first place... it should be method... probably in separate class that is given array as argument... and it return (Hashtable) which contain unique elements and their count... My first try before Hashtable was actually 2 dimensional object array... but was tired of casting int in and out for count every time... so I switched to int array+arraylist... don't know which solution is more complex. I'll redo my code now with hash table... I know about conventions to never give single letter variable names... didn't do it on purpose... and would certainly rename this later if I was happy with approach... I already had bunch of commented code so it was mess... I always first comment things out I don't like... then move them beyond last } and only delete them after I have final release fully debugged... Sure I got some good read on generics so I hope that will give me some idea... Thanks guys for help, this was actually one of questions I had to solve on my job interview-test yesterday... other questions were more like this... combined with ADO.NET, few SQL only... and some .Net stuff.... like, what is base class in net... and such stuff... I messed up this one that is sure... ;P

              1 Reply Last reply
              0
              • G Guffa

                I like generics. :)

                Dictionary<string, int> words = new Dictionary<string, int>();
                string word;
                while ((word = Console.ReadLine()).Length > 0) {
                if (words.ContainsKey(word) {
                words[word] = words[word] + 1;
                } else {
                words.Add(word, 1);
                }
                }
                foreach (KeyValuePair<string, int> pair in words) {
                Console.WriteLine(pair.Key + " : " + pair.Value.ToString());
                }

                --- single minded; short sighted; long gone;

                T Offline
                T Offline
                TrooperIronMan
                wrote on last edited by
                #7

                Got it... public Dictionary GetUniqueElementCollection(object[] PassedArray) { Dictionary ResultList = new Dictionary(); foreach (object origObject in PassedArray) { bool exist = false; foreach (KeyValuePair obj in ResultList) { if (obj.Key.Equals(origObject)) exist = true; } if (exist) { ResultList[origObject] += 1; } else { ResultList.Add(origObject, 1); } } return ResultList; } what do you think guys?

                1 Reply Last reply
                0
                Reply
                • Reply as topic
                Log in to reply
                • Oldest to Newest
                • Newest to Oldest
                • Most Votes


                • Login

                • Don't have an account? Register

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • World
                • Users
                • Groups