This was a problem involving an array of chars and uses recursion. I understand partly how to solve it, but I can't seem to output how many times the char a appears in the char array. Here is the method that I came up with two variations I tried but to no success.
private static Int charCount(char[] test, int i, char c) {
int[] number = new int[26];
char c = 'a';
if (test.length == 0) {
return 0;
}
int count = 0;
if (test == a) {
count++;
}
return count + count(test[1], a);
}
for(c = 'a'; c <= 'z'; c++)
{
for( char x : test )
{
if( c == x )
{
c++;
}
}
}
So I think I understand this, but let me know if I don't. Your question is: How can I read the number of a value in an array? Correct? If so then here is some code which should work:
import java.util.*;
public class HowToReadCountOfDataInArray {
private static final char[] arr = newArr();
private static int ReadArrayValue(char[] arr, char value) {
int count = 0;
for(int i = 0; i < arr.length; i++) {
if(arr[i] == value) {
count++;
}
}
return count;
}
public static void main(String[] args) {
System.out.println(ReadArrayValue(arr, 'a'));
System.out.println(arr);
}
}
P.S. Here is the "newArr()" method:
public static char[] newArr() {
char[] arr = new char[new Random().nextInt(100 + 1 - 1) + 1];
int aOrB = new Random().nextInt(2 + 1 - 1) + 1;
for(int i = 0; i < arr.length; i++) {
aOrB = new Random().nextInt(2 + 1 - 1) + 1;
if(aOrB == 1) {
arr[i] = 'a';
}else if(aOrB == 2) {
arr[i] = 'b';
}
}
return arr;
}
Given a string. Find the longest palindrome subsequence. The string contains an only lowercase letter.
Here, I am creating the array with the length of 26 and keeping track of all lowercase letters (i.e how many times they occur in the string). Finally, I count the number of even letters and if one is odd then (odd-1) is added to it.
public int count(String input1){
int res = 0;
int temp = 0;
char chr [] = input1.toCharArray();
int arr[] = new int[26];
for(int i=0;i<chr.length;i++){
arr[chr[i] - 97]++;
}
for(int val:arr){
if(val%2 != 0) temp++;
if(val%2 ==0){
res=res+val;
}
else{
res = res+(val-1);
}
}
if(temp != 0) res++;
return res;
}
}
it's showing undesired output
It's much easier to understand where is the problem, just split activities in separate methods. E.g. isPalindrome() could be in separate method:
public static int findLongestPalindrome(String str) {
int max = 1;
for (int i = 0; i < str.length(); i++) {
for (int j = str.length() - 1; j > i; j--) {
if (!isPalindrome(str, i, j))
continue;
max = Math.max(max, j - i + 1);
break;
}
}
return max;
}
private static boolean isPalindrome(String str, int i, int j) {
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
I had successfully counted the number of vowels in each element of string array. But i am unable to compare them and the print the array element which has the least number of vowels. Please help me out.
This is the code i had written so far....
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int N = s.nextInt();
int vowelcount = 0;
int maxcount = 0, sum = 0;
String a[] = new String[N];
for(int i = 0; i < N; i++) {
a[i] = s.next();
}
for(int i = 0; i < N; i++) {
String str = a[i];
for(int j = 0; j < str.length(); j++) {
if(str.charAt(j) == 'a' || str.charAt(j) == 'e' || str.charAt(j) == 'i'
|| str.charAt(j) == 'o' || str.charAt(j) == 'u') {
vowelcount = vowelcount + 1;
}
}
System.out.println(vowelcount);
vowelcount = 0;
}
}
I have modified your code.. Please try running the below code
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int N=s.nextInt();
int vowelcount=0;
int maxcount=0,sum=0;
String a[]=new String[N];
for(int i=0;i<N;i++){
a[i]=s.next();
}
//added
int minCount = Integer.MAX_VALUE;
int minCountIndex = Integer.MAX_VALUE;
//till here
for(int i=0;i<N;i++){
String str=a[i];
for(int j=0;j<str.length();j++){
if(str.charAt(j)=='a'||str.charAt(j)=='e'||str.charAt(j)=='i'||str.charAt(j)=='o'||str.charAt(j)=='u'){
vowelcount=vowelcount+1;
}
} //Add below lines
if(vowelcount < minCount) {
minCount = vovelcount;
minCountIndex = i;
} //till here
System.out.println(vowelcount);
vowelcount=0;
}
System.out.println("String with Minimum Vovels :" + a[minCountIndex]); // Added this
}
Create a custom comperator class which suits your needs like this:
static class SortDescendingByNumberOfVowels implements Comparator<String> {
private int getNumberOfVowels(String str) {
int counter = 0;
for(int i = 0; i < str.length(); i++) {
if(str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u') {
counter += 1;
}
}
return counter;
}
#Override
public int compare(String str1, String str2) {
return getNumberOfVowels(str2) - getNumberOfVowels(str1);
}
}
Then use the above comperator to sort the array by using another signature of Arrays.sort() which takes as a 2nd parameter the comperator:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int N = Integer.parseInt(s.nextLine());
String a[] = new String[N];
for(int i = 0; i < N; i++) {
a[i] = s.nextLine();
}
System.out.println("Initial array: " + Arrays.toString(a));
Arrays.sort(a, new SortDescendingByNumberOfVowels());
System.out.println("Sorted array : " + Arrays.toString(a));
System.out.println("Item with less vowels: " + a[N - 1]);
}
You could use a regex rather than comparing individual characters to get the vowel count
Pattern vowels = Pattern.compile("[aeiou]", Pattern.CASE_INSENSITIVE);
int numberOfVowels = value.length() - vowels.matcher(value).replaceAll("").length();
You could also use a stream to do the sorting.
Pair fewest = Arrays.stream(values)
.map(value -> new Pair(value.length() - vowels.matcher(value).replaceAll("").length(), value))
.sorted((v1, v2) -> Integer.compare(v1.length, v2.length))
.findFirst().orElse(null);
System.out.println(fewest.value);
That relies on having a Pair class which holds the length and value
private class Pair {
int length;
String value;
Pair(int length, String value) {
this.length = length;
this.value = value;
}
}
Solving this problem from codingBat
Given a string, return the length of the largest "block" in the
string. A block is a run of adjacent chars that are the same.
maxBlock("hoopla") → 2
maxBlock("abbCCCddBBBxx") → 3
maxBlock("") → 0
I was trying to solve it using one for loop as below:
public int maxBlock(String str) {
int maxCounter=1;
int counter=1;
if(str.length()==0)
{
return 0;
}
for(int i=0;i<str.length()-1;i++)
{
if(str.substring(i,i+1).equals(str.substring(i+1,i+2)))
{
counter++;
}
if(counter>maxCounter)
{
maxCounter=counter;
counter=0;
}
}
return maxCounter;
}
It beats all the cases apart from one. Can anybody show a solution with one for loop?
Sorry for mentioning late but you can't use REGEX or anything from collections framework.
I think you get it wrong in certain edge cases:
public int yourMaxBlock(String str) {
int maxCounter = 1;
int counter = 1;
if (str.length() == 0) {
return 0;
}
for (int i = 0; i < str.length() - 1; i++) {
if (str.substring(i, i + 1).equals(str.substring(i + 1, i + 2))) {
counter++;
}
if (counter > maxCounter) {
maxCounter = counter;
counter = 0;
}
}
return maxCounter;
}
public int myMaxBlock(String str) {
int maxCounter = 1;
int counter = 1;
if (str.isEmpty()) {
return 0;
}
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i - 1) == str.charAt(i)) {
if (++counter > maxCounter) {
maxCounter = counter;
}
} else {
counter = 1;
}
}
return maxCounter;
}
public void test() {
String[] tests = new String[]{
"", "+", "++", "+++,++,++,+", "+,++,+++,++,", "+,++,+++,++++", "+++++,++,+++,++++"
};
for (String s : tests) {
int myMax = myMaxBlock(s);
int yourMax = yourMaxBlock(s);
System.out.println("myMaxBlock(" + s + ") = " + myMax + (myMax != yourMax ? " WRONG! you have " + yourMax : ""));
}
}
prints
myMaxBlock() = 0
myMaxBlock(+) = 1
myMaxBlock(++) = 2
myMaxBlock(+++,++,++,+) = 3
myMaxBlock(+,++,+++,++,) = 3
myMaxBlock(+,++,+++,++++) = 4 WRONG! you have 3
myMaxBlock(+++++,++,+++,++++) = 5 WRONG! you have 4
You can use a Pattern matcher "(.)(\\1)*" that look for repeated char in the String , Here is the code :
public int maxBlock(String str) {
Pattern pattern = Pattern.compile("(.)(\\1)*");
Matcher matcher = pattern.matcher(str);
int max = 0;
while (matcher.find()) {
max = Math.max(max, matcher.group().length());
}
return max;
}
I'm a little late to the party, but here's my CodingBat solution:
public int maxBlock(String str) {
int max = 0;
int count = 1;
char o = ' ';
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == o) {
count++;
if (count > max) { max = count; }
} else {
count = 1;
if (count > max) { max = count; }
}
o = c;
}
return max;
}
Here's a solution based loosely on yours. Note the use of charAt for a neater looking code example.
This starts at the second character of the string and looks backwards to see if we are still encountering the same character. If so, the counter increases. When we finish a string of identical chars, we compare against the max length found thus far and update if necessary.
public static int maxBlock(String str) {
int maxCounter = 1;
int counter = 1;
if (str.length() == 0) {
return 0;
}
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i - 1) == str.charAt(i)) {
counter++;
} else {
// end of a run
if (counter > maxCounter) {
maxCounter = counter;
}
counter = 1;
}
}
return Math.max(maxCounter, counter);
}
Just use one for loop. I think here is another way.
public int maxBlock(String str) {
int len = str.length();
int temp=(len>0)?1:0;
int r =0;
for(int i=1; i<len; i++){
if(str.charAt(i) == str.charAt(i-1)){
temp++;
}
else{
r = (temp>r)?temp:r;
temp=1;
}
}
r = (temp>r)?temp:r;
return r;
}
public int maxBlock(String str) {
int max = 0;
for(int i = 0 ; i < str.length() ; i ++ ) {
char compareChar = str.charAt(i);
int count = 0;
while (i + 1 < str.length()
&& compareChar == str.charAt(i+1)) {
i++;
count ++;
}
if (max < count + 1) {
max = count + 1;
}
}
return max;
}
Here's my solution. It's simpler than you think.
public int maxBlock(String str)
{
//create a counter to return
int counter = 0;
//create a temporary variable to store a running total.
int temp = 1;
//Start on the first character and test to see if the second
//character equals the first.
for (int i = 1; i < str.length(); i++)
{
//If it does, we increment the temp variable.
if (str.charAt(i) == str.charAt(i-1))
{
temp++;
}
//If it doesn't, we wipe the temp variable and start from one.
else
{
temp = 1;
}
//If the temporary variable exceeds the counter amount, we make
//the counter variable equal to the temp variable.
if (temp > counter)
{
counter = temp;
}
}
//Return the counter.
return counter;
}
public int maxBlock(String str) {
int maxLength = 0;
Map<String,Integer> map = new HashMap<String,Integer>();
for(int i = 0; i< str.length(); i++){
String key = str.substring(i,i+1);
if(i!=0 && str.charAt(i) == str.charAt(i-1) && map.containsKey(key)){
map.put(key, map.get(key)+1);
}
else{
map.put(key,1);
}
}
for(Map.Entry<String,Integer> entry : map.entrySet()){
if(maxLength <entry.getValue()){
maxLength = entry.getValue();
}
}
return maxLength;
}
public int maxBlock(String str) {
int count = 0;
int i = 0;
int maxcount = 0;
if (str.length() == 0) return 0;
while (i < str.length() - 1) {
if (str.charAt(i) == str.charAt(i + 1)) {
count++;
if (count > maxcount) {
maxcount = count;
}
} else count = 0;
i++;
}
return maxcount + 1;
}
public int maxBlock(String str) {
int tcount = 0;
if (str.length() < 1) {
return 0;
}
for (int i = 0; i < str.length(); i++) {
int count = 0;
for (int j = i; j < str.length(); j++) {
if (str.charAt(i) == str.charAt(j)) {
count++;
} else
break;
}
if (count > tcount) {
tcount = count;
}
i += count - 1;
}
return tcount;
}
this is easier it totally works.
int i = 0;
int j = 0;
while(i < inner.length && j < outer.length) {
if(inner[i] > outer[j]) {
j++;
} else if(inner[i] < outer[j]) {
return false;
} else {
i++;
}
}
if(i != inner.length)
return false;
return true;
}
Here My code for this
public int maxBlock(String str) {
int count = 1;
for(int i=0;i<str.length()-1;i++){
int count2 = 0;
if(str.substring(i,i+1).equals(str.substring(i+1,i+2) )){
for(int j = i ; j < str.length();j++){
if(str.substring(i,i+1).equals(str.substring(j,j+1))){
++count2;
}
else{
break;
}
}
}
if(count2 > count){
count = count2;
}
}
if(str.isEmpty())return 0;
return count;
}
I wrote a code for my homework which says do inputs create a magic square matrix or don't. In magic square matrix, all of the rows, columns and diagonals sum must be equal. I wrote some functions to calculate the sum of the rows, columns and diagonals. At the end of the code I need to compare them to see they are equal or not. I assigned the results of the functions to different variables and I compared them in if statement at the end of the code. I am wondering is there any smarter way for comparison. I mean in my if statement there are too many variables and too many equality. I believe there is a smarter way for this.
package lab03;
import java.util.Scanner;
public class E7_15 {
public static boolean checkNumbers(int[][] array){
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
if (array[i][j] < 1 || array[i][j] > 16){
System.out.println("You entered a wrong value");
return false;
}
}
}
return true;
}
public static int sumRow(int[][] array, int i){
int sum = 0;
for(int j=0; j<array[i].length; j++){
sum += array[i][j];
}
return sum;
}
public static int sumColumn(int[][] array, int j){
int sum = 0;
for(int i=0; i<array[j].length; i++){
sum += array[i][j];
}
return sum;
}
public static int diagonalSumRightToLeft(int[][] array){
int sum = 0;
for(int i=0; i<array.length; i++){
sum += array[i][array.length-1-i];
}
return sum;
}
public static int diagonalSumLeftToRight(int[][] array) {
int sum = 0;
for(int i=0; i<array.length; i++){
sum += array[i][i];
}
return sum;
}
public static void main (String [] args){
int[][] intArray = new int [4][4];
Scanner in = new Scanner(System.in);
for (int i=0; i<4; i++) {
for ( int j=0; j<4; j++) {
System.out.println("!!!Please enter your numbers between 1-16!!!");
System.out.println("Enter your number for row " + (i+1) + " and column " + (j+1) + ": ");
intArray[i][j] = in.nextInt();
}
}
boolean done = checkNumbers(intArray);
int sumLRD = diagonalSumLeftToRight(intArray);
int sumRLD = diagonalSumRightToLeft(intArray);
int r1 = sumRow(intArray, 0);
int r2 = sumRow(intArray, 1);
int r3 = sumRow(intArray, 2);
int r4 = sumRow(intArray, 3);
int c1 = sumColumn(intArray, 0);
int c2 = sumColumn(intArray, 1);
int c3 = sumColumn(intArray, 2);
int c4 = sumColumn(intArray, 3);
if (done == true){
if(sumLRD==sumRLD && sumLRD==r1 && sumLRD==r2 && sumLRD==r3 && sumLRD==r4 &&
sumLRD==c1 && sumLRD==c2 && sumLRD==c3 && sumLRD==c4 && sumRLD==r1 && sumRLD==r2 &&
sumRLD==r3 && sumRLD==r4 && sumRLD==c1 && sumRLD==c2 && sumRLD==c3 &&
sumRLD==c4 && r1==r2 && r1==r3 && r1==r4 && r1==c1 && r1==c2 && r1==c3 && r1==c4 &&
r2==r3 && r2==r4 && r2==c1 && r2==c2 && r2==c3 && r2==c4 && r3==r4 && r3==c1 &&
r3==c2 && r3==c3 && r3==c4 && r4==c1 && r4==c2 && r4==c3 && r4==c4 && c1==c2 &&
c1==c3 && c1==c4 && c2==c3 && c2==c4 && c3==c4){
System.out.println("This is a magic square matrix");
}
else {
System.out.println("This is NOT a magic square matrix");
}
}
if (done == false){
System.out.println("WRONG VALUE! START AGAIN!");
}
in.close();
}
}
It seems like you're trying to see if all those numbers are equal. Just use a loop that compares every variable in the list with the one following it:
public boolean allEqual(int... values) {
for (int i = 0; i < values.length-1; i++) {
if (values[i] != values[i+1]) {
return false;
}
}
return true;
}
Then replace your megacondition with:
if (allEqual(sumLRD, sumRLD, r1, r2, ...)) {
// ...
}
This works because equality is transitive - i.e. if a == b and b == c then a == c. (The same for any number of variables.)
An alternative would be to refactor the whole check into something like:
boolean isMagicSquare(int[][] intArray) {
// check diagonals
int sum = diagonalSumLeftToRight(intArray);
if (sum != diagonalSumRightToLeft(intArray)) {
return false;
}
// check rows and columns
for (int i = 0; i < 4; i++) {
if (sum != sumRow(intArray, i) || sum != sumColumn(intArray, i)) {
return false;
}
}
return true;
}
// ...
if (isMagicSquare(intArray)) {
// ...
}
You could put all your sums in an array and use a function like this one in order to check if all the values are equal:
public static boolean allElementsTheSame(int[] array) {
if (array.length == 0) {
return true;
} else {
int first = array[0];
for (int element : array) {
if (element != first) {
return false;
}
}
return true;
}
}