Transformation of two ArrayList - java

I've got a couple of ArrayList:
ArrayList a --> ["52", "52", "52", "52", "67", "67", "67", "67"]
ArrayList b --> ["1", "4", "5", "6", "3", "4", "5", "10"]
I want to transform them into:
ArrayList at --> ["52", "52", "67", "67"]
ArrayList bt --> ["1", "4 - 6", "3 - 5", "10"]
I know how to make b into bt, but I can't wrap my head around making a into at.
Algorith for making b into bt:
public static void main(String[] args) {
ArrayList<String> alist = new ArrayList<String>();
alist.add("1");
alist.add("4");
alist.add("5");
alist.add("6");
alist.add("3");
alist.add("4");
alist.add("5");
alist.add("10");
alist = groupByRange(alist);
}
static public ArrayList<String> groupByRange(ArrayList<String> alist) {
// ArrayList<String> to ArrayList<Integer>
/////////////////////////////////////////////////////////
ArrayList<Integer> alist_int = new ArrayList<Integer>();
for (String ident : alist) {
alist_int.add(Integer.parseInt(ident));
}
// ArrayList<Integer> to int[]
/////////////////////////////////////////////////////////
int[] arr = new int[alist_int.size()];
for (int i = 0; i < arr.length; i++) {
arr[i] = alist_int.get(i);
}
// Grouping by range (return ArrayList<String>)
/////////////////////////////////////////////////////////
int start, end;
end = start = arr[0];
ArrayList<String> alist_res = new ArrayList<String>();
for (int i = 1; i < arr.length; i++) {
if (arr[i] == (arr[i - 1] + 1)) {
end = arr[i];
} else {
if (start == end) {
alist_res.add(String.valueOf(start));
} else {
alist_res.add(String.valueOf(start) + " - " + String.valueOf(end));
}
start = end = arr[i];
}
}
if (start == end) {
alist_res.add(String.valueOf(start));
} else {
alist_res.add(String.valueOf(start) + " - " + String.valueOf(end));
}
for (String n : alist_res) {
System.out.println(n);
}
return alist_res;
}

I have method for You:
public List<String> groupByValue(List<String> listA) {
if (listA.isEmpty()) {
return Collections.emptyList();
}
final List<String> result = new ArrayList<>();
result.add(listA.get(0));
for (int actualIndex = 1; actualIndex < listA.size(); actualIndex++) {
if (actualIndex + 1 < listA.size() - 1 && !listA.get(actualIndex + 1).equals(listA.get(actualIndex))) {
result.add(listA.get(actualIndex));
actualIndex++;
}
if (actualIndex < listA.size() - 1 && !listA.get(actualIndex - 1).equals(listA.get(actualIndex))) {
result.add(listA.get(actualIndex));
}
if (actualIndex + 1 == listA.size()) {
result.add(listA.get(actualIndex));
}
}
return result;
}
This method has one parameter, is Your input list a. Then, we chcek list, and next, we add first value from a list. Next we check next values, and we have result on the end, it means at list.

Related

Store data to list

