maximum occuring character using hash table - java

My code is working fine and dispaly the count of maximum occuring character but not display the maximum character.
Also tell me smart way of writing code i am beginner
void checkMax1(String str1){
final int hash=256;
char max_occ=str1.charAt(0);
int asc[]=new int[hash];
int n=str1.length(),max_count=-1;
char Chars[]=str1.toCharArray();
for(int i=0;i<n;i++){
asc[Chars[i]]++;
}
for(int i=0;i<hash;i++){
if(max_count<asc[i]){
max_count=asc[i];
max_occ=(char)asc[i];
System.out.println(asc[i]);
}
}
System.out.println(max_count+""+max_occ);
}
}

Just change the line saving the character to
max_occ = (char) i;
the index is the code of the character, the value in asc the count for that character.
The variable names of your code are kind of hard to understand, maybe a bit better (IMHO):
final int MAX = 255;
int[] count = new int[MAX];
char maxChar = ...
int maxCount = -1;
and variables, by convention, start with lower case, Class and Interface names with upper case...

You just need an extra if
if(max_count<asc[i]){
max_count=asc[i];
System.out.println(asc[i]);
if(max_occ<(char)asc[i]){
max_occ=(char)asc[i]
}
}

you can catch it in same first loop
for (int i=0; i<n; i++)
if (++asc[Chars[i]] > max_occ) {
++max_occ;
max_char = Chars[i];
}

Related

How to Optimise a given problem time complexity?

I have a question which says
Given an input
ababacad
The output should be all the a's should come first together rest characters should follow their sequence as they were originally. i.e.
aaaabbcd
I solved it like below code
String temp="", first="" ;
for(int i=0;i<str.length;i++) {
if(str.charAt(i)!='a')
temp=temp+str.charAt(i);
else
first=first+str.charAt(i);
}
System.out.print(first+temp);
The output matches but it says it is still not optimised. I guess its already order of N complexity. Can it be optimised further.
Optimization here can mean string operations as well as the number of iterations. So, just to be on the safe side, you can implement it using arrays. The time complexity will be O(n) which is the minimum for this problem as you have to check every position for the presence of char 'a'.
String input = "ababacad";
char[] array = input.toCharArray();
char[] modified = new char[array.length];
int a = 0; // index for a
int b = array.length - 1; // index for not a
for (int i = array.length - 1; i >= 0; --i) {
if (array[i] != 'a')
modified[b--] = array[i];
else
modified[a++] = array[i];
}
String output = new String(modified);
System.out.println(output);

Using HashMaps to find string frequencies

My code is meant to find the most frequent codon from a file that contains a lonf string of DNA (i.e. CTAAATCGATGGCGATGATAAATG...). starting at the initial position pos, every three characters makes up one codon. The problem I have is that whenever I run the code, it tell me that the string index is out of range. I know that the issue is in the line
str = line.substring(idx, idx + 2);
but don't know how to fix it. Also, I am not sure whether I am counting frequencies correctly. I needed to increment the value of every key that is seen more than once.
public static void findgene(String line){
int idx, pos;
int[] freq = new int[100];
String str;
//pos is the position to start at
pos = 0;
idx = pos;
for(int i = 0; i < line.length(); i++){
if(idx >= 0){
//makes every three characters into a codon
str = line.substring(idx, idx + 2);
//checks if the codon was previously seen
if(genes.containsKey(str)){
genes.put(str, freq[i]++);
}
idx = idx + 2;
}
}
}
You are incrementing idx by 2 with each iteration of the loop. However, you did not impose any restriction on the upper limit of idx.
Thus the the parameter of the substring() function soon goes out of range in the line:
str = line.substring(idx, idx + 2);
What you need to do is change the condition to:
if(idx+2<=line.length()){
//code here
}

Sum of char array in Java

I have a little trouble of calculating sum of elements in char array. I tried like this but it does not give what I expect:
int count1=0;
char [] charArray1={1,2,35,0};
for (int i =0; i<charArray.length; i++){
count1=count1+charArray1[i];
}
I'm getting Exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 105
at CountDigits.main(CountDigits.java:31)
Any hint please?
In the first place, you should be using an int array instead of char array if your data is purely numberic.
int[] data = {1,2,35,0};
Secondly, your addition in the iteration is incorrect.
int sum;
for(int x=0; x<data.length ;x++)
sum += data[x]; //This is enough to get the sum.
At the moment, I cannot think of any good reason to use char array to store an array of numbers. But if you have to do it for some mysterious reasons, you can do it this way.
char[] data = {'1', '2', '3', '0'}; //Enclose each char with single quote
int sum;
for(int x=0; x<data.length ;x++)
sum += Character.getNumericValue(data[x]); //Convert char to int before summing
You need to change the for loop as follows where I have change the charArray to charArray1 and line in for loop
for (int i =0; i<charArray1.length; i++){
count1=count1+charArray1[i];
}
count1=charArray1['i']+charArray1['i']; is wrong.
what you need is
count1 = count1 + charArray1[i];
Change this -
for (int i = 0; i < charArray.length; i++){
count1 = charArray1['i'] + charArray1['i'];
}
to this -
for (int i = 0; i < charArray.length; i++){
count1 = count1 + charArray1[i];
}
In Java, we cannot use a character or string literal for indexing an array. Only numbers are allowed. Since i is an integer, you need to use it directly as the index.
As T. J. Crowder pointed out in the comment - in order to get the sum of all the numbers, you need what is called an accumulator into which you will collect the result of the sum. In every loop iteration, you need to add the next element to this accumulator result so that in the end, it will hold the result of -
charArray1[0] + charArray1[1] + charArray1[2] + charArray1[3]
Try:
public int add(char[] numbers) {
int result = 0;
for (char i : numbers) {
if(Character.isDigit(i)){
result += Character.getNumericValue(i);
}
}
return result;
}
A little late to answer, but nevertheless, change your code to something below -
int count1 = 0;
char [] charArray1 = {1,2,35,0};
for (int i =0; I < charArray1.length; i++)
{
count1 = count1 + charArray1[i];
}
System.out.println("sum is " + count1);
This code can further be optimized, but if you simply want to fix the error, then try below.

