I'm trying to solve this problem
https://vjudge.net/problem/UVALive-6805
I found solution but in c++ , Can anybody help me converting it to java code. I'm very newbie to programming
I tried a lot of solutions but non of them work.
Please I need help in this if possible
I don't know for example what is the equivalent for .erase function in c++ in java
Also is is sbstr in c++ provide different result from java ?
#include <iostream>
#include <string>
using namespace std;
int syllable(string word)
{
int L = word.size();
int syllable;
if (L>=7)
{
syllable = 3;
}
else if (L==6)
{
int indicator = 0;
for (int k=0; k<=L-2; k++)
{
string subword = word.substr(k, 2);
if (subword == "ng" || subword == "ny")
{
indicator++;
}
}
if (indicator == 0)
{
syllable = 3;
}
else
{
syllable = 2;
}
}
else if (L == 4 || L == 5)
{
syllable = 2;
}
else if (L == 3)
{
char Char = word[0];
if (Char=='a' || Char=='A' || Char=='e' || Char=='E' || Char=='i' || Char=='I' || Char=='o' || Char=='O' || Char=='u' || Char=='U')
{
syllable = 2;
}
else
{
syllable = 1;
}
}
else
{
syllable = 1;
}
return syllable;
}
int main()
{
string word;
int T;
cin >> T;
for (int i=1; i<=T; i++)
{
int syl[] = {0, -1, -2, -3};
string rhy[] = {"a", "b", "c", "d"};
int verse = 0;
int stop = 0;
while (stop == 0)
{
cin >> word;
int L = word.size();
char end = word[L-1];
if (end == '.')
{
stop = 1;
}
if (word[L-1] == ',' || word[L-1] == '.')
{
word = word.erase(L-1, 1);
L = word.size();
}
if (verse<=3)
{
syl[verse] = syl[verse] + syllable(word);
}
if (end == ',' || end == '.')
{
if (verse<=3)
{
rhy[verse] = word.substr(L-2, 2);
}
verse++;
if (verse<=3)
{
syl[verse] = 0;
}
}
}
int A = 0, B = 0, C = 0, D = 0;
for (int k=0; k<4; k++)
{
if (syl[k] >= 8 && syl[k] <= 12)
{
A = A + 10;
}
}
for (int k=0; k<2; k++)
{
if (rhy[k] == rhy[k+2])
{
B = B + 20;
}
}
for (int k=0; k<2; k++)
{
if (syl[k] == syl[k+2])
{
C = C + 10;
}
}
if (verse > 4)
{
D = (verse - 4) * 10;
}
int E = A + B + C - D;
cout << "Case #" << i << ": " << A << " " << B << " " << C << " " << D << " " << E << endl;
}
}
here is my trying
import java.util.*;
public class First {
public static int syllable(String word) {
int L = word.length();
int syllable;
if (L >= 7) {
syllable = 3;
} else if (L == 6) {
int indicator = 0;
for (int k = 0; k < L - 3; k++) {
String subword = word.substring(k, 2);
if (subword == "ng" || subword == "ny") {
indicator++;
}
}
if (indicator == 0) {
syllable = 3;
} else {
syllable = 2;
}
} else if (L == 4 || L == 5) {
syllable = 2;
} else if (L == 3) {
char Char = word.charAt(0);
if (Char == 'a' || Char == 'A' || Char == 'e' || Char == 'E' || Char == 'i' || Char == 'I' || Char == 'o'
|| Char == 'O' || Char == 'u' || Char == 'U') {
syllable = 2;
} else {
syllable = 1;
}
} else {
syllable = 1;
}
return syllable;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word;
int T;
T = sc.nextInt();
for (int i = 1; i <= T; i++) {
int syl[] = { 0, -1, -2, -3 };
String rhy[] = { "a", "b", "c", "d" };
int verse = 0;
int stop = 0;
while (stop == 0) {
word = sc.next();
int L = word.length();
char end = word.charAt(L-1);
if (end == '.') {
stop = 1;
}
if (word.charAt(L-1) == ',' || word.charAt(L-1) == '.') {
word.substring(L-1, 1);
L = word.length();
}
if (verse <= 3) {
syl[verse] = syl[verse] + syllable(word);
}
if (end == ',' || end == '.') {
if (verse <= 3) {
rhy[verse] = word.substring(L - 2, 2);
}
verse++;
if (verse <= 3) {
syl[verse] = 0;
}
}
}
int A = 0, B = 0, C = 0, D = 0;
for (int k = 0; k < 4; k++) {
if (syl[k] >= 8 && syl[k] <= 12) {
A = A + 10;
}
}
for (int k = 0; k < 2; k++) {
if (rhy[k] == rhy[k + 2]) {
B = B + 20;
}
}
for (int k = 0; k < 2; k++) {
if (syl[k] == syl[k + 2]) {
C = C + 10;
}
}
if (verse > 4) {
D = (verse - 4) * 10;
}
int E = A + B + C - D;
System.out.println("Case #" + i + ": " + A + " " + B + " " + C + " " + D + " " + E);
}
}
}
The Exception is thrown by your second and your third call of String substring method. Your beginIndex is higher than your endIndex. As you can see in here https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int) beginIndex always has to be lower than the endIndex.
Before answering your question, there are some important points to mention in regards to Strings and Java in general.
Strings are immutable (This also applies to C++). This means that no method called on a String will change it, and that all methods simply return new versions of the original String with the operations done on it
The substring method in java has two forms.
One takes in beginIndex and returns everything from beginIndex to str.length() - 1 (where str represents a String)
The other takes in the beginIndex, and the endIndex, and returns everything from beginIndex to endIndex - 1. The beginIndex should never be larger than endIndex otherwise it throws an IndexOutOfBoundsException
C++'s substring method (string::substr()) takes in the beginning "index" and takes in the number of characters after it to include in the substring. So by doing substr(L-2, 2) you get the last two characters of the string.
Java will never allow you to go out of bounds. That means you need to constantly check whether you are within the bounds of anything you are iterating through.
With all this in mind, I would go and verify that all of the substring() method calls are returning the proper range of characters, and that you are properly reassigning the values returned from substring() to the proper variable.
To mimic C++'s string::erase(), depending on what part of the word you want to erase, you want to get the substring of the part before and the substring of the part after it and add them together.
Ex. Lets say I have a String line = "I do not like the movies"; Since it is impossible for anyone to not like movies, we want to cut out the word not
We do this by doing what I said above
String before = line.substring(0, 5); // This gives us "I do " since it goes up to but not including the 5th index.
String after = line.substring(5 + 3); // This gives us the rest of the string starting after the word "not" because not is 3 characters long and this skips to the 3rd index after index 5 (or index 8)
line = before + after; // This'll add those two Strings together and give you "I do like the movies"
Hope this helps!
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'm trying to make a program that takes in a string like: KKKKKKKKKKKKKBCCDDDDDDDDDDDDDDDKKKKKMNUUUGGGGG
And returns something like this: $K13BCC$D15$K5MNUUU$G5
Another example is XYZAAAAAAGGTCCCCCCTTTAAAAAAAAAAAAAAKK
Returns: XYZ*A6GGT*C6TTT*A14KK
But i get this StringIndexOutOfBoundsException when i try the first input, can anyone tell me why? Here's my code:
import java.util.Scanner;
class RunLengthEncoding {
public static void main(String[] args) {
Scanner h = new Scanner(System.in);
String s;
char g;
System.out.print("Enter input string: ");
s = h.next();
for (int d = 0; d < s.length(); d++){
if (!Character.isUpperCase(s.charAt(d))){
System.out.print("Bad input.");
return;
}
}
System.out.print("Enter flag character: ");
g = h.next().charAt(0);
if (g != '#' && g != '$' && g != '&' && g != '*'){
System.out.println("Bad input.");
return;
}
char c = s.charAt(0);
String encode = "";
for (int n = 0; n < s.length() - 1; n++){
int k = 0;
int j = 0;
while (k + n < s.length() && s.charAt(k + n) == c){
j++;
k++;
}
if (j > 3){
encode += g;
encode += c;
encode += j;
n += j - 1;
}
else {
encode += c;
}
c = s.charAt(n + 1);
}
System.out.println("Encoded: " + encode);
}
}
The reason that you are getting an out of bounds exception is because you are incrementing n outside of the for loop statement. You do this when you are doing n += j - 1;. This gives you an out of bounds exception because when you do c = s.charAt(n + 1);, n could be greater than or equal to the length of the string. As a general rule, you should not alter the value of the iteration variable in the for loop anywhere outside of the for loop. It makes the code harder to debug.
For anyone interested in the solution I made:
import java.util.Scanner;
public class RunLengthEncoding {
public static void main(String[] args){
Scanner h = new Scanner(System.in);
String s;
char g;
StringBuilder encode = new StringBuilder();
System.out.print("Enter input string: ");
s = h.next();
for (int d = 0; d < s.length(); d++) {
if (!Character.isUpperCase(s.charAt(d))) {
System.out.print("Bad input.");
return;
}
}
System.out.print("Enter flag character: ");
g = h.next().charAt(0);
if (g != '#' && g != '$' && g != '&' && g != '*') {
System.out.println("Bad input.");
return;
}
for (int n = 0; n < s.length(); n++) {
int k = 1;
while (n < s.length() - 1 && s.charAt(n) == s.charAt(n + 1)) {
k++;
n++;
}
if (k > 3) {
encode.append(g).append(s.charAt(n)).append(k);
}
else {
for (int c = 0; c < k; c++) {
encode.append(s.charAt(n));
}
}
}
System.out.print("Encoded: " + encode);
}
}
I have a String of a length of more than 1000 character. In this string i have to print 1st character after that every 5th character.
I tried writing a program to iterate from 0th character to last character and have a count variable.
If count is equal to 5. I am printing the character and count is initializing with 0.
private static String getMaskedToken(String token) {
if (token == null)
return null;
char[] charArray = token.toCharArray();
int length = token.length();
StringBuilder sb = new StringBuilder();
int count = 0;
for (int i = 0; i < length; i++) {
count++;
if (i == 0 || i == length - 1) {
sb.append(charArray[i]);
} else if (count == 5) {
sb.append(charArray[i]);
count=0;
} else if(count < 5 && i == length-1){
sb.append(charArray[i]);
}else {
sb.append('*');
}
}
return sb.toString();
}
Need to print last character if count is less than 5 of last
iteration.
If String of length 9, "12345678" then actual output will be like
1***5**8
If String of length 9, "123456789abcd" then actual output will be
like 1***5****a**d
String output = "";
for (int i = 0; i < str.length(); i++) {
if (i == 0) {
output += str.charAt(i);
output += "***";
output += str.charAt(4);
i = 4;
} else if ((i - 4) % 5 == 0) {
output += str.charAt(i);
} else if (i == str.length()-1) {
output += str.charAt(i);
} else {
output += "*";
}
}
System.out.println(output);
}
This will print 1***5****a**d for string "123456789abcd".
try this code:
public void printFirstAndEveryFifthCharecter(String str)
{
for (int i = 0 ; i < str.length() ; i++)
{
if ((i+1) == 1 | (i+1) % 5 == 0) {
System.out.print(str.charAt(i) + "***");
}
}
if (str.length() % 5 > 0) {
System.out.print(str.charAt(str.length() - 1));
}
}
Your code should work fine. Here's an alternative without using StringBuilder and with fewer checks.
private static String getFirstFifthLast(String str) {
String[] strArray = str.split(""); //returns an array of strings with length 1
int arrayLength = strArray.length;
String result = strArray[0]; //append the first element
//append element if it is in 5th position, append "*" otherwise
for (int i = 0; i < arrayLength; i++) {
if ((i + 1) % 5 == 0) {
result += strArray[i];
} else {
result += "*";
}
}
result += strArray[arrayLength - 1]; //append the last element
return result;
}
Try this code,
private void printEvery5thCharacter(String str) {
for (int i = 1; i < str.length() - 1; i += 5) {
System.out.print(str.charAt(i - 1) + "***");
if (i == 1) {
i = 0;
}
}
if (str.length() % 5 > 0) {
System.out.print(str.charAt(str.length() - 1));
}
}
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;
}
}
So I have the following problem set to me: Write a program that takes an integer command-line argument N, and uses two nested for loops to print an N-by-N board that alternates between 6 colours randomly separated by spaces. The colours are denoted by letters (like 'r' for RED, 'b' for BLUE). You are not allowed to have two of the same colour next to eachother.
So, I know I probably need arrays to get around this problem. I tried several methods that all came up wrong. The following is one of my recent attempts, but I am unsure as how to now go through the grid and correct it. What the code does is make every row randomized with no colour left or right the same, but the columns are not fixed.
Note that I am a first year CS student with no programming history. I am guessing the solution to this problem isnt too complex, however, I cant see a simple solution...
int N = StdIn.readInt();
int array1[] = new int[N];
for (int column = 0; column < N; column++) {
int x = 0;
for (int row = 0; row < N; row++) {
int c = (int) (Math.random() * 6 + 1);
while (x == c) {
c = (int) (Math.random() * 6 + 1);
array1[row] = c;
}
if (c == 1) {
System.out.print("R ");
}
if (c == 2) {
System.out.print("O ");
}
if (c == 3) {
System.out.print("Y ");
}
if (c == 4) {
System.out.print("G ");
}
if (c == 5) {
System.out.print("B ");
}
if (c == 6) {
System.out.print("I ");
}
x = c;
}
System.out.println();
}
}
this was my solution for the problem. Quite convoluted though, but the logic behind it is straightforward. Each time you assign a new colour to your 2D array, you need only check the value of the array to the top and to the left of the position where you want to assign a new colour. You can only do this after you have assigned colours to the first row of the array however so you need to create separate conditions for the first row.
public class ColourGrid {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
char[][] clrGrid = new char[N][N];
char colours[] = {'r','b','y','w','o','g'} ;
for (int counter = 0 ; counter < N; counter++) {
for (int counter2 = 0 ; counter2 < N; counter2++) {
if (counter == 0 && counter2 == 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
else if (counter != 0 && counter2 == 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)-1][counter2]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else if (counter == 0 && counter2 != 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)][counter2-1]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else if (counter != 0 && counter2 != 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)-1][counter2] || clrGrid[counter][counter2] == clrGrid[counter][(counter2)-1]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
}
for (int counter = 0 ; counter < N; counter++) {
System.out.println("");
for (int counter2 = 0 ; counter2 < N; counter2++) {
System.out.print(clrGrid[counter][counter2] + " ");
}
}
}
}