I am currently working on a simple code that will check if an user inputted String contains character(s) that are specified in the for loop.
My current code
import java.util.Scanner;
public class AutumnLeaves {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int G = 0;
int R = 0;
int Y = 0;
int B = 0;
String S = sc.nextLine();
for (int i = 0; i < S.length(); i++) {
if (S.contains("G")) {
G++;
} else {
if (S.contains("R")) {
R++;
} else {
if (S.contains("Y")) {
Y++;
} else {
if (S.contains("B")) {
B++;
}
}
}
}
}
int total = G + R + Y + B;
System.out.println(G/total);
System.out.println(R/total);
System.out.println(Y/total);
System.out.println(B/total);
}
}
As you can see, it checks if the string contains such characters and it will increase the counter of the character by one. However when I run it, I don't receive the results I predicted.
If I input GGRY, it outputs 1 0 0 0. When the desired out put is
0.5
0.25
0.25
0.0
Any help would be appreciated!
The problem is that S.contains returns true if the whole string contains the given character. S.charAt should solve your problem:
for (int i = 0; i < S.length(); i++) {
if (S.charAt(i) == 'G') G++;
else if (S.charAt(i) == 'R') R++;
else if (S.charAt(i) == 'Y') Y++;
else if (S.charAt(i) == 'B') B++;
}
Also, dividing integers will return an integer (rounded down). As such your output would always be 0 unless all the characters are the same. Just cast them to double before printing:
System.out.println((double) G/total);
System.out.println((double) R/total);
System.out.println((double) Y/total);
System.out.println((double) B/total);
Edit: As pointed out by Sumit Gulati in a comment, a switch statement will have better performance in Java 7. Also, as David Conrad pointed out using only ifs in the for loop would work too as the conditions are mutually exclusive.
Your earlier code S.contains("some character") was finding the index of the character in the entire string. Use S.charAt(i) to specifically find the index at ith location in the string.
Finally, you need to convert the integer to floating point in order to print output as floating values.
public class AutumnLeaves {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int G = 0;
int R = 0;
int Y = 0;
int B = 0;
String S = sc.nextLine();
for (int i = 0; i < S.length(); i++) {
if (S.charAt(i) == 'G') {
G++;
} else {
if (S.charAt(i) == 'R') {
R++;
} else {
if (S.charAt(i) == 'Y') {
Y++;
} else {
if (S.charAt(i) == 'B') {
B++;
}
}
}
}
}
int total = G + R + Y + B;
System.out.println(G * 1.0 / total);
System.out.println(R * 1.0 / total);
System.out.println(Y * 1.0 / total);
System.out.println(B * 1.0 / total);
}
}
Related
You have been given a binary string containing only the characters '1' and '0'.
Calculate how many characters of the string need to be changed in order to make the binary string such that each of its substrings of at least a certain length contains at least one "1" character.
I came to think of the following idea but it fails for many testcases:
public static int minimumMoves(String s, int d) {
int n = s.length();
int i=0, answer = 0;
while(i<n)
{
boolean hasOne = false;
int j=i;
while(j<n && j<i+d)
{
if(s.charAt(j) == '1')
{
hasOne = true;
break;
}
j++;
}
if(!hasOne) {
answer++;
i += d;
}
else i++;
}
return answer;
}
Also my algorithm runs on O(|s|2) time. Can anyone suggest ideas on O(|s|) time?
Just throwing off an idea:
return s.split("(?<=\\G.{" + String.valueof(d) + "})").stream().filter(str -> str.contains("1")).count()
You just need to break ensure there is no run of d zeros.
public static int minimumMoves(String s, int d) {
int result = 0;
int runLength = 0;
for(char c: s.toCharArray()) {
if (c == '0') {
runLength += 1;
if (runLength == d) { // we need to break this run
result += 1;
runLength = 0;
}
} else {
runLength = 0;
}
}
return result;
}
I used the sliding window technique and Deque to solve this. This is my accepted solution:
public static int minimumMoves(String s, int d) {
int n = s.length();
Deque<Character> dq = new LinkedList<>();
int count = 0, answer = 0;
for(int i=0; i<d; i++)
{
if(s.charAt(i) == '1') count++;
dq.addLast(s.charAt(i));
}
if(count == 0) {
answer++;
count++;
dq.removeLast();
dq.addLast('1');
}
int i=d;
while(i<n)
{
if(dq.getFirst() == '1') count--;
dq.removeFirst();
if(s.charAt(i) == '1') count++;
dq.addLast(s.charAt(i));
if(count == 0)
{
answer++;
dq.removeLast();
dq.addLast('1');
count++;
}
i++;
}
return answer;
}
You just need to use a sliding window and a count of 1s so far at each index. Use a sliding window of d and if you don't see any ones so far, update the last index of that window with 1 and increment the result.
Code below:
public static int minimumMoves(String s, int d) {
int n = s.length();
int[] count = new int[n+1];
int res = 0;
for ( int i = 1; i <= d; i++ ) {
if ( s.charAt(i-1) == '1') count[i] = count[i-1]+1;
else count[i] = count[i-1];
}
if ( count[d] == 0 ) {
res++;
count[d] = 1;
}
for ( int i = d+1; i <= n; i++ ) {
if ( s.charAt(i-1) == '0' ) {
count[i] = count[i-1];
int ones = count[i] - count[i-d];
if ( ones == 0 ) {
count[i] = count[i-1] + 1;
res++;
}
} else {
count[i] = count[i-1] + 1;
}
}
return res;
}
Thought of another implementation you can do for this by working from the maximum possible changes (assumes at start that all values are '0' in String), reduce it when it finds a '1' value, and then jump to the next substring start. This allows it to run in O(n) and Ω(n/m) (n = String length, m = Substring length).
public static int minimumMoves(String s, int d)
{
char[] a = s.toCharArray();
//Total possible changes (not counting tail)
if(a.length < d)
return 0;
int t = (int) a.length / d;
//Total possible changes (counting tail)
//int t = (int) Math.ceil((double) a.length / (double) d);
for(int i = 0; i < a.length; i++)
{
if(a[i] == '1')
{
t--;
//Calculate index for start of next substring
i = (i / d + 1) * d - 1;
}
}
return t;
}
I am writing a program to find the number of 'a' in a given string that is repeated. For example, the call findAmountA("aba", 7) means that it finds the number of 'a' in the string "aba" repeated for 7 characters. So "abaabaa" is the final string, so that call would return 5.
Without actually making the string 7 characters (so calls for 1,000,000 characters would not take so long), how would I use mathematics to accomplish this task? I cannot get further than this, as I have been trying to troubleshoot this for a while.
Keep in mind I am a beginner Java programmer (Student) and do not want to use any advanced/fancy syntax that I would not learn in high school. Thank you!
public class AInString {
public static void main(String[] args) {
boolean a = findAmountA("aba", 10) == 7;
boolean b = findAmountA("a", 100) == 100;
boolean c = findAmountA("abca", 10) == 5;
boolean d = findAmountA("", 10) == 0;
boolean e = findAmountA("abcaa", 1000000) == 600000;
boolean f = findAmountA("abc", 0) == 0;
boolean g = findAmountA("bcd", 10) == 0;
System.out.println(a && b && c && d && e && f && g);
}
public static int findAmountA(String word, int n) {
String s = word;
if(s.length() == 0 || aInWord(word) == 0) {
return 0;
}else {
int a = (aInWord(s));
return a;
}
}
public static int aInWord(String word) {
String s = word;
int aInWord = 0;
for(int i = 0; i < word.length(); i++) {
if(s.charAt(i) == 'a') {
aInWord++;
}
}
return aInWord;
}
}
Let's say your short string w has N copies of 'a' in it. Then the result string will consist of K copies of w followed by a possibility empty “tail” string.
The value of K can be determined by integer-dividing the number of 'a's in the target string by N. Then the number t of 'a's in the “tail” would be equal to the remainder of the division. Now you can print K copies of w followed by the shortest prefix of 'w' containing t 'a's.
Divide the target length by the input length: for the example:
7 / 3 = 2 remainder 1
2 the number of "full copies" of the entire input string you will use. So, find the number of "a"s in the entire string, multiply by 2.
You will take the first 1 character of the input to make up the remainder of the 7 characters. Count the number of "a"s in that substring.
Simply add these two numbers together.
int total = count(input, "a") * targetLength / input.length()
+ count(input.substring(0, targetLength % input.length()), "a");
where count(input, c) is some method to count the number of occurrences of c in input.
Now that you've counted the occurrences of a char a in a string word, you can count the occurrences of the char in the string extended n characters with:
return n / word.length() * aInWord(word) + aInWord(word.substring(0, n % word.length()));
n / word.length() gives the number of full repeats of the string that fit into n. Multiplying this by the count of aInWord(word) gives the count of a in repeats of word that fit cleanly into n.
The rest is a matter of finding the number of repeats in the substring of word that doesn't fit cleanly into n using the % modulus operator to find the size of the partial substring (if any). Adding the two counts together produces the total number of occurrences in the extended string.
Here is a clean version which avoids duplicate variables, extra conditionals and generalizes methods to maximize reusability:
class Main {
public static void main(String[] args) {
assert findAmount("aba", 10, "a") == 7;
assert findAmount("a", 100, "a") == 100;
assert findAmount("abca", 10, "a") == 5;
assert findAmount("", 10, "a") == 0;
assert findAmount("abcaa", 1000000, "a") == 600000;
assert findAmount("abc", 0, "a") == 0;
assert findAmount("bcd", 10, "a") == 0;
System.out.println("tests passed");
}
public static int findAmount(String word, int n, String target) {
if (word.length() == 0) {
return 0;
}
return n / word.length() * count(target, word) +
count(target, word.substring(0, n % word.length()));
}
public static int count(String target, String s) {
return s.length() - s.replace(target, "").length();
}
}
Try it!
I made some changes in your code, take a look:
public static void main(String[] args) {
int a = findAmountA("aba", 10); // 7
int b = findAmountA("a", 100); // 100;
int c = findAmountA("abca", 10); //5;
int d = findAmountA("", 10); //0;
int f = findAmountA("abc", 0); //0;
int g = findAmountA("bcd", 10); //0;
System.out.println(a + " " + b + " " + c + " " + d + " " + f + " " + g);
}
public static int findAmountA(String word, int n) {
if (word.length() < n) {
for (int i=0; i<word.length(); i++) {
while (word.length() < n) {
word = word + word.charAt(i);
break;
}
}
} else if (word.length() > n) {
for (int i=0; i<word.length(); i++) {
word = word.substring(0, n);
}
} else {
return aInWord(word);
}
return aInWord(word);
}
public static int aInWord(String word) {
String s = word;
int aInWord = 0;
for(int i = 0; i < word.length(); i++) {
if(s.charAt(i) == 'a') {
aInWord++;
}
}
Thank you all for your help, using substrings I found an answer:
public class AInString {
public static void main(String[] args) {
boolean a = findAmountA("aba", 10) == 7;
boolean b = findAmountA("a", 100) == 100;
boolean c = findAmountA("abca", 10) == 5;
boolean d = findAmountA("", 10) == 0;
boolean e = findAmountA("abcaa", 1000000) == 600000;
boolean f = findAmountA("abc", 0) == 0;
boolean g = findAmountA("bcd", 10) == 0;
System.out.println(a && b && c && d && e && f && g);
}
public static int findAmountA(String word, int n) {
String s = word;
if(s.length() == 0 || aInWord(s) == 0) {
return 0;
}else {
int a = aInWord(s)*(n/s.length());
int b = n % s.length();
return a + aInWord(s.substring(0, b));
}
}
public static int aInWord(String word) {
String s = word;
int aInWord = 0;
for(int i = 0; i < word.length(); i++) {
if(s.charAt(i) == 'a') {
aInWord++;
}
}
return aInWord;
}
}
I'm doing an assignment and I am done. This is a simple program that prints out pyramids of chars. However, I can't figure out why the program prints a newline when I never specified it with some input, even if it's meant to: https://i.imgur.com/gPs5oC5.png
Why do I have to have an extra newline when printing the pyramid upside down? Where is the newline printed?
import java.util.Scanner;
public class Test23 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean state = true;
String messageL = "Length: ";
String messageD = "Position: ";
String messageS = "Shutdown!";
while(state) {
int limit = 0;
int degree;
System.out.print(messageL);
int length = input.nextInt();
while ((length < 1 && length == -1) || length > 26) {
if (length == -1 ) {
System.out.println(messageS + "\n");
state = false;
break;
} else {
System.out.print(messageL);
length = input.nextInt();
}
}
if (!state)
break;
System.out.print(messageD);
degree = input.nextInt();
while((degree > 1) || (degree < 0)) {
System.out.print(messageD);
degree = input.nextInt();
}
if (degree == 0)
//No newline is needed here for some reason.
length++;
else if (degree == 1)
limit = length;
//New line here for the pyramids to print symmetrically.
//System.out.println("");
for (int i = 0; i < length; ++i) {
for (int counter = 0; counter < limit; counter++) {
char letter = (char)(counter + 'A');
System.out.print(letter);
}
if (degree == 0)
limit++;
else if (degree == 1)
limit--;
System.out.println("");
}
System.out.println("");
}
}
}
Small java program prints invisible newline?
In your program the last System.out.println(""); causes an extra line at the end of your program, i.e while(state) is true at the end, So either you comment the print statement or make your state=false at end.
while(state) {
...
System.out.println("");
}
The most inner loop won't run if the input is 0. limit will be 0, and hence the loop condition is false. As of this it will print en empty line, proceeding to add 1 too limit and then print chars.
for (int i = 0; i < length; ++i) {
for (int counter = 0; counter < limit; counter++) {
char letter = (char)(counter + 'A');
Here is my analysis to this problem: There are four kinds of conditions where the brackets is matching: {{()}}, {}[]<>, <{}[]>, {<>[]}<>
So it could be complicated if I just think about these 4 matching forms. So I try to find out when is the brackets is not matching. if I let { and } be a pair, I find out if one bracket is on the odd position then his pair must be in a even position, vice versa. Take {<>[]}<> as an example, { is at the 1st position which is an odd position and } is at the 6th position which is an even position. Therefore I use numbers to mark them which '()'--1,9; '[]'--2,8; '<>' --3,7; '{}' --4,6 so if two number adds up is equals to 10 then these two numbers represents a pair. Then I use those numbers to represent bracket structure. and I pull out bracket in odd position and bracket in even position(use number to represent them) and I add each items in odd position and even position with each other to see if there is a match which adds up is 10, if not, I say it's a match. My code is as below:
/** Matching Brackets
* Tony
*/
import java.util.*;
public class Solution19 {
public static String process(String n) {
/** build a condition combination: */
String newString = "";
for (int i = 0; i < n.length(); i++) {
if (n.charAt(i) == '(' || n.charAt(i) == ')' || n.charAt(i) == '[' || n.charAt(i) == ']'
|| n.charAt(i) == '<' || n.charAt(i) == '>' || n.charAt(i) == '{' || n.charAt(i) == '}') {
newString += n.charAt(i);
}
}
return newString;
}
public static String numForm(String s) {
String newone = "";
for (int i = 0; i < s.length(); i++) {
switch(s.charAt(i)) {
case '(': newone += "1 ";break;
case ')': newone += "9 ";break;
case '[': newone += "2 ";break;
case ']': newone += "8 ";break;
case '<': newone += "3 ";break;
case '>': newone += "7 ";break;
case '{': newone += "4 ";break;
case '}': newone += "6 ";break;
}
}
return newone;
}
public static int[] intArray(String m) {
String[] stringArray = m.split(" ");
int[] intArr = new int[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
intArr[i] = Integer.parseInt(stringArray[i]);
}
return intArr;
}
public static void printArray (int[] array) {
for (int n : array) {
System.out.print(n + " ");
}
}
public static int[] oddPosition (int[] array) {
int [] oddNumbers = new int[array.length / 2];
int j = 0;
for (int i = 0; i < array.length; i++) {
if ((i + 1) % 2 != 0) {
oddNumbers[j] = array[i];
j ++;
}
}
return oddNumbers;
}
public static int[] evenPosition (int[] array) {
int [] evenNumbers = new int[array.length / 2];
int j = 0;
for (int i = 0; i < array.length; i++) {
if ((i + 1) % 2 == 0) {
evenNumbers[j] = array[i];
j ++;
}
}
return evenNumbers;
}
public static boolean addsUpten (int [] array) {
boolean conditionSum = false;
boolean conditionSingle = false;
for (int i = 0; i < array.length; i++) {
int d = 0;
while (i + d < array.length) {
if (array[i] + array[i+d] == 10) {
conditionSingle = true;
}
conditionSum = (conditionSum || conditionSingle);
d ++;
}
}
return conditionSum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int times = sc.nextInt();
String voider = sc.nextLine();
for (int i = 0; i < times; i ++) {
String formula = sc.nextLine();
String processed = process(formula);
String numFormed = numForm(processed);
// System.out.println(numFormed);
int[] numArray = intArray(numFormed);
if (numArray.length % 2 != 0) {
System.out.print("0 ");
}
else {
int[] oddNumbers = oddPosition(numArray);
int[] evenNumbers = evenPosition(numArray);
if (addsUpten(oddNumbers) || addsUpten(evenNumbers) == true) {
System.out.print("0 ");
}
else {
System.out.print("1 ");
}
}
}
}
}
as I expected, it should work and it does work when I input:
4
(a+[b*c]-{d/3})
(a + [b * c) - 17]
(((a * x) + [b] * y) + c
auf(zlo)men [gy<psy>] four{s}
it gives me output:1 0 0 1 (1 represent it is a match, 0 represent it's not a match). However when I input something longer like [^]<t>(z){<[^]<w>[{f}c]y[-][v]{<y>g<+( )>(c){w{a{t}}}}>((a)w)} it is a match but it gives me 0. I wonder the way I determine if it's a match or not is right or wrong? What did I miss? Sorry for the long code, just wondering ("I find out if one bracket is on the odd position then his pair must be in a even position, vice versa.") this way to describe a bracket match is right or wrong? Thx!
Your approach has a fundamental problem - it does not support nesting very well.
You can solve this by creating a stack of parentheses:
When you see an opening parenthesis, you push it on the stack
When you see a closing parenthesis, you pop an opening parenthesis that is supposed to pair with it off the stack
If the pair from the stack matches, continue
If the pair does not match, or the stack is empty, report a mismatch
If the stack is not empty at the end of the loop, also report a mismatch.
I have a code that must print only vowels from my strings in the array list but I'm not sure if I'm doing it right in my method. How do I resolve this? Its only printing out 5 of them because I'm not sure how to directly get each specific vowels. Please find the below code that I have tried.
import java.util.*;
public class vowels {
public static void main(String[] args) {
ArrayList<String> vowels = new ArrayList<String>();
vowels.add("mitsubishi");
vowels.add("subaru");
vowels.add("nissan");
vowels.add("honda");
vowels.add("toyota");
averageVowels(vowels);
}
public static void averageVowels(ArrayList<String> vowels) {
System.out.println(vowels);
int number = 0;
for (int i = 0; i < vowels.size(); i++)
{
if (vowels.get(i).contains("a") || vowels.get(i).contains("e") || vowels.get(i).contains("i") ||vowels.get(i).contains("o") || vowels.get(i).contains("u"))
{
number++;
}
}
System.out.println("a count: " +number);
System.out.println("e count: " +number);
System.out.println("i count: " +number);
System.out.println("o count: " +number);
System.out.println("u count: " +number);
}
}
You can do without any loops, quite easily so
public static void averageVowels(ArrayList<String> vowels) {
System.out.println(vowels);
String arrayToString = vowels.toString();
int length = arrayToString.length();
System.out.println("a count: " + (length - arrayToString.replace("a", "").length()));
System.out.println("e count: " + (length - arrayToString.replace("e", "").length()));
System.out.println("i count: " + (length - arrayToString.replace("i", "").length()));
System.out.println("o count: " + (length - arrayToString.replace("o", "").length()));
System.out.println("u count: " + (length - arrayToString.replace("u", "").length()));
}
It prints
[mitsubishi, subaru, nissan, honda, toyota]
a count: 4
e count: 0
i count: 4
o count: 3
u count: 3
You want to count five types of things, so you need five variables:
int aCount = 0;
int eCount = 0;
int iCount = 0;
int oCount = 0;
int uCount = 0;
There are many different ways you could loop through each of the words, and then each of the characters in each of the words. Here's one way:
for (int i = 0; i < vowels.size(); i++) {
String lowerCaseWord = vowels.get(i).toLowerCase(); //get lowercase version so we don't have to check each letter twice
for (int j=0; j<lowerCaseWord.length(); j++){ //loop through each char in the string
char c = lowerCaseWord.charAt(j);
if (c == 'a') aCount++;
else if (c == 'e') eCount++;
else if (c == 'i') iCount++;
else if (c == 'o') oCount++;
else if (c == 'u') uCount++;
}
}
Make 5 different variables to count the number of the vowel. For example numbera, number e etc. Then you will need 5 if statements (one for each vowel) each of which will increase its respective count by 1.
for (int i = 0; i < vowels.size(); i++)
for (int j = 0; j<vowels.get(j).length(); j++) {
if (vowels.get(i).charAt('a'))
{
numbera++;
}
if (vowels.get(i).charAt('e'))
{
numbere++;
}
if (vowels.get(i).charAt('i'))
{
numberi++;
}
if (vowels.get(i).charAt('o'))
{
numbero++;
}
if (vowels.get(i).charAt('u'))
{
numberu++;
}}
This
if (vowels.get(i).contains("a") || vowels.get(i).contains("e") || vowels.get(i).contains("i") ||vowels.get(i).contains("o") || vowels.get(i).contains("u"))
only checks if the string contains a, e, i, o, or u. If it found one of these, it won't bother to check the rest of the string. And since you are using ||, in your if statement, it will not evaluate the next conditions if the current condition is already true, so it will proceed to increment number.
If you want to find the number of each vowel, One way is to loop through the string by turning it into a char array and check if a character is a vowel. Then you should create a counter for each vowel and a separated if/switch statement for each. For example with an if statement.
int aCount = 0;
int eCount = 0;
int iCount = 0;
int oCount = 0;
int uCount = 0;
for (int i = 0; i < vowels.size(); i++) {
for (char c : vowels.get(i).toCharArray()) {
if (c == 'a') {
aCount++;
} else if (c == 'e') {
eCount++;
} else (c == 'i') {
iCount++;
} else if (c == 'o') {
oCount++;
} else if (c == 'u') {
uCount++;
} else {
continue;
}
}
}
The following implementation will be efficient. Maintaining a single char array of size 256 would be good enough, which works not only for vowels but for any ASCII character.
import java.util.*;
public class Vowels {
public static void main(String[] args) {
ArrayList<String> vowels = new ArrayList<String>();
vowels.add("mitsubishi");
vowels.add("subaru");
vowels.add("nissan");
vowels.add("honda");
vowels.add("toyota");
averageVowels(vowels);
}
public static void averageVowels(ArrayList<String> vowels) {
System.out.println(vowels);
int[] chars = new int[256];
int number = 0;
for (int i = 0; i < vowels.size(); i++)
{
for (char c : vowels.get(i).toCharArray()) {
chars[c]++;
}
}
System.out.println("a count: " +chars['a']);
System.out.println("e count: " +chars['e']);
System.out.println("i count: " +chars['i']);
System.out.println("o count: " +chars['o']);
System.out.println("u count: " +chars['u']);
}
}