Below is my requirements
Scramble the word into all possible permutations and store them in a
list or array
What I have tried
public class Example {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
Example e = new Example();
String changeCase = "ab";
String result = changeCase.toLowerCase();
list = e.permutation("", result);
System.out.println("list size is "+list.size());
for (String str : list) {
System.out.println(str);
}
}
private ArrayList<String> permutation(String prefix, String str) {
ArrayList<String> l = new ArrayList<String>();
int n = str.length();
if (n == 0) {
System.out.println(prefix);
l.add(prefix);
} else {
for (int i = 0; i < n; i++) {
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
return l;
}
}
Output
ab
ba
list size is 0
I make sure all the value is added into list, but when I check the list size, it displays zero.
You create a new ArrayList for each recursive call of permutations instead of reusing the same list every time.
Possible solution:
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
Example e = new Example();
e.permutation(list, "", result);
...
}
private void permutation(List<String> list, String prefix, String str) {
int n = str.length();
if (n == 0) {
System.out.println(prefix);
list.add(prefix);
} else {
for (int i = 0; i < n; i++) {
permutation(list, prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
}
you need to add the response of recursive calls(i.e. response list which contains the permutations) in your list as
l.addAll(permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n)));
You forgot to capture the recursion result
for (int i = 0; i < n; i++) {
l.addAll(permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n))));
}
I've commented your code to point what is going on when you first call this method (prefix="" and str="ab") :
private ArrayList<String> permutation(String prefix, String str) {
ArrayList<String> l = new ArrayList<String>(); //Create a new empty list
int n = str.length(); //obtain the length of str ("ab") so n=2
if (n == 0) { //wrong cause n=2
System.out.println(prefix); //does not execute cause n=2
l.add(prefix); //does not execute cause n=2
} else { //execute the else cause if condition is false
for (int i = 0; i < n; i++) { //for each character in str
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n)); //call a function and ignore the result
}
} //end of else
return l; //return l, but since nothing was added to l, l is the empty list created at the beginning => l.size()=0
}
The problem in your recursion is that you re-create the list every time and ignore the result of sub-steps. You need to catch the result of sub-step and add it to your list.
private ArrayList<String> permutation(String prefix, String str) {
ArrayList<String> l = new ArrayList<String>();
int n = str.length();
if (n == 0) {
System.out.println(prefix);
l.add(prefix);
} else {
for (int i = 0; i < n; i++) {
l.addAll(permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n))); //add the result of the sub-step to the list
}
}
return l;
}
Personally I would make the list a class member instead
public class Example {
private List<String> result = new ArrayList<String>();
public List<String> getResult() {
return result;
}
private void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) {
result.add(prefix);
} else {
for (int i = 0; i < n; i++) {
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
}
public static void main(String[] args) {
Example e = new Example();
String scramble = "abc";
e.permutation("", scramble);
for (String str : e.getResult()) {
System.out.println(str);
}
}
}

Poker game hand evaluator arrays condition structure

I made up a quick poker game. It generates 5 random numbers and converts those numbers into actual cards values and symbols based on their value. However, I have problems when it comes to making the hand evaluation.
So far I only did the flush right as it's really easy but even then it's not perfect (it prints that the user has a flush 5 times... ) and I would really appreciate if someone could help me with the pair, two pair, three of a kind and straight. I could do the rest afterwards but I just need a heads-up on how to do those.
Thank you in advance for your help, here is the code :
package tests;
import java.util.*;
public class TESTS {
public static void main(String[] args) {
boolean[] pack = new boolean[52]; // Array to not generate the same number twice
int[] cards = new int[5]; //The 5 unique random numbers are stored in here.
String[] cardsvalues = new String[5]; // This will assign the card's value based on the random number's value
char[] cardssymbols = new char[5];//This will assign the card's symbol based on the random number's value
char symbols[] = {'♥', '♦', '♣', '♠'}; // possible symbols that the random number can take
String values[] = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"}; // possible values that the random number can take
Random give = new Random();
for (int i = 0; i < cards.length; i++) { // Gives 5 unique random numbers
do {
cards[i] = give.nextInt(52);
} while (pack[cards[i]]);
pack[cards[i]] = true;
System.out.println(cards[i]);
}
for (int i = 0; i < cards.length; i++) { // This converts the number to a card symbol based on the number's value
final int numOfSymbol = cards[i] / 13;
cardssymbols[i] = symbols[numOfSymbol];
}
for (int i = 0; i < cards.length; i++) { // This converts the number to an actual card value based on the number's value.
final int numOfValues = cards[i] % 13;
cardsvalues[i] = values[numOfValues];
}
for (int i = 0; i < cardssymbols.length; i++) { // Prints the actual cards once they are converted
System.out.print(cardssymbols[i]);
System.out.println(cardsvalues[i]);
}
for (int i = 0; i < cardsvalues.length; i++) { //Here is the problem, i have no idea on how to make the handevaluator ...
if (cardsvalues[i] == cardsvalues[i] + 1) {
System.out.println("PAIR !!!");
} else if (cardsvalues[i] == cardsvalues[i] + 1 && cardsvalues[i] == cardsvalues[i] + 2) {
System.out.println("TRIPS !!!");
} else if (cardssymbols[0] == cardssymbols[1] && cardssymbols[1] == cardssymbols[2] && cardssymbols[2] == cardssymbols[3] && cardssymbols[3] == cardssymbols[4]) {
System.out.println("FLUSHHH");
}
}
}
Hints:
To simplify testing for straights and sorting by highest card, it is easier to represent ranks by their indexes, and only translate them to the symbols for printing.
Using a Card object allows for clearer code.
The Java Collection framework has useful functions for shuffling, slicing and sorting.
My solution:
public class Test {
static final char[] suits = {'♥', '♦', '♣', '♠'};
static final String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
static class Card {
final int suit;
final int rank;
Card(int s, int r) {
suit = s;
rank = r;
}
#Override
public String toString() {
return suits[suit] + ranks[rank]; // or however you want the cards to be printed
}
}
public static void main(String[] args) {
List<Card> deck = new ArrayList<>();
for (int s = 0; s < suits.length; s++) {
for (int r = 0; r < ranks.length; r++) {
deck.add(new Card(s,r));
}
}
Collections.shuffle(deck);
List<Card> hand = deck.subList(0,5);
Collections.sort(hand, Comparator.comparing(c -> c.rank));
System.out.println("Your hand is: " + hand);
System.out.println(value(hand));
}
static String value(List<Card> hand) {
boolean straight = true;
boolean flush = true;
for (int i = 1; i < hand.size(); i++) {
straight &= hand.get(i - 1).rank + 1 == hand.get(i).rank;
flush &= hand.get(i - 1).suit == hand.get(i).suit;
}
if (straight && flush) {
return "Straight Flush from " + hand.get(4);
}
List<Run> runs = findRuns(hand);
runs.sort(Comparator.comparing(r -> -r.rank));
runs.sort(Comparator.comparing(r -> -r.length));
if (runs.get(0).length == 4) {
return "Four of a Kind: " + runs;
}
if (runs.get(0).length == 3 && runs.get(1).length == 2) {
return "Full House: " + runs;
}
if (straight) {
return "Straight from " + hand.get(4);
}
if (runs.get(0).length == 3) {
return "Three of a Kind: " + runs;
}
if (runs.get(1).length == 2) {
return "Two pair: " + runs;
}
if (runs.get(0).length == 2) {
return "Pair: " + runs;
}
return "High card: " + runs;
}
/** Represents {#code length} cards of rank {#code rank} */
static class Run {
int length;
int rank;
#Override
public String toString() {
return ranks[rank];
}
}
static List<Run> findRuns(List<Card> hand) {
List<Run> runs = new ArrayList<>();
Run run = null;
for (Card c : hand) {
if (run != null && run.rank == c.rank) {
run.length++;
} else {
run = new Run();
runs.add(run);
run.rank = c.rank;
run.length = 1;
}
}
return runs;
}
}
Example output:
Your hand is: [♣10, ♥J, ♦J, ♠K, ♥K]
Two pair: [K, J, 10]

Sort only Numeric elements from String Array in java?

I am keen to sort only numeric elements that are in String array. I am doing it in java. Please help me to solve this Problem.
Here is my Problem
For the given set of characters, choose integers only and sort them in descending order and put in their position leaving other characters position intact.
The change is position should only be of integers not of other characters.
Sample Input:-
d,1,4,c,9,6
109,87,911,b,645
77,19,#,.,95
8,99,14,2,5,6,49
Sample Output:-
Case #1: d,9,6,c,4,1
Case #2: 911,645,109,b,87
Case #3: 95,77,#,.,19
Case #4: 99,49,14,8,6,5,2
Thank you to all viewer. Please would you all help me to solve this problem in Java
Here is my Code, I have tried So far.
import java.util.Arrays;
import java.util.Iterator;
import java.util.ArrayList;
class alphaNumeric {
public static void main(String a[]) {
String s1[] = new String[9];
ArrayList l_numList = new ArrayList();
ArrayList l_strList = new ArrayList();
s1[0] = "1000.1";
s1[1] = "100";
s1[2] = "xBC100";
s1[3] = "XBB100";
s1[4] = "TEST";
s1[5] = "AYZ2100";
s1[6] = "99";
s1[7] = "90";
s1[8] = "1000";
System.out.print("Before sorting, numbers are ");
for(int i = 0; i < s1.length; i++)
{
System.out.print(s1[i]+" ");
}
System.out.println();
for (int i = 0; i < s1.length; i++) {
if (isNumber(s1[i])) {
l_numList.add(s1[i]);
} else {
l_strList.add(s1[i]);
}
}
Object[] l_objArray = (Object[]) l_numList.toArray();
int l_intArray[] = new int[l_objArray.length];
for (int i = 0; i < l_objArray.length; i++) {
l_intArray[i] = Integer.parseInt((String) l_objArray[i]);
}
Arrays.sort(l_intArray);
for (int i = 0; i < l_intArray.length; i++) {
System.out.println("after Numsort: " + l_intArray[i]);
}
System.out.print("After sorting, numbers are ");
for(int i = 0; i < l_intArray.length; i++)
{
System.out.print(l_intArray[i]+" ");
}
Object[] l_strArray = (Object[]) l_strList.toArray();
Arrays.sort(l_strArray);
for (int i = 0; i < l_strArray.length; i++) {
System.out.println("after Strsort: " + l_strArray[i]);
}
}
static boolean isNumber(String s) {
String validChars = "0123456789";
boolean isNumber = true;
for (int i = 0; i < s.length() && isNumber; i++) {
char c = s.charAt(i);
if (validChars.indexOf(c) == -1) {
isNumber = false;
} else {
isNumber = true;
}
}
return isNumber;
}
}
I couldn't figure out what you were trying to do, but here's how I'd do it
Extract a List of only the Integers AND create List of indexes at which they occur in original array
Sort that List using standard reverse sort
Put sorted List values back into the original array, using index List
Working example
public class SortOnlyNumbers {
public static void main(String[] args) {
sortOnlyNumbers(new String[] { "d", "1", "4", "c", "9", "6" });
sortOnlyNumbers(new String[] { "109", "87", "911", "b", "645" });
sortOnlyNumbers(new String[] { "77", "19", "#", ".", "95" });
sortOnlyNumbers(new String[] { "8", "99", "14", "2", "5", "6", "49" });
}
private static void sortOnlyNumbers(String[] array) {
List<Integer> indexes = new ArrayList<Integer>();
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
try {
numbers.add(Integer.parseInt(array[i]));
indexes.add(i);
} catch (NumberFormatException e) {
// don't care
}
}
Collections.sort(numbers, Collections.reverseOrder());
for (int i = 0; i < numbers.size(); i++) {
array[indexes.get(i)] = String.valueOf(numbers.get(i));
}
System.out.println(Arrays.toString(array));
}
}
Output
[d, 9, 6, c, 4, 1]
[911, 645, 109, b, 87]
[95, 77, #, ., 19]
[99, 49, 14, 8, 6, 5, 2]

Iterating two lists same time which have different size

I have two list X,Y.
Which are lists of Strings .
there is a possibility to have the two lists different sizes .
If both lists are of same size of 2 then i can procedd like
for (int i =0; i<anyList.size(); i++){
system.out.printLn(X(i) +" "+Y(i));
}
example result :
stringX1 stringY1
stringX2 stringY2
how can i handle the loop which have different sizes
example result should be look like this
example result :
stringX1 stringY1
stringX2 stringY2
stringX3
stringX4
Iterator<String> x_it = x.iterator();
Iterator<String> y_it = y.iterator();
while(x_it.hasNext() && y_it.hasNext()){
System.out.println(x.next() + " " + y.next())
}
while(x_it.hasNext()){
System.out.println(x.next());
}
while(y_it.hasNext()){
System.out.println(y.next());
}
for (int i =0; i<max(X.size(),Y.size()); i++){
if(i<X.size() && i<Y.size()) {
print(X.get(i) + " " + Y.get(i));
} else if(i<Y.size()) {
print(Y.get(i));
} else {
print(X.get(i));
}
}
Programming a max(int, int) and print(String) method shouldn't be to hard.
if(arr1.size()>=arr2.size())
max = arr1.size();
else
max = arr2.size();
for(int i=0;i<max;i++)
{
if(arr1.size() >= i+1)
System.out.println(arr1.get(i));
if(arr2.size() >= i+1)
System.out.println(arr2.get(i));
}
public static void main(String[] args) {
List<String> l1 = new ArrayList<String>();
l1.add("Pif");
l1.add("Paf");
l1.add("Pouf");
List<String> l2 = new ArrayList<String>();
l2.add("Argh!");
l2.add("Aie!");
Iterator<String> it1 = l1.iterator();
Iterator<String> it2 = l2.iterator();
String s1, s2;
while (it1.hasNext() || it2.hasNext()) {
if (it1.hasNext()) {
s1 = it1.next();
System.out.print(s1 + " - ");
}
if (it2.hasNext()) {
s2 = it2.next();
System.out.print(s2);
}
System.out.println();
}
}
Which yields:
Pif - Argh!
Paf - Aie!
Pouf -
int size = x.size() > y.size ? x.size() : y.size();
for (int i =0; i< size ; i++)
{
System.out.printLn( ( x.size() > i + 1 ? X(i) : "") +" "+( y.size() > i + 1 ? Y(i) : "") );
}
List<String> shorter = Arrays.asList("red", "blue");
List<String> longer = Arrays.asList("one", "two", "three", "four");
int size = Math.max(shorter.size(), longer.size());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
if (shorter.size() > i) {
sb.append(shorter.get(i)).append('\t');
} else {
sb.append("\t\t");
}
if (longer.size() > i) {
sb.append(longer.get(i));
}
sb.append('\n');
}
System.out.println(sb.toString());
output
red one
blue two
three
four

Java count occurrence of each item in an array

Is there any method for counting the occurrence of each item on an array?
Lets say I have:
String[] array = {"name1","name2","name3","name4", "name5"};
Here the output will be:
name1 1
name2 1
name3 1
name4 1
name5 1
and if I have:
String[] array = {"name1","name1","name2","name2", "name2"};
The output would be:
name1 2
name2 3
The output here is just to demonstrate the expected result.
List asList = Arrays.asList(array);
Set<String> mySet = new HashSet<String>(asList);
for(String s: mySet){
System.out.println(s + " " + Collections.frequency(asList,s));
}
With java-8, you can do it like this:
String[] array = {"name1","name2","name3","name4", "name5", "name2"};
Arrays.stream(array)
.collect(Collectors.groupingBy(s -> s))
.forEach((k, v) -> System.out.println(k+" "+v.size()));
Output:
name5 1
name4 1
name3 1
name2 2
name1 1
What it does is:
Create a Stream<String> from the original array
Group each element by identity, resulting in a Map<String, List<String>>
For each key value pair, print the key and the size of the list
If you want to get a Map that contains the number of occurences for each word, it can be done doing:
Map<String, Long> map = Arrays.stream(array)
.collect(Collectors.groupingBy(s -> s, Collectors.counting()));
For more informations:
Stream
Collectors
Hope it helps! :)
You could use a MultiSet from Google Collections/Guava or a Bag from Apache Commons.
If you have a collection instead of an array, you can use addAll() to add the entire contents to the above data structure, and then apply the count() method to each value. A SortedMultiSet or SortedBag would give you the items in a defined order.
Google Collections actually has very convenient ways of going from arrays to a SortedMultiset.
I wrote a solution for this to practice myself. It doesn't seem nearly as awesome as the other answers posted, but I'm going to post it anyway, and then learn how to do this using the other methods as well. Enjoy:
public static Integer[] countItems(String[] arr)
{
List<Integer> itemCount = new ArrayList<Integer>();
Integer counter = 0;
String lastItem = arr[0];
for(int i = 0; i < arr.length; i++)
{
if(arr[i].equals(lastItem))
{
counter++;
}
else
{
itemCount.add(counter);
counter = 1;
}
lastItem = arr[i];
}
itemCount.add(counter);
return itemCount.toArray(new Integer[itemCount.size()]);
}
public static void main(String[] args)
{
String[] array = {"name1","name1","name2","name2", "name2", "name3",
"name1","name1","name2","name2", "name2", "name3"};
Arrays.sort(array);
Integer[] cArr = countItems(array);
int num = 0;
for(int i = 0; i < cArr.length; i++)
{
num += cArr[i]-1;
System.out.println(array[num] + ": " + cArr[i].toString());
}
}
Using HashMap it is walk in the park.
main(){
String[] array ={"a","ab","a","abc","abc","a","ab","ab","a"};
Map<String,Integer> hm = new HashMap();
for(String x:array){
if(!hm.containsKey(x)){
hm.put(x,1);
}else{
hm.put(x, hm.get(x)+1);
}
}
System.out.println(hm);
}
It can be done in a very simple way using collections
please find the code below
String[] array = {"name1","name1","name2","name2", "name2"};
List<String> sampleList=(List<String>) Arrays.asList(array);
for(String inpt:array){
int frequency=Collections.frequency(sampleList,inpt);
System.out.println(inpt+" "+frequency);
}
Here the output will be like
name1 2
name1 2
name2 3
name2 3
name2 3
To avoid printing redundant keys use HashMap and get your desired output
I would use a hashtable with in key takes the element of the array (here string) and in value an Integer.
then go through the list doing something like this :
for(String s:array){
if(hash.containsKey(s)){
Integer i = hash.get(s);
i++;
}else{
hash.put(s, new Interger(1));
}
Count String occurence using hashmap, streams & collections
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class StringOccurence {
public static void main(String args[]) {
String[] stringArray = { "name1", "name1", "name2", "name2", "name2" };
countStringOccurence(stringArray);
countStringOccurenceUsingStream(stringArray);
countStringOccurenceUsingCollections(stringArray);
}
private static void countStringOccurenceUsingCollections(String[] stringArray) {
// TODO Auto-generated method stub
List<String> asList = Arrays.asList(stringArray);
Set<String> set = new HashSet<String>(asList);
for (String string : set) {
System.out.println(string + " --> " + Collections.frequency(asList, string));
}
}
private static void countStringOccurenceUsingStream(String[] stringArray) {
// TODO Auto-generated method stub
Arrays.stream(stringArray).collect(Collectors.groupingBy(s -> s))
.forEach((k, v) -> System.out.println(k + " --> " + v.size()));
}
private static void countStringOccurence(String[] stringArray) {
// TODO Auto-generated method stub
Map<String, Integer> map = new HashMap<String, Integer>();
for (String s : stringArray) {
if (map.containsKey(s)) {
map.put(s, map.get(s) + 1);
} else {
map.put(s, 1);
}
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " --> " + entry.getValue());
}
}
}
Here is my solution -
The method takes an array of integers(assuming the range between 0 to 100) as input and returns the number of occurrences of each element.
let's say the input is [21,34,43,21,21,21,45,65,65,76,76,76].
So the output would be in a map and it is: {34=1, 21=4, 65=2, 76=3, 43=1, 45=1}
public Map<Integer, Integer> countOccurrence(int[] numbersToProcess) {
int[] possibleNumbers = new int[100];
Map<Integer, Integer> result = new HashMap<Integer, Integer>();
for (int i = 0; i < numbersToProcess.length; ++i) {
possibleNumbers[numbersToProcess[i]] = possibleNumbers[numbersToProcess[i]] + 1;
result.put(numbersToProcess[i], possibleNumbers[numbersToProcess[i]]);
}
return result;
}
There are several methods which can help, but this is one is using for loop.
import java.util.Arrays;
public class one_dimensional_for {
private static void count(int[] arr) {
Arrays.sort(arr);
int sum = 0, counter = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[0] == arr[arr.length - 1]) {
System.out.println(arr[0] + ": " + counter + " times");
break;
} else {
if (i == (arr.length - 1)) {
sum += arr[arr.length - 1];
counter++;
System.out.println((sum / counter) + " : " + counter
+ " times");
break;
} else {
if (arr[i] == arr[i + 1]) {
sum += arr[i];
counter++;
} else if (arr[i] != arr[i + 1]) {
sum += arr[i];
counter++;
System.out.println((sum / counter) + " : " + counter
+ " times");
sum = 0;
counter = 0;
}
}
}
}
}
public static void main(String[] args) {
int nums[] = { 1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 5, 5, 5, 5, 6 };
count(nums);
}
}
You can do it by using Arrays.sort and Recursion. The same wine but in a different bottle....
import java.util.Arrays;
public class ArrayTest {
public static int mainCount=0;
public static void main(String[] args) {
String prevItem = "";
String[] array = {"name1","name1","name2","name2", "name2"};
Arrays.sort(array);
for(String item:array){
if(! prevItem.equals(item)){
mainCount = 0;
countArray(array, 0, item);
prevItem = item;
}
}
}
private static void countArray(String[] arr, int currentPos, String item) {
if(currentPos == arr.length){
System.out.println(item + " " + mainCount);
return;
}
else{
if(arr[currentPos].toString().equals(item)){
mainCount += 1;
}
countArray(arr, currentPos+1, item);
}
}
}
You can use Hash Map as given in the example below:
import java.util.HashMap;
import java.util.Set;
/**
*
* #author Abdul Rab Khan
*
*/
public class CounterExample {
public static void main(String[] args) {
String[] array = { "name1", "name1", "name2", "name2", "name2" };
countStringOccurences(array);
}
/**
* This method process the string array to find the number of occurrences of
* each string element
*
* #param strArray
* array containing string elements
*/
private static void countStringOccurences(String[] strArray) {
HashMap<String, Integer> countMap = new HashMap<String, Integer>();
for (String string : strArray) {
if (!countMap.containsKey(string)) {
countMap.put(string, 1);
} else {
Integer count = countMap.get(string);
count = count + 1;
countMap.put(string, count);
}
}
printCount(countMap);
}
/**
* This method will print the occurrence of each element
*
* #param countMap
* map containg string as a key, and its count as the value
*/
private static void printCount(HashMap<String, Integer> countMap) {
Set<String> keySet = countMap.keySet();
for (String string : keySet) {
System.out.println(string + " : " + countMap.get(string));
}
}
}
This is a simple script I used in Python but it can be easily adapted. Nothing fancy though.
def occurance(arr):
results = []
for n in arr:
data = {}
data["point"] = n
data["count"] = 0
for i in range(0, len(arr)):
if n == arr[i]:
data["count"] += 1
results.append(data)
return results
you can find using HashMap with simple technic
public class HashMapExample {
public static void main(String[] args) {
stringArray();
}
public static void stringArray()
{
String[] a = {"name1","name2","name3","name4", "name5"};
Map<String, String> hm = new HashMap<String, String>();
for(int i=0;i<a.length;i++)
{
String bl=(String)hm.get(a[i]);
if(bl==null)
{
hm.put(a[i],String.valueOf(1));
}else
{
String k=hm.get(a[i]);
int j=Integer.valueOf(k);
hm.put(a[i],String.valueOf(j+1));
}
}
//hm.entrySet();
System.out.println("map elements are "+hm.toString());
}
}
You could use
for (String x : array){
System.out.println(Collections.frequency(array,x));
}
You can use HashMap, where Key is your string and value - count.
// An Answer w/o using Hashset or map or Arraylist
public class Count {
static String names[] = {"name1","name1","name2","name2", "name2"};
public static void main(String args[]) {
printCount(names);
}
public static void printCount(String[] names){
java.util.Arrays.sort(names);
int n = names.length, c;
for(int i=0;i<n;i++){
System.out.print(names[i]+" ");
}
System.out.println();
int result[] = new int[n];
for(int i=0;i<n;i++){
result[i] = 0;
}
for(int i =0;i<n;i++){
if (i != n-1){
for(int j=0;j<n;j++){
if(names[i] == names[j] )
result[i]++;
}
}
else if (names[n-2] == names[n-1]){
result[i] = result[i-1];
}
else result[i] = 1;
}
int max = 0,index = 0;
for(int i=0;i<n;i++){
System.out.print(result[i]+" ");
if (result[i] >= max){
max = result[i];
index = i;
}
}
}
}
public class Main
{
public static void main(String[] args) {
String[] a ={"name1","name1","name2","name2", "name2"};
for (int i=0;i<a.length ;i++ )
{
int count =0;
int count1=0;
for(int j=0;j<a.length;j++)
{
if(a[i]==a[j])
{
count++;
}
}
for(int j=i-1;j>=0 ;j--)
{
if(a[i]==a[j])
{
count1++;
}
}
if(count1 ==0)
{
System.out.println(a[i]+" occurs :"+count);
}
}
}
}
import java.util.HashMap;
import java.util.Map;
public class FrequencyUsingMap {
public static void main(String[] args) {
int a[] = {1,1,1,1,2,2,3,4,1};
int num = 0;
int maxfreq = 0;
int maxnum =0;
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i<a.length; i++){
num = a[i];
if(map.containsKey(num)){
int frq = map.get(num);
frq++;
map.put(num, frq);
if(frq>maxfreq){
maxfreq = frq;
maxnum = num;
}
}else{
map.put(num, 1);
}
}
System.out.println(map);
System.out.println("number "+ maxnum + " having max frequency " +maxfreq);
}
}
I wrote an easy solution for this, have a look:
public class Plus_Minus {
public static void main(String[] args) {
double [] x = { -4, 3, -9, -5, 4, 1 };
double p = 0;
double n = 0;
int z = 0;
for (int i = 0; i < x.length; i++) {
if (x[i] > 0) {
p += 1;
}
if (x[i] < 0) {
n += 1;
}
if (x[i] == 0) {
z += 1;
}
}
double ppi = p / x.length;
double pni = n / x.length;
int pzi = z / x.length;
System.out.println(ppi);
System.out.println(pni);
System.out.println(pzi);
}
}
public class test {
static String uniq[];
public static String[] convertWordArray(String str) {
str = str.toLowerCase();
String test[] = str.split(" ");
return test;
}
public static void findRepetitiveWordsinString(String str) {
String[] test =convertWordArray(str);
int len = test.length;
int count;
List<Integer> l = new ArrayList<>();
for (int i = 0; i < len; i++) {
count = 1;
for (int j = i + 1; j < len; j++) {
if (test[i].equals(test[j])) {
count++;
test[j] = "0";
}
}
if (count > 1 && test[i] != "0") {
System.out.println(test[i]);
l.add(i);
}
}
System.out.println("Repetitive words at index :" +l);
uniq = new String[l.size()];
for (int i = 0; i < l.size(); i++) {
uniq[i] = test[l.get(i)];
}
System.out.println("Number of words that are repeated: " + uniq.length);
}
public static void countMatches(String a[], String b[]) {
int count;
for (int i = 0; i < a.length; i++) {
count = 0;
for (int j = 0; j < b.length; j++) {
if (a[i].equals(b[j]))
count++;
}
if (count > 1) {
System.out.println("Repeating word is: " + a[i] + " and the repeating count is " + count);
}
}
}
public static void main(String[] args) {
String str;
Scanner scanner = new Scanner(System.in);
str = scanner.nextLine();
findRepetitiveWordsinString(str);
countMatches(uniq, convertWordArray(str));
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class MultiString {
public HashMap<String, Integer> countIntem( String[] array ) {
Arrays.sort(array);
HashMap<String, Integer> map = new HashMap<String, Integer>();
Integer count = 0;
String first = array[0];
for( int counter = 0; counter < array.length; counter++ ) {
if(first.hashCode() == array[counter].hashCode()) {
count = count + 1;
} else {
map.put(first, count);
count = 1;
}
first = array[counter];
map.put(first, count);
}
return map;
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] array = { "name1", "name1", "name2", "name2", "name2",
"name3", "name1", "name1", "name2", "name2", "name2", "name3" };
HashMap<String, Integer> countMap = new MultiString().countIntem(array);
System.out.println(countMap);
}
}
Gives you O(n) complexity.

Categories