• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Comparing Integers in Array

 
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
lets say we have
int[] c = new int[5];

this is later filled with 5 different values from 2 to 14 (repetition is allowed)

I need a way to find out how many numbers are repeated and how many times this number is repeated.

lets say the array was { 3 , 12 , 3 , 3 , 12 }
3 is repeated 3 times
12 is repeated 2 times

what is a good method for doing this?
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
'good' depends on many things... how big will the real array be? what is the range of the expected values?

one way might be a map that uses the value as the key. each time you read a value, like '3', you check to see if that key/value is defined. if so, you increment the value. If not, you create it with a value of 1.

when you're done, you get a list of all the keys, and use that to get the counts.

if your range is sufficiently small, you could just define an int array of say (from your example) 15. Then, as you read each value, increment the int at that index by 1.

'good' is a balance between speed, readability, maintainability, and ease of programming.
 
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
this sounds like a programming exercise ... hints:

The trivial solution uses two nested for loops and runs in o(n�) - avoiding dupliacte output will take an additional data structure, eg a second array or a set.

The half-trivial solution involves sorting and runs in o(n*log(n)).

The nifty solution involves a HashMap and runs in linear time.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic