Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

avoid count same element in array java

// Repetaded element run multiple times means avoid duplicate element count multiple times

import java.util.Scanner;

public class FindFrequency {

    
    public static void main(String[] args) {
       int t,  count=0;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter number of elements to insert in an array: ");
      int  len = in.nextInt();
        int[] arr = new int[len];
        System.out.println("Enter elements to insert in an array: ");
        for( int i=0;i<len;i++)
        {
            t = in.nextInt();
            arr[i] = t;
        }
        System.out.println("
");
        for(int i=0;i<len;i++)
        {
            count=1;
            for(int j=i+1;j<=len-1;j++)
            {
                if(arr[i]==arr[j] )
                {
                    count++;
                 }
            }
            System.out.println(arr[i] + " is " + count + " times.
");
            }        
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have used one more array to store the print value.We can use set as well as.I hope you get the answer.

let array = [1,2,1,3,4,5,6,2]
var arrayWithPosition = [Int]()

for i in 0..<array.count {
    var position = 0
    while position < arrayWithPosition.count {
        if arrayWithPosition[position] == array[i]{
            break
        }
        position += 1
    }
    if position == arrayWithPosition.count{
        arrayWithPosition.append(array[i])
    }else{
        continue
    }
    var count = 1
    for j in i+1..<array.count {
        if array[i] == array[j] {
            count += 1
        }
    }
    print(array[i],count)
}

Output : -

1 2
2 2
3 1
4 1
5 1
6 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...