Maximum count of same digit in array list - java
Suppose I have an array list of of values {0,1,1,0,1,1,1}
Here the maximum repeat of value 1 in continuous sequence is 3.
How do I find the maximum count.
List<String> list = new ArrayList<String>();
for (int i=0;i<5;i++)
{
System.out.println("Enter value");
x = in.nextLine();
list.add(""+x);
}
Map<String, Integer> countMap = new HashMap<>();
for (String word : list) {
Integer count = countMap.get(word);
if(count == null) {
count = 0;
}
countMap.put(word, (count.intValue()+1));
}
This gives total count of same value but I need maximum continuous values.
public static void main(String args[]) throws IOException{
List<String> list = new ArrayList<String>();
List<String> temp = new ArrayList<String>();
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
for (int i=0;i<15;i++)
{
System.out.println("Enter value");
String x=br.readLine();
list.add(x);
}
LinkedHashMap<String, Integer> lhm=new LinkedHashMap<String, Integer>();
for(String str1:list){
int flag=0;
for(Entry<String, Integer> entry:lhm.entrySet()){
if(entry.getKey().equals(str1)){
flag=1;
break;
}}
if(flag==0){
lhm.put(str1, 1);
}
}
int maxCount = 1;
int currCount = 1;
for (int i=1;i<list.size();++i) {
if (list.get(i).equals(list.get(i-1))) {
++currCount;
if(list.size()==i+1){
maxCount = Math.max(lhm.get(list.get(i)), currCount);
lhm.put(list.get(i), maxCount);
}
} else {
maxCount = Math.max(lhm.get(list.get(i-1)), currCount);
lhm.put(list.get(i-1), maxCount);
currCount = 1;
}
}
for(Entry<String, Integer> entry:lhm.entrySet()){
System.out.println("Maximum Sequential occurrence of element- "+entry.getKey()+" is- "+entry.getValue());//display result
}
}
Above code will print max sequential occurrence of all element in list.
How about:
// Initialize to 1 because first element is equal to itself.
int maxCount = 1;
int currCount = 1;
for (int i=1;i<list.size();++i) {
if (list.get(i).equals(list.get(i-1))) {
++currCount;
} else {
currCount = 1;
}
maxCount = Math.max(maxCount, currCount);
}
return maxCount;
This iterates over your sequence and finds the longest continuous sequence.
Related
Java Deque (Finding the max number of unique integers from subarrays.)
I was trying to solve a HackerRank problem on Java Deque. My code passed all the cases apart from the ones which have 100,000 inputs. Problem: In this problem, you are given N integers. You need to find the maximum number of unique integers among all the possible contiguous subarrays of size M. --->So we wre given N integers, and need to find the number of "unique integers" in each contagious subarray(of size M). And then print the maximum number of those "unique Integers". link: https://www.hackerrank.com/challenges/java-dequeue/problem My Code: public static void main(String[] args) { Scanner in = new Scanner(System.in); Deque deque = new ArrayDeque<>(); HashSet<Integer> set = new HashSet<>(); int n = in.nextInt(); int m = in.nextInt(); int max=0; for (int i = 0; i < n; i++) { int num = in.nextInt(); deque.add(num); set.add(num); if(i>=m-1){ if(set.size()>max)max=set.size(); Integer removed=(Integer)deque.removeFirst(); set.remove(removed); set.add((Integer)deque.peek()); } } System.out.println(max); } Please tell me where my code went wrong.
What is the point of this line? set.add((Integer)deque.peek()); I don't see anything in your code that is slow. I just wonder how you can keep track of unique numbers by using a set, given that a set only tells you if there is such a number (but not how many occurrences of the same number there are). And you don't want to keep scanning the deque to see if the number being removed is the last one. I don't think this is great/fast code, but it seems to pass the test-cases. I keep a count of how many of each integer there is in the window by using a map (and use some of your code). import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); Deque<Integer> deque = new ArrayDeque<>(); HashMap<Integer, Integer> counts = new HashMap<>(); int n = in.nextInt(); int m = in.nextInt(); int max = 0; for (int i = 0; i < n; i++) { int num = in.nextInt(); deque.add(num); int count = counts.getOrDefault(num, 0); counts.put(num, ++count); if (i >= m - 1) { if (counts.size() > max) max = counts.size(); Integer removed = deque.removeFirst(); int removing = counts.get(removed); removing--; if (removing == 0) { counts.remove(removed); } else { counts.put(removed, removing); } } } System.out.println(max); } }
Just wanted to share how I solved it in case it helps. public static void main(String[] args) { Scanner in = new Scanner(System.in); Deque deque = new ArrayDeque(); Set<Integer> integers = new HashSet<>(); int n = in.nextInt(); int m = in.nextInt(); long result = 0; for (int i = 0; i < n; i++) { int num = in.nextInt(); deque.add(num); integers.add(num); if (deque.size() == m) { long currentSize = integers.size(); if (currentSize > result) { result = currentSize; } Integer removed = (Integer) deque.pollFirst(); if (!deque.contains(removed)) { integers.remove(removed); } } } System.out.println(result); }
We can optimize the space a little bit by avoiding the hashmap all together, but it seems like Hackerrank does not care about that. Any how I am putting my solution here which can solve this problem by using using a map. private int countUniqueNumsInSubarrays(int[] nums, int m) { Deque<Integer> deque = new LinkedList<>(); int maxUniqueCount = 0; for (int i = 0; i < nums.length; i++) { // if deque's left entry is outside the window then pop it out while (!deque.isEmpty() && i - deque.peekFirst() >= m) { deque.removeFirst(); } // this will make sure that the deque only contains unique numbers, // this is essentially helps us avoid that extra hash map while (!deque.isEmpty() && nums[deque.peekLast()] == nums[i]) { deque.removeLast(); } deque.addLast(i); if (i >= m - 1) { maxUniqueCount = Math.max(maxUniqueCount, deque.size()); } } return maxUniqueCount; }
import java.io.*; import java.util.*; import java.util.stream.Stream; public class Solution { public static void main(String[] args) { var sc = new Scanner(System.in); var split = sc.nextLine().split(" "); int n = Integer.parseInt(split[0]); int m = Integer.parseInt(split[1]); if (!(1 <= n && n <= 100_000)) { System.exit(0); } if (!(1 <= m && m <= 100_000)) { System.exit(0); } if (!(m <= n)) { System.exit(0); } split = sc.nextLine().split(" "); sc.close(); int maxNumUniqueInt = 0; HashSet<Integer> dist = new HashSet<>(); Deque<Integer> deque = new ArrayDeque<>(); int[] arr = Stream.of(split).mapToInt(Integer::parseInt).toArray(); for (int i = 0; i < m; i++) { deque.addLast(arr[i]); dist.add(arr[i]); } int num = dist.size(); if (maxNumUniqueInt < num) { maxNumUniqueInt = num; } for (int i = m; i < n; i++) { deque.addLast(arr[i]); dist.add(arr[i]); int remove = deque.removeFirst(); if (!deque.contains(remove)) { dist.remove(remove); } num = dist.size(); if (maxNumUniqueInt < num) { maxNumUniqueInt = num; } // System.out.println(i + " | " + deque + " | " + dist + " | " + maxNumUniqueInt); } System.out.println(maxNumUniqueInt); } }
import java.util.*; public class test { public static void main(String[] args) { Scanner in = new Scanner(System.in); Deque<Integer> deque = new ArrayDeque<>(); int n = in.nextInt(); int m = in.nextInt(); int maxUnique = 0; Map<Integer, Boolean> uniqSet = new HashMap<>(); for (int i = 0; i < n; i++) { int num = in.nextInt(); deque.addLast(num); uniqSet.put(num, true); if(deque.size() == m){ // int uniqueSize = new HashSet<>(deque).size(); int uniqueSize = uniqSet.size(); maxUnique = Math.max(maxUnique, uniqueSize); int x = deque.removeFirst(); if(!deque.contains(x)){ uniqSet.remove(x); } } } in.close(); System.out.println(maxUnique); } }
Get largest Group of anagrams in an array
For an assignment I have been asked to find the largest group of anagrams in a list. I believe I would have to have an accumulation loop inside of another loop that keeps track of the largest number of items. The problem is that I don't know how to count how many of each anagram I have. I have been able to sort the array into groups based on their anagrams. So from the index 1-3 is one anagram, 4-10 is another, etc. How do I search through and count how many of each anagram I have? Then compare each one to the previous count. Sample of the code: public static String[] getLargestAnagramGroup(String[] inputArray) { ArrayList<String> largestGroupArrayList = new ArrayList<String>(); if (inputArray.length == 0 || inputArray == null) { return new String[0]; } insertionSort(inputArray, new AnagramComparator()); String[] largestGroupArray = new String[largestGroupArrayList.size()]; largestGroupArrayList.toArray(inputArray); System.out.println(largestGroupArray); return largestGroupArray; } UPDATE: This is how we solved it. Is there a more efficient way? public static String[] getLargestAnagramGroup(String[] inputArray) { int numberOfAnagrams = 0; int temporary = 1; int position = -1; int index = 0; if (inputArray == null) { return new String[0]; } insertionSort(inputArray, new AnagramComparator()); for (index = 0; index < inputArray.length - 1; index++) { if (areAnagrams(inputArray[index], inputArray[index + 1])) { temporary++; } else { if (temporary > numberOfAnagrams) { numberOfAnagrams = temporary; position = index; temporary = 1; } else if (temporary < numberOfAnagrams) { temporary = 1; } } } if (temporary > numberOfAnagrams) { position = index; numberOfAnagrams = temporary; } String[] largestArray = new String[numberOfAnagrams]; for (int startIndex = position - numberOfAnagrams + 1, i = 0; startIndex <= position; startIndex++, i++) { largestArray[i] = inputArray[startIndex]; } return largestArray; }
Here is a piece of code to help you out. public class AnagramTest { public static void main(String[] args) { String[] input = {"test", "ttes", "abcd", "dcba", "dbac"}; for (String string : getLargestAnagramGroup(input)) { System.out.println(string); } } /** * Gives an array of Strings which are anagrams and has the highest occurrence. * * #param inputArray * #return */ public static String[] getLargestAnagramGroup(String[] inputArray) { // Creating a linked hash map to maintain the order Map<String, List<String>> map = new LinkedHashMap<String, List<String>>(); for (String string : inputArray) { char[] charArray = string.toCharArray(); Arrays.sort(charArray); String sortedStr = new String(charArray); List<String> anagrams = map.get(sortedStr); if (anagrams == null) { anagrams = new ArrayList<String>(); } anagrams.add(string); map.put(sortedStr, anagrams); } Set<Entry<String, List<String>>> entrySet = map.entrySet(); List<String> l = new ArrayList<String>(); int highestAnagrams = -1; for (Entry<String, List<String>> entry : entrySet) { List<String> value = entry.getValue(); if (value.size() > highestAnagrams) { highestAnagrams = value.size(); l = value; } } return l.toArray(new String[l.size()]); } } The idea is to first find the anangrams. I am doing that using a sorting the string's character array and using the LinkedhashMap. Then I am storing the original string in the list which can be used to print or reuse as a result. You have to keep counting the number of times the an anagram occurs and that value can be used solve your problem
This is my solution in C#. public static string[] LargestAnagramsSet(string[] words) { var maxSize = 0; var maxKey = string.Empty; Dictionary<string, List<string>> set = new Dictionary<string, List<string>>(); for (int i = 0; i < words.Length; i++) { char[] temp = words[i].ToCharArray(); Array.Sort(temp); var key = new string(temp); if (set.ContainsKey(key)) { set[key].Add(words[i]); } else { var anagrams = new List<string> { words[i] }; set.Add(key, anagrams); } if (set[key].Count() > maxSize) { maxSize = set[key].Count(); maxKey = key; } } return string.IsNullOrEmpty(maxKey) ? words : set[maxKey].ToArray(); }
Java program to find the duplicate record in an array when the number is repeated more than twice
I am very new to java and a junior java developer. The requirement asks to get the list of customerid and if the list contains customer ids which are repeated, then it would display the dupliate record. And if there are no customer id which are repeated then it would display no duplicate record. I have tried but stuck at the point where the customerid is repeated more than twice. My code works fine till the point the customerid is repeated twice. For ex: Customerid:(5 input) 123 123 234 123 234 Output(Expected) 123 234 Actual: 123 123 123 234 for Scenario where there is no duplicate element, it would print no records found. Input: 123 234 345 456 567 Output: No records found Output of my code is wrong when the repetition is more than twice. Kindly Advice. Code: package firstpack; import java.util.Scanner; public class Class9 { public static void main(String[] args) { int a, i; Scanner sc = new Scanner(System.in); a = sc.nextInt(); long[] b = new long[a]; for (i = 0; i <= (b.length - 1); ) { do { b[i] = sc.nextLong(); i++; } while (i <= a - 1); } System.out.println("Duplicate records :"); for (i = 0; i < b.length - 1; i++) { for (int j = i + 1; j < b.length; j++) { if ((b[i] == (b[j])) && (i != j)) { System.out.println(b[j]); } } } }
//Try this code if you don't want to use set for Array uniqueness. import java.util.*; class MyUnique{ public static void main(String args[]){ Scanner sc= new Scanner(System.in); ArrayList<Integer> arr= new ArrayList<Integer>(); int length=sc.nextInt(); int myarr[]= new int[length]; for(int i=0;i<length;i++){ System.out.println("enter the value of array"); int value=sc.nextInt(); if(arr.contains(value)){ System.out.println("dublicate value not add and index not increased"); i = i-1; //index will not increse }else{ myarr[i] = value; } arr.add(value); } System.out.println("Here is the array output"); for(int m=0;m<length; m++){ System.out.print(myarr[m]+","); } } }
As commented by alfasin, you should use HashSet as they don't take duplicate values. So you don't have to use any loops to check. After that just print the set and you will get the result. So use something like this : Set<Integer> s = new HashSet<Integer>(); s.add(123); s.add(123); s.add(234); s.add(123); s.add(234); for(Integer i : s) { System.out.println(i); } When I print it I get: 234 123 Hope that helps !!
You can use LinkedHashSet to get the distinct list of inputs and counts how many same inputs are in the list. public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int inputCount = sc.nextInt(); List<Long> inputArr = new ArrayList<>(); for (int i = 0; i < inputCount; i++){ inputArr.add(sc.nextLong()); } System.out.println("=================="); Set<Long> distinctArr = new LinkedHashSet<>(inputArr); for (Long input : distinctArr) { if(Collections.frequency(inputArr, input) > 1){ System.out.println(input); } } } Or you could just put your result in HashSet before print out. Set<Long> set = new HashSet<Long>(); for (i = 0; i < b.length - 1; i++) { for (int j = i + 1; j < b.length; j++) { if ((b[i] == (b[j])) && (i != j)) { set.add(b[j]); } } } for (Long result: set) { System.out.println(result); }
Try this use set to find out if duplicate entry exists or not public static void main(String[] args) throws IOException { int a, i; Scanner sc = new Scanner(System.in); a = sc.nextInt(); long[] b = new long[a]; for (i = 0; i <= (b.length - 1); ) { do { b[i] = sc.nextLong(); i++; } while (i <= a - 1); } Set<Long> first = new HashSet<>(); Set<Long> duplicates = new HashSet<>(); for (i = 0; i < b.length ; i++) { if(!first.add(b[i])) { duplicates.add(b[i]); } } String message = duplicates.size() > 0 ? "Duplicate records:": "No Duplicate entry"; System.out.println(message); duplicates.stream().forEach(System.out::println); //in case if you want to print unique entries first.removeAll(duplicates); if(first.size() > 0){ System.out.println("Unique Entries:"); first.stream().forEach(System.out::println); } }
You can use HashMap to store the count of each element and print only if the count is more than 1. And if you need in the order of insertion then use LinkedHashMap instead of HashMap. import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Class9 { public static void main(String[] args) { int a, i; Scanner sc = new Scanner(System.in); a = sc.nextInt(); long[] b = new long[a]; Map<Long, Integer> countMap = new HashMap<Long, Integer>(); for (i = 0; i <= (b.length - 1); ) { do { b[i] = sc.nextLong(); if (countMap.containsKey(b[i])) { countMap.put(b[i], countMap.get(b[i]) + 1); } else { countMap.put(b[i], 1); } i++; } while (i <= a - 1); } System.out.println("Duplicate records :"); for (Long key : countMap.keySet()) { if (countMap.get(key) > 1) { System.out.println(key); } } } }
Getting group of the same numbers numbers
I'm working on a code which will count how many are the groups with the same number. For example: 11022 = 2 groups with the same number 1100021 = 2 groups with the same number 12123333 = 1 group with the same number So far I've come up to this code: package Numbers; import java.util.*; public class Numbers{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int strI ; strI = scan.nextInt(); int[] a = {strI}; System.out.println(sum(a)); System.out.println("length = "+a.length); } public static in sum(int[] a){ int sum = 0; int last = 0; for (int i = 0; i < a.length - 1; i++){ if(a[i] == a[i + 1] && last != a[i + 1]){ sum++; } last = a[i]; } return sum; } } My problem is that the inputted number will register as 1 index. is it possible to enter a series of number that will go to different indexes?
This is easiest done by converting it to a string so you don't have to deal with place value. After all, you only care about the characters themselves. public static void main(String[] args){ // Get number n... Assuming n has been set to the int in question int n = ...; //Fill in with whatever int you want to test String s = n + ""; char same = ' '; int consec = 0; for(int i = 0; i < s.length() - 1; i++){ if(s.charAt(i) == s.charAt(i+1)){ if(same == ' ') consec++; same = s.charAt(i); } else{ same = ' '; } } System.out.println(consec); }
First, you can get the count of consecutive digits with something like public static int sum(int a) { String strI = String.valueOf(a); int count = 0; boolean inRun = false; for (int i = 1; i < strI.length(); i++) { if (strI.charAt(i - 1) == strI.charAt(i)) { if (inRun) { continue; } inRun = true; count++; } else { inRun = false; } } return count; } public static void main(String[] args) { int[] arr = { 11022, 1100021, 12123333 }; for (int val : arr) { int count = sum(val); String group = "groups"; if (count == 1) { group = "group"; } System.out.printf("%d = %d %s with the same number%n", val, count, group); } } Output is the requested 11022 = 2 groups with the same number 1100021 = 2 groups with the same number 12123333 = 1 group with the same number As for your second question, you might read Integer into a List - Java arrays are immutable, List<Integer> al = new ArrayList<>(); Scanner scan = new Scanner(System.in); while (scan.hasNextInt()) { al.add(scan.nextInt()); } Integer[] arr = al.toArray(new Integer[0]); System.out.println(Arrays.toString(arr));
Finding repeated words on a string and counting the repetitions
I need to find repeated words on a string, and then count how many times they were repeated. So basically, if the input string is this: String s = "House, House, House, Dog, Dog, Dog, Dog"; I need to create a new string list without repetitions and save somewhere else the amount of repetitions for each word, like such: New String: "House, Dog" New Int Array: [3, 4] Is there a way to do this easily with Java? I've managed to separate the string using s.split() but then how do I count repetitions and eliminate them on the new string? Thanks!
You've got the hard work done. Now you can just use a Map to count the occurrences: Map<String, Integer> occurrences = new HashMap<String, Integer>(); for ( String word : splitWords ) { Integer oldCount = occurrences.get(word); if ( oldCount == null ) { oldCount = 0; } occurrences.put(word, oldCount + 1); } Using map.get(word) will tell you many times a word occurred. You can construct a new list by iterating through map.keySet(): for ( String word : occurrences.keySet() ) { //do something with word } Note that the order of what you get out of keySet is arbitrary. If you need the words to be sorted by when they first appear in your input String, you should use a LinkedHashMap instead.
Try this, public class DuplicateWordSearcher { #SuppressWarnings("unchecked") public static void main(String[] args) { String text = "a r b k c d se f g a d f s s f d s ft gh f ws w f v x s g h d h j j k f sd j e wed a d f"; List<String> list = Arrays.asList(text.split(" ")); Set<String> uniqueWords = new HashSet<String>(list); for (String word : uniqueWords) { System.out.println(word + ": " + Collections.frequency(list, word)); } } }
public class StringsCount{ public static void main(String args[]) { String value = "This is testing Program testing Program"; String item[] = value.split(" "); HashMap<String, Integer> map = new HashMap<>(); for (String t : item) { if (map.containsKey(t)) { map.put(t, map.get(t) + 1); } else { map.put(t, 1); } } Set<String> keys = map.keySet(); for (String key : keys) { System.out.println(key); System.out.println(map.get(key)); } } }
As mentioned by others use String::split(), followed by some map (hashmap or linkedhashmap) and then merge your result. For completeness sake putting the code. import java.util.*; public class Genric<E> { public static void main(String[] args) { Map<String, Integer> unique = new LinkedHashMap<String, Integer>(); for (String string : "House, House, House, Dog, Dog, Dog, Dog".split(", ")) { if(unique.get(string) == null) unique.put(string, 1); else unique.put(string, unique.get(string) + 1); } String uniqueString = join(unique.keySet(), ", "); List<Integer> value = new ArrayList<Integer>(unique.values()); System.out.println("Output = " + uniqueString); System.out.println("Values = " + value); } public static String join(Collection<String> s, String delimiter) { StringBuffer buffer = new StringBuffer(); Iterator<String> iter = s.iterator(); while (iter.hasNext()) { buffer.append(iter.next()); if (iter.hasNext()) { buffer.append(delimiter); } } return buffer.toString(); } } New String is Output = House, Dog Int array (or rather list) Values = [3, 4] (you can use List::toArray) for getting an array.
Using java8 private static void findWords(String s, List<String> output, List<Integer> count){ String[] words = s.split(", "); Map<String, Integer> map = new LinkedHashMap<>(); Arrays.stream(words).forEach(e->map.put(e, map.getOrDefault(e, 0) + 1)); map.forEach((k,v)->{ output.add(k); count.add(v); }); } Also, use a LinkedHashMap if you want to preserve the order of insertion private static void findWords(){ String s = "House, House, House, Dog, Dog, Dog, Dog"; List<String> output = new ArrayList<>(); List<Integer> count = new ArrayList<>(); findWords(s, output, count); System.out.println(output); System.out.println(count); } Output [House, Dog] [3, 4]
If this is a homework, then all I can say is: use String.split() and HashMap<String,Integer>. (I see you've found split() already. You're along the right lines then.)
It may help you somehow. String st="I am am not the one who is thinking I one thing at time"; String []ar = st.split("\\s"); Map<String, Integer> mp= new HashMap<String, Integer>(); int count=0; for(int i=0;i<ar.length;i++){ count=0; for(int j=0;j<ar.length;j++){ if(ar[i].equals(ar[j])){ count++; } } mp.put(ar[i], count); } System.out.println(mp);
Once you have got the words from the string it is easy. From Java 10 onwards you can try the following code: import java.util.Arrays; import java.util.stream.Collectors; public class StringFrequencyMap { public static void main(String... args) { String[] wordArray = {"House", "House", "House", "Dog", "Dog", "Dog", "Dog"}; var freq = Arrays.stream(wordArray) .collect(Collectors.groupingBy(x -> x, Collectors.counting())); System.out.println(freq); } } Output: {House=3, Dog=4}
You can use Prefix tree (trie) data structure to store words and keep track of count of words within Prefix Tree Node. #define ALPHABET_SIZE 26 // Structure of each node of prefix tree struct prefix_tree_node { prefix_tree_node() : count(0) {} int count; prefix_tree_node *child[ALPHABET_SIZE]; }; void insert_string_in_prefix_tree(string word) { prefix_tree_node *current = root; for(unsigned int i=0;i<word.size();++i){ // Assuming it has only alphabetic lowercase characters // Note ::::: Change this check or convert into lower case const unsigned int letter = static_cast<int>(word[i] - 'a'); // Invalid alphabetic character, then continue // Note :::: Change this condition depending on the scenario if(letter > 26) throw runtime_error("Invalid alphabetic character"); if(current->child[letter] == NULL) current->child[letter] = new prefix_tree_node(); current = current->child[letter]; } current->count++; // Insert this string into Max Heap and sort them by counts } // Data structure for storing in Heap will be something like this struct MaxHeapNode { int count; string word; }; After inserting all words, you have to print word and count by iterating Maxheap.
//program to find number of repeating characters in a string //Developed by Subash<subash_senapati#ymail.com> import java.util.Scanner; public class NoOfRepeatedChar { public static void main(String []args) { //input through key board Scanner sc = new Scanner(System.in); System.out.println("Enter a string :"); String s1= sc.nextLine(); //formatting String to char array String s2=s1.replace(" ",""); char [] ch=s2.toCharArray(); int counter=0; //for-loop tocompare first character with the whole character array for(int i=0;i<ch.length;i++) { int count=0; for(int j=0;j<ch.length;j++) { if(ch[i]==ch[j]) count++; //if character is matching with others } if(count>1) { boolean flag=false; //for-loop to check whether the character is already refferenced or not for (int k=i-1;k>=0 ;k-- ) { if(ch[i] == ch[k] ) //if the character is already refferenced flag=true; } if( !flag ) //if(flag==false) counter=counter+1; } } if(counter > 0) //if there is/are any repeating characters System.out.println("Number of repeating charcters in the given string is/are " +counter); else System.out.println("Sorry there is/are no repeating charcters in the given string"); } }
public static void main(String[] args) { String s="sdf sdfsdfsd sdfsdfsd sdfsdfsd sdf sdf sdf "; String st[]=s.split(" "); System.out.println(st.length); Map<String, Integer> mp= new TreeMap<String, Integer>(); for(int i=0;i<st.length;i++){ Integer count=mp.get(st[i]); if(count == null){ count=0; } mp.put(st[i],++count); } System.out.println(mp.size()); System.out.println(mp.get("sdfsdfsd")); }
If you pass a String argument it will count the repetition of each word /** * #param string * #return map which contain the word and value as the no of repatation */ public Map findDuplicateString(String str) { String[] stringArrays = str.split(" "); Map<String, Integer> map = new HashMap<String, Integer>(); Set<String> words = new HashSet<String>(Arrays.asList(stringArrays)); int count = 0; for (String word : words) { for (String temp : stringArrays) { if (word.equals(temp)) { ++count; } } map.put(word, count); count = 0; } return map; } output: Word1=2, word2=4, word2=1,. . .
import java.util.HashMap; import java.util.LinkedHashMap; public class CountRepeatedWords { public static void main(String[] args) { countRepeatedWords("Note that the order of what you get out of keySet is arbitrary. If you need the words to be sorted by when they first appear in your input String, you should use a LinkedHashMap instead."); } public static void countRepeatedWords(String wordToFind) { String[] words = wordToFind.split(" "); HashMap<String, Integer> wordMap = new LinkedHashMap<String, Integer>(); for (String word : words) { wordMap.put(word, (wordMap.get(word) == null ? 1 : (wordMap.get(word) + 1))); } System.out.println(wordMap); } }
I hope this will help you public void countInPara(String str) { Map<Integer,String> strMap = new HashMap<Integer,String>(); List<String> paraWords = Arrays.asList(str.split(" ")); Set<String> strSet = new LinkedHashSet<>(paraWords); int count; for(String word : strSet) { count = Collections.frequency(paraWords, word); strMap.put(count, strMap.get(count)==null ? word : strMap.get(count).concat(","+word)); } for(Map.Entry<Integer,String> entry : strMap.entrySet()) System.out.println(entry.getKey() +" :: "+ entry.getValue()); }
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class DuplicateWord { public static void main(String[] args) { String para = "this is what it is this is what it can be"; List < String > paraList = new ArrayList < String > (); paraList = Arrays.asList(para.split(" ")); System.out.println(paraList); int size = paraList.size(); int i = 0; Map < String, Integer > duplicatCountMap = new HashMap < String, Integer > (); for (int j = 0; size > j; j++) { int count = 0; for (i = 0; size > i; i++) { if (paraList.get(j).equals(paraList.get(i))) { count++; duplicatCountMap.put(paraList.get(j), count); } } } System.out.println(duplicatCountMap); List < Integer > myCountList = new ArrayList < > (); Set < String > myValueSet = new HashSet < > (); for (Map.Entry < String, Integer > entry: duplicatCountMap.entrySet()) { myCountList.add(entry.getValue()); myValueSet.add(entry.getKey()); } System.out.println(myCountList); System.out.println(myValueSet); } } Input: this is what it is this is what it can be Output: [this, is, what, it, is, this, is, what, it, can, be] {can=1, what=2, be=1, this=2, is=3, it=2} [1, 2, 1, 2, 3, 2] [can, what, be, this, is, it]
import java.util.HashMap; import java.util.Scanner; public class class1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); String inpStr = in.nextLine(); int key; HashMap<String,Integer> hm = new HashMap<String,Integer>(); String[] strArr = inpStr.split(" "); for(int i=0;i<strArr.length;i++){ if(hm.containsKey(strArr[i])){ key = hm.get(strArr[i]); hm.put(strArr[i],key+1); } else{ hm.put(strArr[i],1); } } System.out.println(hm); } }
Please use the below code. It is the most simplest as per my analysis. Hope you will like it: import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class MostRepeatingWord { String mostRepeatedWord(String s){ String[] splitted = s.split(" "); List<String> listString = Arrays.asList(splitted); Set<String> setString = new HashSet<String>(listString); int count = 0; int maxCount = 1; String maxRepeated = null; for(String inp: setString){ count = Collections.frequency(listString, inp); if(count > maxCount){ maxCount = count; maxRepeated = inp; } } return maxRepeated; } public static void main(String[] args) { System.out.println("Enter The Sentence: "); Scanner s = new Scanner(System.in); String input = s.nextLine(); MostRepeatingWord mrw = new MostRepeatingWord(); System.out.println("Most repeated word is: " + mrw.mostRepeatedWord(input)); } }
package day2; import java.util.ArrayList; import java.util.HashMap;`enter code here` import java.util.List; public class DuplicateWords { public static void main(String[] args) { String S1 = "House, House, House, Dog, Dog, Dog, Dog"; String S2 = S1.toLowerCase(); String[] S3 = S2.split("\\s"); List<String> a1 = new ArrayList<String>(); HashMap<String, Integer> hm = new HashMap<>(); for (int i = 0; i < S3.length - 1; i++) { if(!a1.contains(S3[i])) { a1.add(S3[i]); } else { continue; } int Count = 0; for (int j = 0; j < S3.length - 1; j++) { if(S3[j].equals(S3[i])) { Count++; } } hm.put(S3[i], Count); } System.out.println("Duplicate Words and their number of occurrences in String S1 : " + hm); } }
public class Counter { private static final int COMMA_AND_SPACE_PLACE = 2; private String mTextToCount; private ArrayList<String> mSeparateWordsList; public Counter(String mTextToCount) { this.mTextToCount = mTextToCount; mSeparateWordsList = cutStringIntoSeparateWords(mTextToCount); } private ArrayList<String> cutStringIntoSeparateWords(String text) { ArrayList<String> returnedArrayList = new ArrayList<>(); if(text.indexOf(',') == -1) { returnedArrayList.add(text); return returnedArrayList; } int position1 = 0; int position2 = 0; while(position2 < text.length()) { char c = ','; if(text.toCharArray()[position2] == c) { String tmp = text.substring(position1, position2); position1 += tmp.length() + COMMA_AND_SPACE_PLACE; returnedArrayList.add(tmp); } position2++; } if(position1 < position2) { returnedArrayList.add(text.substring(position1, position2)); } return returnedArrayList; } public int[] countWords() { if(mSeparateWordsList == null) return null; HashMap<String, Integer> wordsMap = new HashMap<>(); for(String s: mSeparateWordsList) { int cnt; if(wordsMap.containsKey(s)) { cnt = wordsMap.get(s); cnt++; } else { cnt = 1; } wordsMap.put(s, cnt); } return printCounterResults(wordsMap); } private int[] printCounterResults(HashMap<String, Integer> m) { int index = 0; int[] returnedIntArray = new int[m.size()]; for(int i: m.values()) { returnedIntArray[index] = i; index++; } return returnedIntArray; } }
/*count no of Word in String using TreeMap we can use HashMap also but word will not display in sorted order */ import java.util.*; public class Genric3 { public static void main(String[] args) { Map<String, Integer> unique = new TreeMap<String, Integer>(); String string1="Ram:Ram: Dog: Dog: Dog: Dog:leela:leela:house:house:shayam"; String string2[]=string1.split(":"); for (int i=0; i<string2.length; i++) { String string=string2[i]; unique.put(string,(unique.get(string) == null?1:(unique.get(string)+1))); } System.out.println(unique); } }
//program to find number of repeating characters in a string //Developed by Rahul Lakhmara import java.util.*; public class CountWordsInString { public static void main(String[] args) { String original = "I am rahul am i sunil so i can say am i"; // making String type of array String[] originalSplit = original.split(" "); // if word has only one occurrence int count = 1; // LinkedHashMap will store the word as key and number of occurrence as // value Map<String, Integer> wordMap = new LinkedHashMap<String, Integer>(); for (int i = 0; i < originalSplit.length - 1; i++) { for (int j = i + 1; j < originalSplit.length; j++) { if (originalSplit[i].equals(originalSplit[j])) { // Increment in count, it will count how many time word // occurred count++; } } // if word is already present so we will not add in Map if (wordMap.containsKey(originalSplit[i])) { count = 1; } else { wordMap.put(originalSplit[i], count); count = 1; } } Set word = wordMap.entrySet(); Iterator itr = word.iterator(); while (itr.hasNext()) { Map.Entry map = (Map.Entry) itr.next(); // Printing System.out.println(map.getKey() + " " + map.getValue()); } } }
public static void main(String[] args){ String string = "elamparuthi, elam, elamparuthi"; String[] s = string.replace(" ", "").split(","); String[] op; String ops = ""; for(int i=0; i<=s.length-1; i++){ if(!ops.contains(s[i]+"")){ if(ops != "")ops+=", "; ops+=s[i]; } } System.out.println(ops); }
For Strings with no space, we can use the below mentioned code private static void findRecurrence(String input) { final Map<String, Integer> map = new LinkedHashMap<>(); for(int i=0; i<input.length(); ) { int pointer = i; int startPointer = i; boolean pointerHasIncreased = false; for(int j=0; j<startPointer; j++){ if(pointer<input.length() && input.charAt(j)==input.charAt(pointer) && input.charAt(j)!=32){ pointer++; pointerHasIncreased = true; }else{ if(pointerHasIncreased){ break; } } } if(pointer - startPointer >= 2) { String word = input.substring(startPointer, pointer); if(map.containsKey(word)){ map.put(word, map.get(word)+1); }else{ map.put(word, 1); } i=pointer; }else{ i++; } } for(Map.Entry<String, Integer> entry : map.entrySet()){ System.out.println(entry.getKey() + " = " + (entry.getValue()+1)); } } Passing some input as "hahaha" or "ba na na" or "xxxyyyzzzxxxzzz" give the desired output.
Hope this helps : public static int countOfStringInAText(String stringToBeSearched, String masterString){ int count = 0; while (masterString.indexOf(stringToBeSearched)>=0){ count = count + 1; masterString = masterString.substring(masterString.indexOf(stringToBeSearched)+1); } return count; }
package string; import java.util.HashMap; import java.util.Map; import java.util.Set; public class DublicatewordinanArray { public static void main(String[] args) { String str = "This is Dileep Dileep Kumar Verma Verma"; DuplicateString(str); } public static void DuplicateString(String str) { String word[] = str.split(" "); Map < String, Integer > map = new HashMap < String, Integer > (); for (String w: word) if (!map.containsKey(w)) { map.put(w, 1); } else { map.put(w, map.get(w) + 1); } Set < Map.Entry < String, Integer >> entrySet = map.entrySet(); for (Map.Entry < String, Integer > entry: entrySet) if (entry.getValue() > 1) { System.out.printf("%s : %d %n", entry.getKey(), entry.getValue()); } } }
Using Java 8 streams collectors: public static Map<String, Integer> countRepetitions(String str) { return Arrays.stream(str.split(", ")) .collect(Collectors.toMap(s -> s, s -> 1, (a, b) -> a + 1)); } Input: "House, House, House, Dog, Dog, Dog, Dog, Cat" Output: {Cat=1, House=3, Dog=4}
please try these it may be help for you. public static void main(String[] args) { String str1="House, House, House, Dog, Dog, Dog, Dog"; String str2=str1.replace(",", ""); Map<String,Integer> map=findFrquenciesInString(str2); Set<String> keys=map.keySet(); Collection<Integer> vals=map.values(); System.out.println(keys); System.out.println(vals); } private static Map<String,Integer> findFrquenciesInString(String str1) { String[] strArr=str1.split(" "); Map<String,Integer> map=new HashMap<>(); for(int i=0;i<strArr.length;i++) { int count=1; for(int j=i+1;j<strArr.length;j++) { if(strArr[i].equals(strArr[j]) && strArr[i]!="-1") { strArr[j]="-1"; count++; } } if(count>1 && strArr[i]!="-1") { map.put(strArr[i], count); strArr[i]="-1"; } } return map; }
as introduction of stream has changed the way we code; i would like to add some of the ways of doing this using it String[] strArray = str.split(" "); //1. All string value with their occurrences Map<String, Long> counterMap = Arrays.stream(strArray).collect(Collectors.groupingBy(e->e, Collectors.counting())); //2. only duplicating Strings Map<String, Long> temp = counterMap.entrySet().stream().filter(map->map.getValue() > 1).collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue())); System.out.println("test : "+temp); //3. List of Duplicating Strings List<String> masterStrings = Arrays.asList(strArray); Set<String> duplicatingStrings = masterStrings.stream().filter(i -> Collections.frequency(masterStrings, i) > 1).collect(Collectors.toSet());
Use Function.identity() inside Collectors.groupingBy and store everything in a MAP. String a = "Gini Gina Gina Gina Gina Protijayi Protijayi "; Map<String, Long> map11 = Arrays.stream(a.split(" ")).collect(Collectors .groupingBy(Function.identity(),Collectors.counting())); System.out.println(map11); // output => {Gina=4, Gini=1, Protijayi=2} In Python we can use collections.Counter() a = "Roopa Roopi loves green color Roopa Roopi" words = a.split() wordsCount = collections.Counter(words) for word,count in sorted(wordsCount.items()): print('"%s" is repeated %d time%s.' % (word,count,"s" if count > 1 else "" )) Output : "Roopa" is repeated 2 times. "Roopi" is repeated 2 times. "color" is repeated 1 time. "green" is repeated 1 time. "loves" is repeated 1 time.