Counting lower case letters in a string and printing out their occurrence in the form of a histogram?

I am currently trying to write a program where the user will input a string and then the program will output the occurrence of lowercase letters as such:
"Hello world! The quick brown fox jumps over the fence."
a:
b:*
c:**
d:*
e:*****
f:**
g:
h:***
... so on until z.
I just have no idea how to go about writing this. I've looked around but no one uses arrays. I was thinking you have an array for the alphabet and then have a loop that takes each element of the string and corresponds it with a letter of the alphabet, which then adds one to the counter which wil ultimately display the histogram.
Just not sure how to go about it.
Thanks.
EDIT: Here's what I have so far. It's not much and I still don't really understand what to do. But it's something.
import java.util.Scanner;
public class CountingChars {
public static void main(String[] args) {
System.out.println("Enter the text you would like to count the characters of. Please end with a blank line.");
Scanner sc = new Scanner(System.in);
String userInput = sc.nextLine();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
int[] amount = new int[alphabet.length()];
//for (int i = 0; i < userInput.length();i++){
//}
char occurrence;
int count = 0;
while(userInput.length()>0){
occurrence = userInput.charAt(0);
int i = 0;
while(i < userInput.length() && userInput.charAt(i) == occurrence){
count++;
}
}
}
}
Two basic ways of doing this which come to mind.
First is using an array of fixed length with stored ints (lower alph chars), where 'a' is on index 0. And then iterate through the given chararray updating the specific index (you can get the index by something like 'selectedChar' - 'a', which will give you the index position). Then you simply iterate through the list a print number of asterisks accordingly.
Second way is using a HashMap, where you store per each character the value, count the chars, update the value in the map accordingly and then simply go through the map and print those out (now that I am thinking about it, SortedMap will be better).
public static void printAlphabetHistogram(String input) {
int amount[] = new int[25];
for(char c : input.toCharArray()) {
if(Character.isAlphabetic(c)) {
c = Character.toLowerCase(c);
amount[c - 'a'] += 1;
}
}
for(int i = 0; i < amount.length; i++) {
System.out.printf("%s:", (char)('a' + i));
for(int j = 0; j < amount[i]; j++) {
System.out.print("*");
}
System.out.println();
}
}

Counting occurrences of characters in a word list

I'm trying to make an AI for a hangman game, part of which requires counting all occurrences of each possible character in the word list. I'm planning on culling the word list before this counting to make things run faster (by first culling out all words that are not the same length as the guessable phrase, and then by culling out words that do not match the guessed characters).
The problem I am having is in the code below. Somehow, it always returns a list of e's that are the correct length (matching the number of possible characters). I'm not sure exactly what I'm doing wrong here, but the problem is definitely somewhere in countCharacters.
MethodicComputer(){
guessable = parseGuessable();
wordList = parseText();
priorities = countCharacters(guessable);
}
public char guessCharacter(String hint){
char guess = 0;
System.out.println(guessable);
System.out.println(priorities);
guess = priorities.charAt(0);
priorities = priorities.replaceAll("" + guess, "");
return guess;
}
private String countCharacters(String possibleChars){
charCount = new Hashtable();
String orderedPriorities = "";
char temp = 0;
char adding = 0;
int count = 0;
int max = 0;
int length = possibleChars.length();
for (int i = 0; i<length; i++){
temp = possibleChars.charAt(i);
count = wordList.length() - wordList.replaceAll("" + temp, "").length();
charCount.put(temp, count);
}
while (orderedPriorities.length() < length){
for (int i = 0; i < possibleChars.length(); i++){
temp = possibleChars.charAt(i);
if (max < (int) charCount.get(temp)){
max = (int) charCount.get(temp);
adding = temp;
}
}
orderedPriorities += adding;
possibleChars = possibleChars.replaceAll("" + adding, "");
}
return orderedPriorities;
}
The problem is that I did not update the max variable, so it never entered the if statement and updated the adding variable. A simple addition of
max = 0;
to the end of the while loop fixed it.

Categories

Resources