Page 1 of 2 12 LastLast
Results 1 to 20 of 32
Like Tree2Likes

Thread: Printing repeating integers in an array problem!

  1. #1
    andrewk1978 is offline Member
    Join Date
    Aug 2012
    Posts
    8
    Rep Power
    0

    Default Printing repeating integers in an array problem!

    Hey guys,
    Im very new to java so please forgive my noobishness!
    I have a problem where i have to write some code to read through an int array and print out the different integers and how many times they occur. For example:

    if the array contained the numbers 1,4,2,3,5,4,4,7,5,4,3,6,8,6,4,

    i would need the print to appear something like this


    integer: 1, times: 1
    integer: 4, times: 5
    integer: 2, times: 1
    etc
    as the array is read sequentialy from element 0 to the end. the program should find the integer value in the first element (increment a counter by 1) and then search all other elements to see if the integer reoccurs (counter++ for each time it reappears). obviously the counter would be the 'times' value in the second column.

    My problem is i can get this accomplished yet i cant get the program to recognise when it has already registered an integer in a previous element and skip to the next element looking for a new integer. SO for each element in the array it prints the integer and then searches the entire array for the integer again and increments the counter accordingly. so in essence there is a line printed for each integer the number of times it actually occurs.

    I simply wish to have my code to find an integer and the number of times it occurs. and then disregard the elements it has registered the previous integer in.

    Also, keep in mind that i am NOT permitted to use any new data structures/arrays for storing/remembering values. I can only use int and double variables throughout.

    what i have so far is this: with the array being customerID[] :

    Java Code:
    int num;
    int counter;
    
    for(int count = 0; count < customerID.length; count++)
    {
        counter = 0;
        num = customerID[count];
      
        for(int count2 = 0; count2 < customerID.length; count2++)
          {
        
        	if(num == customerID[count2])
        	    {
        	     counter++;
        	    }
          }
        System.out.println("Integer: " + num + ", Times: " + counter);
        
    }
    The output for the int array 1,1,3,0,3,2,0,4,1,3, looks something like this:

    Integer: 1, Times: 3
    Integer: 1, Times: 3
    Integer: 3, Times: 3
    Integer: 0, Times: 2
    Integer: 3, Times: 3
    Integer: 2, Times: 1
    Integer: 0, Times: 2
    Integer: 4, Times: 1
    Integer: 1, Times: 3
    Integer: 3, Times: 3


    and as you can see lines are repeated for each time the same integer occurs in a new element. i just need my code to skip an element if the integer has been previously encounterd and recorded. i.e i need it to look more like this :

    Integer: 1, Times: 3
    Integer: 3, Times: 3
    Integer: 0, Times: 2
    Integer: 2, Times: 1
    Integer: 4, Times: 1

    with the first encountered integer being checked throughout the array and then moving to the next integer/element which is not the same as any previous.
    any tips would be greatly appreciated!

    cheers
    Last edited by andrewk1978; 08-05-2012 at 03:27 PM.

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,548
    Rep Power
    23

    Default Re: Printing repeating integers in an array problem!

    What is the algorithm you are using to count the instances? Can you post pseudo code the the program's logic?
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    .paul. is offline Member
    Join Date
    Jun 2012
    Posts
    73
    Blog Entries
    1
    Rep Power
    0

    Default Re: Printing repeating integers in an array problem!

    try this:

    Java Code:
    package dictionary;
    
    import java.util.*;
    
    /**
     *
     * @author Paul
     */
    public class Dictionary {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here
            
            int[] intArray = {1,4,2,3,5,4,4,7,5,4,3,6,8,6,4};
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            
            for(int x : intArray){
                if(map.containsKey(x)){
                    int newCount = map.get(x) + 1;
                    map.remove(x);
                    map.put(x, newCount);
                }
                else{
                    map.put(x, 1); 
                }            
            }
            
            for(Map.Entry<Integer, Integer> e : map.entrySet()){            
                System.out.println("Integer: " + e.getKey() + ", Occurences: " + e.getValue());
            }
            
        }
    }

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,548
    Rep Power
    23

    Default Re: Printing repeating integers in an array problem!

    @.paul What did you post code for? How is that helping the OP write his assignment?
    Where are your comments explaining what the posted code does and how it will solve the problem?
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    .paul. is offline Member
    Join Date
    Jun 2012
    Posts
    73
    Blog Entries
    1
    Rep Power
    0

    Default Re: Printing repeating integers in an array problem!

    without the HashMap:

    Java Code:
    package arraycount;
    
    /**
     *
     * @author Paul
     */
    public class ArrayCount {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here
            
            int[] intArray = {1,4,2,3,5,4,4,7,5,4,3,6,8,6,4};
            
            for(int outer = 0; outer < intArray.length; outer++){
                if(intArray[outer] != Integer.MIN_VALUE) {
                    int num = intArray[outer];
                    intArray[outer] = Integer.MIN_VALUE;
                    int counter = 1;
                    for(int inner = outer + 1; inner < intArray.length; inner++){
                        if(intArray[inner] == num){
                            counter++;
                            intArray[inner] = Integer.MIN_VALUE;
                        }
                    }
                    System.out.println("Integer: " + num + ", Times: " + counter);
                }            
            }
            
        }
    }

  6. #6
    .paul. is offline Member
    Join Date
    Jun 2012
    Posts
    73
    Blog Entries
    1
    Rep Power
    0

    Default Re: Printing repeating integers in an array problem!

    Quote Originally Posted by Norm View Post
    @.paul What did you post code for? How is that helping the OP write his assignment?
    Where are your comments explaining what the posted code does and how it will solve the problem?
    in post#3 the code uses a HashMap<key, Value>
    it iterates through the array + checks if the HashMap contains that key + if so increments the count for that key, + if not adds a new key with a value (count) of 1
    it then iterates through the HashMap + outputs the results

    in post#5 i used nested for loops to iterate through the array counting occurences of numbers

    anyone who is not a complete beginner should be able to understand most of that by studying the code

  7. #7
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,548
    Rep Power
    23

    Default Re: Printing repeating integers in an array problem!

    Why are you trying to do the OPs homework for him? You're not helping the OP by giving him code.
    The Problem with Spoon-feeding

    Why aren't the comments in post #6 in the code so they can be read as the code is read?
    The code does not have any comments describing what it is doing and how it i doing it.
    awinston and Fubarable like this.
    If you don't understand my response, don't ignore it, ask a question.

  8. #8
    andrewk1978 is offline Member
    Join Date
    Aug 2012
    Posts
    8
    Rep Power
    0

    Default Re: Printing repeating integers in an array problem!

    Quote Originally Posted by Norm View Post
    What is the algorithm you are using to count the instances? Can you post pseudo code the the program's logic?
    Thanks for the reply norm,

    Basically my intent is to count the occurances of each integer that occurs in the array, print the integer along with its occurances.

    In my code i allocate the integer in the element 0 to the variable num, then search all elements for num. for each occurance of num i increment a counter x 1. at the completion of the search of the entire array i print num and the counter.
    Then set num to the contents of element 1 and again search all elements from 0 to array.length and incremenet the counter for each time num occurs. Then i print the variables num and counter. This process is repeated through the entire array using a nested for loop.
    You should be able to see form this where the error is occuring. basically the code doesnt take into acount that the next element contains the same integer as a previous element and it repeats the process for the integer again.
    The problem is my knowledge of java (and i have googled and searched for days) isnt enought to work out how to check if 'num' is the same as any of the previous elements of the array and if so , skip it. Im just not sure how to code that. Im assuming it would be in a while loop and nest the inner for loop inside the while loop.

    The while loop could be something like : While (num != to any previous array elements) { Check each element for num and increment the times variable for each occurance}. however im just not sure how to write that (num != to any previous arrays) in code or if it is even possible?




    Another method i have tried....

    since all integers in this case are >= 0, i create a counter that starts at 0 and i compare all elements of the array to this counter. if an element contans 0 i increase the times variable by 1 for each occurance. i then print out the counter/integer and the times variable ONLy if the integer (0 in this case) resulted in the times variable being incremented (ie if the integer occured in the array). i then reset the times variable and increment the counter to the next integer (1). i then repeat the process searching every element of the array for the integer and if it occurs increment the times variable accordigingly and print the results once the search is completed. etc etc

    if i explained that well enough youll see that the error in this case is in the fact that every integer is searched for in sequential order from 0 up to the length of the array incrementing by 1. what i want the output to do is simply find the first integer in element 0, and search for it throughout the array. then print out the number of occurances. skip to the next element and repeat the process IF the integer hasnt been recorded previously. So the output should have the integers sorted in the order they appear sequentially from array element 0 to array.length

    very long winded i appolagize. i hope this helps you see where im going wrong. well i know where im going wrong i just dont have the knowledge to implement that one step after a lot of searching.


    thanks!
    Last edited by andrewk1978; 08-06-2012 at 01:52 AM.

  9. #9
    .paul. is offline Member
    Join Date
    Jun 2012
    Posts
    73
    Blog Entries
    1
    Rep Power
    0

    Default Re: Printing repeating integers in an array problem!

    you need an outer loop that iterates from 0 through the array
    inside that loop you need to loop from 0 to outer - 1 + test if your current number has already been counted
    if not already counted then an inner loop that iterates from outer + 1 through the array + counts reoccurences of your current number

  10. #10
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,548
    Rep Power
    23

    Default Re: Printing repeating integers in an array problem!

    Your second approach is near the one I was thinking of. Instead of using a counter that starts at 0 and goes to max int value, try doing a search through the array for the next value to count.
    If you don't understand my response, don't ignore it, ask a question.

  11. #11
    andrewk1978 is offline Member
    Join Date
    Aug 2012
    Posts
    8
    Rep Power
    0

    Default Re: Printing repeating integers in an array problem!

    Hmm thanks for the tips, ill keep cracking on and post and future progress or dramas.

    Thanks!

  12. #12
    andrewk1978 is offline Member
    Join Date
    Aug 2012
    Posts
    8
    Rep Power
    0

    Default Re: Printing repeating integers in an array problem!

    this step im finding difficult because we are only allowed to use double or int variables for storing values. So i can set an int variable to be the previous number. then go to the next element and check if it is the same as the previous element by checking the int variable. and if not, set the int variable to be the new element contents and repeat the process. problem is im only checking against the single previous element. have to try and wrap my head around a way to check ALL previous elements using only an int variable or numerous int variables to store checked integers.

  13. #13
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,755
    Rep Power
    7

    Default Re: Printing repeating integers in an array problem!

    A Map would be ideal for this but I guess that is too advanced for you. Parallel arrays are generally frowned upon by many experienced programmers but it would be workable solution for you. Whenever you encounter a number in the original array place it in another array and update a count in a parallel array but only insert it into the new array the first time you encounter it.

    Say you have and array: 1,2,1,4,1,2,1,4,1,3
    Then 2nd array would be: 1,2,4,3
    Count array would be: 5,2,2,1
    That is 1 appears 5 times.
    2 appears 2 times
    4 appears 2 times.
    3 appears 1 times.

    Obviosly I have omitted the nitty gritty details which you need to work out.

  14. #14
    andrewk1978 is offline Member
    Join Date
    Aug 2012
    Posts
    8
    Rep Power
    0

    Default Re: Printing repeating integers in an array problem!

    Quote Originally Posted by Junky View Post
    A Map would be ideal for this but I guess that is too advanced for you. Parallel arrays are generally frowned upon by many experienced programmers but it would be workable solution for you. Whenever you encounter a number in the original array place it in another array and update a count in a parallel array but only insert it into the new array the first time you encounter it.

    Say you have and array: 1,2,1,4,1,2,1,4,1,3
    Then 2nd array would be: 1,2,4,3
    Count array would be: 5,2,2,1
    That is 1 appears 5 times.
    2 appears 2 times
    4 appears 2 times.
    3 appears 1 times.

    Obviosly I have omitted the nitty gritty details which you need to work out.
    thanks for the response. but i specifically cant use ANYTHING other than int and double variables for storing values. so no data structures/arrays.
    Doing my head in :)

  15. #15
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,755
    Rep Power
    7

    Default Re: Printing repeating integers in an array problem!

    Are you positive you cannot use arrays? By only using variables makes this problem nearly impossible unless you have been told that the array will only have a maximum size of 10 elements.

    If the problem needs to solve for an array of any size then how exactly do you know how many variables to declare. Besides declaring more than 10 variables becomes a real PITA to code and maintain.

  16. #16
    andrewk1978 is offline Member
    Join Date
    Aug 2012
    Posts
    8
    Rep Power
    0

    Default Re: Printing repeating integers in an array problem!

    Quote Originally Posted by Junky View Post
    Are you positive you cannot use arrays? By only using variables makes this problem nearly impossible unless you have been told that the array will only have a maximum size of 10 elements.

    If the problem needs to solve for an array of any size then how exactly do you know how many variables to declare. Besides declaring more than 10 variables becomes a real PITA to code and maintain.
    certain. no arrays, no data structures. only int or double variables. the size of the array is nominated by a variable named 'size' where in the example size is set to 10. however they are specific in that the program should work for any size value greater than 1. u can see why im bashing my head against a wall here. its been done by plenty of people. just struggling being so new to it to get my head around the logic.

  17. #17
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Printing repeating integers in an array problem!

    No arrays is a bit tough ... given that the d@mn things make their appearance in array.

    Can you (assignment rules and knowledge) sort the input? If so that would be a first step that would make the dulicate detection and counting problem a little more tractable.

  18. #18
    andrewk1978 is offline Member
    Join Date
    Aug 2012
    Posts
    8
    Rep Power
    0

    Default Re: Printing repeating integers in an array problem!

    nope! specifically no sorting of the results allowed. the second approach posted got the correct output but in order sequence based on integer value. not based on the order at which the random integers appear in the array from element 0 and onwards. and that is still incorrect. no sorting, no arrays. its painful.

    again. thanks for all the responses. ill keep on it.

  19. #19
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,548
    Rep Power
    23

    Default Re: Printing repeating integers in an array problem!

    Can the contents of the array be changed?
    Seems the problem is how to keep track of what numbers have been counted. Could a method that scans the array determine if a number has already been counted?
    If you don't understand my response, don't ignore it, ask a question.

  20. #20
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,442
    Rep Power
    18

    Default Re: Printing repeating integers in an array problem!

    That's what I'm thinking as well, Norm.
    Are the values in that array (for example) always +ve or 0?
    If so then you could set the ones you have checked to a negative value to mark them as "checked".
    Or even simply max integer or min integer...just something to flag them.
    Please do not ask for code as refusal often offends.

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 4
    Last Post: 01-27-2012, 11:18 AM
  2. Replies: 7
    Last Post: 04-22-2011, 11:40 AM
  3. Printing repeating integers in a given array?
    By baumboards in forum New To Java
    Replies: 7
    Last Post: 01-24-2011, 07:08 PM
  4. Non-Repeating Random Integers
    By Psyclone in forum New To Java
    Replies: 5
    Last Post: 01-31-2010, 09:04 PM
  5. Problem printing an array
    By denial in forum New To Java
    Replies: 3
    Last Post: 11-01-2009, 10:09 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •