Count of Each Alphabet using Array - java

I have a string as an input eg. Testerty. I want to find the count of each alphabet in the string. I have tried using a HashMap. But I want to implement this using array.
Can you please suggest some way.

You can use ASCII to assign the letters number values:
int[] letters = new int[128]; // There are 128 different possible characters.
for(int i = 0; i < input.length; i++) {
char current = input.charAt(i);
int index = Character.getNumericValue(char);
letters[index]++;
}

ArrayList<Character> ch = new ArrayList<Character>();
ArrayList<Integer> count = new ArrayList<Integer>();
someMethod(String input) {
for(char c : input.toCharArray()) {
if(ch.indexOf(c) != -1) {
i.set(ch.indexOf(c), i.get(ch.indexOf(c))+1);
} else {
ch.add(c);
i.add(1);
}
}
}

doing it with a Map is easier, where the letters are keys and the values are counts. Using an array is more tricky; you could assign each letter a number, and use that number as an index into the array, and store the counts in the array. So 'A' is 1, 'B' is 2, etc....The algorithm is
Get next letter of string.
Get the index for the letter.
Increment the value at that index in the array by 1.
Of course you need to do null checking and whatever.
Note that this is logically a Map. It's just when you use a Map, the Map does step 2 above for you.

You should use a collection implementing Multiset iunterface, i.e. HashMultiset (both taken from Google Guava library). Multiset is designed to hold counts for objects in collection:
Multiset<String> m = HashMultiset.create(Arrays.asList("a", "a", "b", "c", "b", "a"));
// m.toString() prints "a x 3, b x 2, c x 1"
// m.count() gives 6

One way could be, you first create an array, then traverse string using charAt(index) method ,match the current char against those in the array.If you find the match ,increment the value there,or add it as a new entry in the array.

Related

How can I concat two characters to form another character?

I have an arraylist which has a list of characters. Now I want to append another character to a certain character from the list (not to form a String,but a character). How do I do that?
Example- Suppose my arraylist has the elements [E,X,Y,M,...]. Now I want to concat another character called 'X' with E.
My code:
for (int i = 0; i < ar.length; i++) {
if (i == 1) {
list.add(ar[i-1]+'X');
}
}
How can I concat two characters to form another character?
You can't. A character is just that: one character.
When you want to concat characters, you automatically, by definition create a string (which represents a sequence of characters).
As you already know the index you care about, a simple
String result = yourList.get(0) + "X";
should do. (iterating a list to retrieve one element at a known index is a bad idea, just get the value at the index you already know).
And note: lists and array in java start at index 0, not 1. 'E' in your example list has index 0, not 1!
Try below code,
char[] ar = { 'E', 'X', 'Y', 'M' };
List<String> list = new ArrayList<>();
for (int i = 0; i < ar.length; i++) {
if (i == 1) {
list.add(String.valueOf(ar[i - 1]) + 'X');
}
}
System.out.println(list);
Output
[EX]
You can use this code
ArrayList<String> list = new ArrayList<String>();
list.add("E");
list.add("X");
list.add("Y");
list.add("M");
//Printing List
for(int i=0;i<list.size();i++)
{
System.out.print(list.get(i));
}
System.out.println();
//Adding Character X with E
list.add(1, "X");
//Printing List
for(int i=0;i<list.size();i++)
{
System.out.print(list.get(i));
}
It will make the list elements as follows - {E, X, X, Y, M}
"char" is just a "char"!
char holds up to 16-bits (2 bytes) of a single Unicode character.
That means you cannot combine two chars as a "char" (Impossible!)
Your list is qualified to hold "chars" only not "Strings".
"String" make sense!
You can use "StringBuilder" to concatenate two chars, but that would produce a "String", not a "char".
My advice to you is to strengthen your conceptual knowledge of Java.

Java for loop with char arrays dis-function

