My Question is-
Input is string. Return true if the String has exactly 1 character that appears twice in the string, 0 character that appear thrice in the string, and at least 1 character that appear four or more times in the string. There is a problem in my code and I am unable to find out the problem.
public class CheckCharacterOccurence {
static String testcase1 = "jjiiiiyy";
public static void main(String[] args) {
CheckCharacterOccurence testInstance = new CheckCharacterOccurence();
boolean result = testInstance.checkCharacterOccurence(testcase1);
System.out.println(result);
}
public boolean checkCharacterOccurence(String str) {
char ch=' ';
char ch1=' ';
int temp=0;
int temp1=0;
int temp2=0;
int count=0;
for(int i=0;i<str.length();i++){
ch=str.charAt(i);
for(int j=i;j<str.length();j++){
if(str.charAt(i)==str.charAt(j)){
ch1=str.charAt(i);
count++;
}
}
System.out.println(count);
if(count==2&&ch!=ch1){
temp++;
}
if(count==3&&ch!=ch1){
temp1++;
}
if(count>=4){
temp2++;
}
count=0;
}
if(temp==1&&temp1==0&&temp2>=1){
return true;
}
return false;
}
}
I would suggest using a map
For all characters in string, increment map[that_char]
At last iterate over map to find how many times each character appeared.
Alternatively you can use array also to keep count.
Something like
int [] ctr = new int[256]
ctr = all zeroes
for (ch : string)
ctr[ch]++
mxocc = 0
maxch = 'a'
for(ch = a, b, c, d, e...)
if(ctr[ch] > maxocc) maxocc = ctr[ch] and maxch = ch
Output require info
hey you can figure out the problem ... atleast i can give to some extend same code , you can check it and try to solve your problem... This program finds the pattern in the string, now you can go through this program, and try to solve ur problem in your program by your own self.and try to do it by your own then only ur coding skills will get improved.and vote this answer if u fing it really helpful
#include<stdio.h>
#include<string.h>
int occur(char[],char[]);
int occur(char sent[],char pattern[])
{
int count=0;
for(int i=0,j=i;sent[i]!='\0';)
{
if(sent[i+j]==pattern[j]&&pattern[j]!='\0')
{
j++;
}
else if(j==strlen(pattern))
{
count++;
i=i+j;
j=0;
}
else
{
i++;
j=0;
}
}
return count;
}
int main()
{
char sent[] = "aabaabaaabbbabababddfggaabbbasab";
char pattern[] = "aba";
int result = occur(sent,pattern);
printf("\nNo of Occurrences --- > %d",result);
return 0;
}
You should simplify your code. For example there is not need to use those complex for-loops, you can use a for-each.
This code finds out the frequency of characters in a string and stores it in a Map.
import java.util.*;
public class CheckCharacterOccurence {
public static void main(String[] args) {
Map<Character, Integer> counting = new HashMap<Character, Integer>();
String testcase1 = "Helloooo";
for(char ch: testcase1.toCharArray()){
Integer freq = counting.get(ch);
counting.put(ch, (freq == null) ? 1 : freq + 1);
}
System.out.println(counting.size() + " distinct characters:");
System.out.println(counting);
}
}
Related
I've been trying to create an algorithm where each letter adds points. I don't want to use charAt, I'd like to use the substring method.
My problem is that String letter does not seem to get each letter and the result is always 0.
Is there a way to get each letter and convert it to points?
public class WDLPoints{
public static void main(String[] args){
String word = "LDWWL";
System.out.println(getMatchPoints(word));
}
public static int getMatchPoints(String word) {
int points = 0;
String letter = word.substring(5);
for (int i = 0; i < word.length(); i++) {
if (letter.equals("W")) {
points+=3;
}
else if (letter.equals("D")) {
points+=1;
}
else {
points = 0;
}
}
return points;
}
}
You may try the following changes in your public static int getMatchPoints(String word) method:
for (int i = 0; i < word.length(); i++) {
String letter = word.substring(i, i + 1);
if (letter.equals("W")) {
points+=3;
}
else if (letter.equals("D")) {
points+=1;
}
}
word.substring(i, i + 1) will get a single letter word and will help you compute your score the way you want.
If you want to make it really simple you can just use String.toCharArray() and then iterate over the array of char and check its value:
public static int getMatchPoints(String word) {
int points = 0;
char[] arr = word.toCharArray();
for (char letter : arr) {
if (letter == 'W') {
points += 3;
}
else if (letter == 'D') {
points += 1;
}
}
return points;
}
I also removed your else statement because that was just setting the value to 0 if there is any other letter in the loop. I think you intended it to be points += 0 which does nothing, so it can just be removed.
Example Run:
Input:
String word = "LDWWL";
Output:
7
Note: I am aware you might not be allowed to use this solution, but I thought it would be good info on the possibilities since it does not technically use charAt()
Also I'd like to point out you misunderstand what substring(5) does. This will return all characters after the position of 5 as a single String, it does not separate the String into different characters or anything.
You will find that your variable letter is always the empty String. Here's a better way of doing things:
class WDLPoints
{
public static void main(String[] args)
{
String word = "LDWWL";
System.out.println(getMatchPoints(word));
}
// We have only one method to encode character values, all in one place
public static int getValueForChar(int c)
{
switch((char)c)
{
case 'W': return 3;
case 'D': return 1;
default: return 0; //all non-'W's and non-'D's are worth nothing
}
}
public static int getMatchPoints(String word)
{
// for all the characters in the word
return word.chars()
// get their integer values
.map(WDLPoints::getValueForChar)
// and sum all the values
.sum();
}
}
Assuming your string represents a football teams performance of the last 5 games, you could keep it simple and readable with something like:
public static int getMatchPoints(String word) {
String converted = word.replace('W', '3').replace('D', '1').replace('L', '0');
return converted.chars().map(Character::getNumericValue).sum();
}
This converts your example input "LDWWL" to "01330" and sums each char by getting its numeric value.
I am solving this question as an assignment of the school. But the two of my test cases are coming out wrong when I submit the code? I don't know what went wrong. I have checked various other test cases and corner cases and it all coming out right.
Here is my code:
public static boolean isPermutation(String input1, String input2) {
if(input1.length() != input2.length())
{
return false;
}
int index1 =0;
int index2 =0;
int count=0;
while(index2<input2.length())
{
while(index1<input1.length())
{
if( input1.charAt(index1)==input2.charAt(index2) )
{
index1=0;
count++;
break;
}
index1++;
}
index2++;
}
if(count==input1.length())
{
return true;
}
return false;
}
SAMPLE INPUT
abcde
baedc
output
true
SAMPLE INPUT
abc
cbd
output
false
A simpler solution would be to sort the characters in both strings and compare those character arrays.
String.toCharArray() returns an array of characters from a String
Arrays.sort(char \[\]) to sort a character array
Arrays.equals(char \[\], char \[\]) to compare the arrays
Example
public static void main(String[] args) {
System.out.println(isPermutation("hello", "olleh"));
System.out.println(isPermutation("hell", "leh"));
System.out.println(isPermutation("world", "wdolr"));
}
private static boolean isPermutation(String a, String b) {
char [] aArray = a.toCharArray();
char [] bArray = b.toCharArray();
Arrays.sort(aArray);
Arrays.sort(bArray);
return Arrays.equals(aArray, bArray);
}
A more long-winded solution without sorting would to be check every character in A is also in B
private static boolean isPermutation(String a, String b) {
char[] aArray = a.toCharArray();
char[] bArray = b.toCharArray();
if (a.length() != b.length()) {
return false;
}
int found = 0;
for (int i = 0; i < aArray.length; i++) {
char eachA = aArray[i];
// check each character in A is found in B
for (int k = 0; k < bArray.length; k++) {
if (eachA == bArray[k]) {
found++;
bArray[k] = '\uFFFF'; // clear so we don't find again
break;
}
}
}
return found == a.length();
}
You have two ways to proceed
Sort both strings and then compare both strings
Count the characters in string and then match.
Follow the tutorial here
In case you String is ASCII you may use the next approach:
Create 256 elements int array
Increment element of corresponding character whenever it's found in string1
Decrement element of corresponding character whenever it's found in string2
If all elements are 0, then string2 is permutation of string1
Overall complexity of this approach is O(n). The only drawback is space allocation for charCount array:
public static boolean isPermutation(String s1, String s2) {
if (s1.length() != s2.length()) {
return false;
}
int[] charCount = new int[256];
for (int i = 0; i < s1.length(); i++) {
charCount[s1.charAt(i)]++;
charCount[s2.charAt(i)]--;
}
for (int i = 0; i < charCount.length; i++) {
if (charCount[i] != 0) {
return false;
}
}
return true;
}
If your strings can hold non-ASCII values, the same approach could be implemented using HashMap<String, Integer> as character count storage
I have a recursive method to solve the permutations problem. I think that this code will seem to be tough but if you will try to understand it you will see the beauty of this code. Recursion is always hard to understand but good to use! This method returns all the permutations of the entered String 's' and keeps storing them in the array 'arr[]'. The value of 't' initially is blank "" .
import java.io.*;
class permute_compare2str
{
static String[] arr= new String [1200];
static int p=0;
void permutation(String s,String t)
{
if (s.length()==0)
{
arr[p++]=t;
return;
}
for(int i=0;i<s.length();i++)
permutation(s.substring(0,i)+s.substring(i+1),t+s.charAt(i));
}
public static void main(String kr[])throws IOException
{
int flag = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the first String:");
String str1 = br.readLine();
System.out.println("Enter the second String:");
String str2 = br.readLine();
new permute_compare2str().permutation(str1,"");
for(int i = 0; i < p; ++i)
{
if(arr[i].equals(str2))
{
flag = 1;
break;
}
}
if(flag == 1)
System.out.println("True");
else
{
System.out.println("False");
return;
}
}
}
One limitation that I can see is that the length of the array is fixed and so will not be able to return values for a large String value 's'. Please alter the same as per the requirements. There are other solution to this problem as well.
I have shared this code because you can actually use this to get the permutations of a string printed directly without the array as well.
HERE:
void permutations(String s,String t)
{
if (s.length()==0)
{
System.out.print(t+" ");
return;
}
for(int i=0;i<s.length();i++)
permutations(s.substring(0,i)+s.substring(i+1),t+s.charAt(i));
}
Value of 's' is the string whose permutations is needed and value of 't' is again empty "".
it will take O(n log n) cuz i sort each string and i used more space to store each one
public static boolean checkPermutation(String a,String b){
return sortString(a).equals(sortString(b));
}
private static String sortString(String test) {
char[] tempChar = test.toCharArray();
Arrays.sort(tempChar);
return new String(tempChar);
}
String checkPermutation(String a,String b){
char[] aArr = a.toCharArray();
char[] bArr = b.toCharArray();
Arrays.sort(aArr);
Arrays.sort(bArr);
if(aArr.length != bArr.length){
return "NO";
}
int p = 0, q = 0;
while(p < aArr.length){
if(aArr[p] != bArr[q]){
return "NO";
}
p++;
q++;
}
return "YES";
}
public static boolean isStringArePermutate(String s1, String s2){
if(s1==null || s2==null) {
return false;
}
int len1 = s1.length();
int len2 =s2.length();
if(len1!=len2){
return false;
}
for(int i =0;i<len1;i++){
if(!s1.contains(String.valueOf(s2.charAt(i)))) {
return false;
}
s1=s1.replaceFirst(String.valueOf(s2.charAt(i)), "");
}
if(s1.equals("")) {
return true;
}
return false;
}
how do I store a void in to an array?
for my example:
count (String text) into int[] letter.
is there a quick and easy opportunity to do it or should I rewrite it completely?
I really appreciate your help
my code:
public static void main (String [] args){
String text="E";
String[] words = split(text);
int[] letter = count(text);
someWords(words, letter);
}
public static int[] count(String text){
int count;
for (char letter=(char)65;letter<=90;letter++){
count=0;
for (int i=0; i<text.length(); i++){
if (letter==text.charAt(I) || (letter+32)==text.charAt(I)){
count++;
}
}
if (count>0){
System.out.println(letter+" = "+count);
}
}
}
I could be wrong, because your question is not very clear, but it seems that what you're trying to do is:
public static int[] count(String text){
int[] counts = new int[26];
// iterate over each letter:
for (char letter='A';letter<='Z';letter++){
int currentIndex = (int) letter - 'A';
// count the occurrences of the current letter:
for (int i=0; i<text.length(); i++){
if (letter==text.charAt(i) || (letter+32)==text.charAt(i)){
counts[currentIndex]++;
}
}
// print the count for the current letter if non-zero
if (counts[currentIndex]>0){
System.out.println(letter+" = " + counts[currentIndex]);
}
}
return counts;
}
There's surely a more efficient way to do this (iterating over the characters in text and incrementing the count index accordingly would be faster than checking all the chars in text 26 times), but the approach works.
I don't really understand why you want to do it like this, but you can just pass the int[] as a paramter.
...
int[] count = new int[1];
count(text, count);
...
public static void count(String text, int[] count){
...
count[0] = ..
}
Reading your code it seems like you just want to return and integer and not an integer array (the number of letters in a String as it seems)
public static int count(String text){
int count;
for (char letter=(char)65;letter<=90;letter++){
count=0; // are you sure you want to set the value of count to 0 every time you loop?
for (int i=0; i<text.length(); i++){
if (letter==text.charAt(i) || (letter+32)==text.charAt(i)){
count++;
}
}
if (count>0){
System.out.println(letter+" = "+count);
}
}
return count;
}
In your main method you write:
String[] words = split(text);
int letter = count(text);
public int count()
{
count = 0;
for ...
...
...
return count;
}
you should use RETURN word at the end of your function, and declare the return type (int, string, ...etc) next to the function name.
You only need to spin through the string once:
public static int[] count(String text) {
int[] totals = new int[26];
for (char c : text.toUpperCase().toCharArray()) {
int idx = (int)c - (int)'A';
if ((idx >= 0) && (idx <= 26)) {
totals[idx]++;
}
}
return totals;
}
As i have tried ,it gives ArrayIndexOutOfBounds Ecxeption and does not print last char
please help me to find bug in my code.or is there any alternate
public static void sequenceCount(String s) {
int counter;
int i=0;
char c;
char[] arr = s.toCharArray();
while(i<arr.length){
counter=0;
c = arr[i];
while(c==arr[i]){
counter++;
i++;
}
System.out.println("letter"+" "+c+":"+"number of times"+counter);
}
}
As i am a novice to java my code may be inefficient
Your inner loop is not bound by the length of the array. Try:
while(i < arr.length && c==arr[i]){
counter++;
i++;
}
This works - you need to ensure that your inner loop doesn't pass beyond the end of the string, and you need to always catch the last letter, too:
public static void sequenceCount(String s) {
char[] arr = s.toCharArray();
int i = 0, n = arr.length;
while (i < n) {
char c = arr[i];
int count = 0;
do {
++i; ++count;
} while (i < n && arr[i] == c);
System.out.println("letter "+ c +":"+"number of times " + count);
}
}
My approach would be to use two for loops.
The first for loop would run a loop with the decimal equivalent of A to Z.
The second for loop would run a loop that runs through the entire character array/string (I'd prefer a string rather than a char array here) and check to see if that given value at that index is equal the the value ran by the first for loop. If they are equal than add one to count. Print.
Don't forget to reset your counter after every run as well.
Similar Topic can be found here: Counting letters in a string using two for-loops
While many answers here are O(n^2), I tried to do it within O(n) time using recursion. This is modified from existing code that I already had so I know the method returns an int, but I don't use it (it's left over from copied code - fix it as you see fit)
public class CountCharSeqRecursive {
private String test = "AAABBA"; // (3)A(2)B(1)A
private StringBuilder runningString = new StringBuilder();
public static void main(String[] args) {
CountCharSeqRecursive t = new CountCharSeqRecursive();
System.out.println(t.getEncryptedValue(t.test));
}
public String getEncryptedValue(String seq){
int startIndex=0;
this.createCounterSeq(seq.charAt(startIndex), seq, startIndex);
return runningString.toString();
}
private int createCounterSeq(char prev, String sequence, int currentIndex){
return createCounterSeq(prev, sequence, currentIndex, 0);
}
private int createCounterSeq(char prev, String sequence, int currentIndex, int count){
if(currentIndex<sequence.length()){
char current = sequence.charAt(currentIndex);
if((prev^current) < 1){
++count;
}else {
this.addToSequence(count, prev);
count = 1;
}
return count += createCounterSeq(current, sequence, ++currentIndex, count);
}
this.addToSequence(count, prev);
return count;
}
private void addToSequence(int count, char ch){
runningString.append("("+count+")").append(ch);
}
}
My solution using HashSet, Works for all cases of a non-empty string.
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<Character> set = new HashSet<Character>();
String input = "aabbcdeaab";
set.add(input.charAt(0));
int count = 1;
StringBuilder output = new StringBuilder("");
for(int i=1;i<input.length();i++) {
char next = input.charAt(i);
if(set.contains(next)) {
count++;
}else {
char prev = input.charAt(i-1);
output.append(Character.toString(prev) + count );
set.remove(prev);
set.add(next);
count=1;
}
}
output.append(Character.toString(input.charAt(input.length()-1)) + count );
System.out.println(output.toString());
}
I want to get a string count any letter in the string how many time it's appeared in the string,and print the letter and the number So that what i did:
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
String str;
Scanner in = new Scanner(System.in);
System.out.println("enter name");
str = in.nextLine();
char[] c1 = str.toCharArray();
int[] f = new int[str.length()];
for(int i=0;i<str.length();i++) {
for(int j=0;j<str.length();j++) {
if(c1[i]==c1[j]) {
f[i]++;
}
}
}
for(int k=0;k<c1.length;k++) {
for(int l=0;l<c1.length;l++) {
if(c1[k]==c1[l]) {
if(l!=k) {c1[k]=0;f[k]=0;}
}
}
System.out.println(c1[k]+"="+f[k]);
}
}
}
There are two problems:
1. when i print it's printing the duplicated letter twice(or thrice or more depends how many times the letter is in the string).
so i added the another 2 loops(k and l) that deletes the duplicated letters,but now instead of the duplicated letter it's print me: an square and a zero,how i can just get delete the letter and the number from the char and int array's?(for example when i insters the name "elichai" i get:
e=1
l=1
(an square)=0
c=1
h=1
a=1
i=2
2.The letter it deletes is the second letter not the first
(in "elichai" example it's deleted the first 'i' instead of the second 'i')
Thanks!
Different approach to solve your problem, but this is how I would probably do it:
String input = "Whatever";
Map<Character, Integer> charCounter = new LinkedHashMap<>(); // respects insertion order
for (char c : input.replaceAll("\\s+", "").toCharArray()) { // ignore spaces
Integer count = charCounter.get(c);
count = count == null ? 0 : count;
charCounter.put(c, count + 1);
}
System.out.println(charCounter);
class Twice_Occuring
{
void main(String s)
{
int count=0;
for(int i=0;i<s.length();i++)
{
char c=s.charAt(i);
int ind1=s.indexOf(c,i);
int ind2=s.indexOf(c,i+1);
if(ind2-ind1==1)
{System.out.print(c+" ");count++;}
}
System.out.println("\n Number of counts = "+count);
}
}