I'm stuck with a loop issue here, I'm working on a script who will receive let's say the String "geij" or "abab" and will have to turn it into a double like "6478" or "0101". I do the conversion from letter to number thanks to a two-dimensional array :
String crypt = "geij";
char twoD[][] = {{'a','b','c','d','e','f','g','h','i','j'}, {'0','1','2','3','4','5','6','7','8','9'}};
First I pass the String into a char array :
char tab[] = crypt.toCharArray();
Then I use a loop to convert from letter to number :
for(int c=0;c<tab.length;c++) {
for(int z=0;z<twoD.length;z++) {
if(tab[c] == twoD[0][z]) {
tab[c] = twoD[1][z];
}
}
Then I create a new instance of String named 'second' to turn the array into a String
String second = new String(tab);
And I turned this String into a double
double finalC = Double.parseDouble(second);
The issue is with this loop, If the String crypt is "abab", the loop will return 0101 as it is supposed to, but if the String contains any letter after "a" or "b" from the first array of the two-dimensional array, like for example the String "geij" the program will simply return "geij".
I don't understand why the program doesn't go further than b and it is starting to give me an egghead. If anyone has an idea I'll be grateful !
Here is an example of the inside of the tab array after the loop for the String "abcd" :
Indice : 0 value: 0
Indice : 1 value: 1
Indice : 2 value: c
Indice : 3 value: d
Kevin Cruijssen resolves your problem but you can more:
Use HashMap to this problem. For now, your algorithm time complexity is O(n*m) (n-base string length, m - amount of letters in the table) because you must iterate through the whole array of letters for each letter.
Using HashMap you can find the right letter in O(1). A lot faster. So now your algorithm has O(n) time complexity.
Simple example:
Map<Character, Integer> encoding = new HashMap<>();
encoding.put('a', 0);
encoding.put('b', 1);
encoding.put('c', 2);
encoding.put('d', 3);
String toEncode = "abcd";
char[] chars = toEncode.toCharArray();
StringBuilder sb = new StringBuilder();
for(char c : chars){
int newInt = encoding.getOrDefault(c, -5); //-5 is just a flag that there is no char to encode
if(newInt == -5){
continue; //or do something else, e.g throw exception;
}
sb.append(newInt);
}
System.out.println(sb.toString());
//Parse double if you want, but remember that what *Nikolas* said in the comments under your post.
//Double.parseDouble(sb.toString());
The problem is in your inner loop: twoD.length is 2, because twoD contains your two inner array of characters.
You should use twoD[0].length instead:
for(int c=0; c<tab.length; c++) {
for(int z=0; z<twoD[0].length; z++) {
...
However, since you are using all ten digits, perhaps better to use that instead:
char twoD[][] = {{'a','b','c','d','e','f','g','h','i','j'}, {'0','1','2','3','4','5','6','7','8','9'}};
int amountOfDigitsUsed = 10; // Equal to `twoD[0].length` or `twoD[1].length`.
for(int c=0; c<tab.length; c++) {
for(int z=0; z<amountOfDigitsUsed; z++) {
...
Regardless whether you use a hard-coded twoD conversion and amountOfDigits used or not. In your current implementation your twoD.length is 2, causing the issues you have right now.
Length of your twoD array is 2. Your second loop should iterate from z = 0 to twoD[0].length.
Try naming your variables meaningfully so it will be easier to find bugs like this. Also check out foreach loops so you don't have to worry about indexes. Java Maps could be better for mapping characters to numbers.
Since it seems as though in your case the characters are incrementing along with their int values, you don't need a map at all. You can cast the character to an int, and then subtract a's int value. This is a slight variation of B_Osipiuk's answer:
String toEncode = "abcd";
char[] chars = toEncode.toCharArray();
StringBuilder sb = new StringBuilder();
for(char c : chars){
int newInt = c - 'a';
if (newInt < 0 || newInt > ('j'-'a')) {
continue; //or do something else, e.g throw exception;
}
sb.append(newInt);
}
System.out.println(sb.toString());

Is there an array_intersect() equivalent in java?

I want to find the first repeated character from a string. I usually do it using array_intersect in php. Is there something similar in Java?
For example:
String a=zxcvbnmz
Desired output : z
array_intersect — Computes the intersection of arrays (source)
So in this case you can use Set::retainAll :
Integer[] a = {1,2,3,4,5};
Integer[] b = {2,4,5,6,7,8,9};
Set<Integer> s1 = new HashSet<>(Arrays.asList(a));
Set<Integer> s2 = new HashSet<>(Arrays.asList(b));
s1.retainAll(s2);
Integer[] result = s1.toArray(new Integer[s1.size()]);
System.out.println(Arrays.toString(result));
Output
[2, 4, 5]
You can read about this here Java, find intersection of two arrays
There's no default implementation for this behavior; however, you can code your own solution! Since you want to find the first repeated character, you can make a HashSet of Characters. As you iterate through the array, you add each character to the HashSet until you come across a character already in the HashSet - this must be the first repeated character. Example code below:
public char arrayIntersect(String string) {
HashSet<Character> hashSet = new HashSet<>();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (hashSet.contains(c))
return c;
else
hashSet.add(c);
}
return null;
}
This runs in O(n) time, as HashSet lookups run in O(1) time.

multiply string element per int element from two arrays Java

I am learning Java and looking for a comprehensive code of multiplying the elements from 2 arrays, possibly without importing anything to achieve it.
In Python it's quite easy:
a=['a','b','c','d']
b=[1,2,3,4]
[x*y for x,y in zip(a,b)]
['a', 'bb', 'ccc', 'dddd']
How can I achieve the same thing in Java, when the first array is an array of strings and the second is integers?
I'm afraid Java isn't going to support this kind of thing natively, and you'll need to perform some of your own logic to implement it. Let's say you've got your String[]..
String[] a = {"a", "b", "c", "d"};
And you've got your int[]..
int[] b = {1,2,3,4};
Next, you'll need to check that the arrays are the same size.
if(a.length == b.length) {
// Continue.
}
Then you need to implement a loop, to go through each item in the arrays.
for(int x = 0; x < a.length; x++)
{
// Some looping code.
}
And you're going to grab each item.
String value = a[x];
int multiplier = b[x];
If you're not importing anything, you declare the total value:
String total = "";
But if you're allowing for a StringBuilder, then you'll import it and declare..
StringBuilder total = new StringBuilder();
NOTE: StringBuilder is strongly recommended here.
And then you're looping multiplier amount of times..
for(int y = 0; y < multiplier; y++)
{
// If you use StringBuilder..
total.append(value);
// If you don't..
total += value;
}
// If you use StringBuilder..
a[x] = total.toString();
// If you don't...
a[x] = total;
This will set the value of a[x] to the repeated String.
NOTE: Something that's also important is leaning good practise. If you're using Java code, it's considered terrible practise to repeatedly concatenate String objects. StringBuilder is more efficient, and is the Java standard. I would strongly recommend using this.
Have fun putting it all together!!
To create string filled with multiple instances of same character like "ccc" you can firs create array of characters which will hold only 3 characters like
char[] myCharacters = new char[3];
Now this array is filled with zeroes ('\0'), so you need to fill it with desired character 'c'. You simply do it using for loop
for (int i = 0; i<myCharacters; i++){
myCharacters[i] = 'c';
}
After this your array will contain ['c', 'c', 'c'].
Now you can use this array to create string using characters from it. To do so you just need to pass this array to String constructor like
String myString = new String(myCharacters);
And there you go. Now you have "ccc" String. Repeat these steps for each pair of elements from a and b arrays.
You can also use shorter version which kinds of do the same
String myString = new String(new char[3]).replace('\0','c');//will produce "ccc"

Compare two arrays of a different type, print element in the same "slot" Java

so i am working on comparing two arrays based on a users input. One array is an int array, the other is a string. What i want to do is take a users input, compare the input to the first int array, then calculate the element within the same position of the string array. then print out my results based on the second array.
Like below i would input 12 then get bob or 21 then get andrea. Example code below. I have everything up to the comparison of the second array (i have the user input, finding it within the int array - the loop, but i just cant figure out the comparison to the second array)
int[] number = {12, 15, 19, 21}
String[] character = {bob, sally, james, andrea}
would i just compare both the arrays then save it in a new variable:
number = character
then print the new variables value?
thanks for the help. i have been searching everywhere for this one. mainly spend a day and a half on this website.
You can you use a Map here.
Instantiate and populate the map:
Map<Integer, String> numberToNameMap = new HashMap<Integer, String>();
numberToNameMap.put(12, "bob");
//...
And then do a lookup:
String name = numberToNameMap.get(inputNumber);
You do not need to compare anything to the second array: once you have the index of the matching element in the first array, simply use that index against the second array. That's all there is to it!
int[] number = {12, 15, 19, 21};
String[] character = {"bob", "sally", "james", "andrea"};
int userInput = ... // <<== You know how to do all that
for (int i = 0 ; i != number.length ; i++) {
if (number[i] == userInput) {
// Element at index i is matching:
System.out.println(character[i]);
break;
}
}

Categories