JetBrains Academy: Processing strings - Kamil-Jankowski/Learning-JAVA GitHub Wiki
Create a euphonious word:
All the letters of the English alphabet are divided into vowels and consonants.
- The vowels are: a, e, i, o, u, y.
- The remaining letters are consonants.
A word is considered euphonious if it has not three or more vowels or consonants in a row. Otherwise, it is considered discordant.
Your task is to create euphonious words from discordant. You can insert any letters inside word. You should output the minimum number of characters needed to create a euphonious word from a given word.
For example, word "schedule" is considered discordant because it has three consonants in a row - "sch". To create a euphonious word you need to add any vowel between 's' and 'c' or between 'c' and 'h'.
import java.util.*;
public class Euphonius {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] word = input.split("");
int counter = 0;
ArrayList<String> vowels = new ArrayList<>(Arrays.asList(new String[] {"a", "e", "i", "o", "u", "y"}));
for (int i = 0; i < word.length; i++){
if (word.length - i > 2){
if(vowels.contains(word[i]) && vowels.contains(word[i+1]) && vowels.contains(word[i+2])){
counter++;
i++;
} else if(!vowels.contains(word[i]) && !vowels.contains(word[i+1]) && !vowels.contains(word[i+2])){
counter++;
i++;
}
} else {
break;
}
}
System.out.println(counter);
}
}
Generating passwords:
The password is hard to crack if it contains at least A uppercase letters, at least B lowercase letters, at least C digits and includes exactly N symbols. Also, a password cannot contain two or more same characters coming one after another. For a given numbers A, B, C, N you should output password that matches these requirements.
3 4 1 8
> PaSsw0rD
import java.util.*;
public class PasswordGenerator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
int digitCount = 0;
int n = scanner.nextInt();
char[] passElements = new char[n];
char[] bigLetters = new char[a];
if (a+b+c <= n){
// big letters generator - different
for (int i = 0; i < a; i++){
char tmp = (char) (Math.random() * 25 + 65);
if (i > 0){
while(tmp == bigLetters[i-1]){
tmp = (char) (Math.random() * 25 + 65);
}
}
bigLetters[i] = tmp;
// big letters placement
if (a <= (n-1)/2+1){
passElements[i*2] = bigLetters[i];
} else {
passElements[i] = bigLetters[i];
}
}
// small letters generator - different
for (int i = 0; i < b; i++){
char tmp = (char) (Math.random() * 25 + 97);
if (i > 0){
while(tmp == passElements[i-1]){
tmp = (char) (Math.random() * 25 + 97);
}
}
for(int j = 0; j < n; j++){
if (b <= n/2){
passElements[i*2+1] = tmp;
break;
} else {
if(passElements[j] == 0){
passElements[j] = tmp;
break;
}
}
}
}
// digits generator
for (int i = 0; i < n; i++){
if (digitCount == c){
break;
}
if (passElements[i] == 0){
char tmp = (char) (Math.random() * 10 + 48);
if (i > 0){
while(tmp == passElements[i-1]){
tmp = (char) (Math.random() * 10 + 48);
}
passElements[i] = tmp;
digitCount++;
} else {
passElements[i] = tmp;
digitCount++;
}
}
}
if (a+b+c < n) {
// additional small letters generator
for (int i = 0; i < n; i++){
char tmp = (char) (Math.random() * 25 + 97);
if (passElements[i] == 0){
if (i > 0 && i != passElements.length-1){
while(tmp == passElements[i-1] || tmp == passElements[i+1]){
tmp = (char) (Math.random() * 25 + 97);
}
passElements[i] = tmp;
} else if (i > 1 && i == passElements.length-1){
while(tmp == passElements[i-1]){
tmp = (char) (Math.random() * 25 + 97);
}
passElements[i] = tmp;
} else {
passElements[i] = tmp;
}
}
}
}
} else {
System.out.println("Parameters invalid to create password");
}
System.out.println(String.valueOf(passElements));
}
}
Maximum sequence of the same characters:
For a given string you need to find a length of the maximum sequence containing only same characters.
The input string could be empty.
import java.util.*;
public class LongestSequence {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String letters = scanner.nextLine();
int currentMax = 0;
int counter = 1;
if (letters.length() != 0){
currentMax = 1;
if (letters.length() > 1){
for (int i = 1; i < letters.length(); i++){
if (letters.charAt(i) == letters.charAt(i-1)){
counter++;
if (currentMax < counter){
currentMax = counter;
}
continue;
}
counter = 1;
}
} else {
currentMax = 1;
}
}
System.out.println(currentMax);
}
}
Parse URL:
You want to hack a website and get all available parameters. Print them "key : value". If you find the password (parameter pass), you should print it after all parameters. If a parameter doesn't have value print "not found".
Note: The order of parameters should like as in the url. If a url does not contain parameter pass, do not print anything after parameters:
https://target.com/index.html?pass=12345&port=8080&cookie=&host=localhost
import java.util.*;
class UrlParse {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String url = scanner.nextLine();
String password = null;
String[] websiteAndParameters = url.split("\\?");
String parameters = websiteAndParameters[1];
String[] parameter = parameters.split("&");
for (String p : parameter){
String[] keyValue = p.split("=");
if (keyValue.length == 1){
System.out.println(keyValue[0] + " : not found");
} else {
System.out.println(keyValue[0] + " : " + keyValue[1]);
}
if (keyValue[0].equals("pass") && keyValue.length > 1){
password = keyValue[1];
}
}
if (password != null){
System.out.println("password : " + password);
}
}
}
Alphabetical order:
Write a program that reads a string and output "true" only when the letters of the String are in alphabetical order, otherwise, "false".
Assume the empty string is in alphabetical order.
Note, string can contain only a single character.
import java.util.Scanner;
class Alphabetical {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String letters = scanner.next();
boolean ordered = true;
for (int i = 0; i < (letters.length()-1); i++){
char ch = letters.charAt(i);
char nextCh = letters.charAt(i+1);
if (ch <= nextCh){
continue;
} else {
ordered = false;
}
}
System.out.println(ordered);
}
}
Compression algorithm:
Upon learning that DNA is not a random string, freshmen of the Bioinformatics Institute from the informatics group suggested using a compression algorithm that compresses repeated characters in a string.
Encoding is performed as follows: The string "aaaabbсaa" is converted into "a4b2с1a2", that is, the groups of the same characters of the input string are replaced by the symbol and the number of its repetitions in this string.
Write a program, which reads the string, encodes it by this algorithm and outputs the encoded sequence. The encoding must be case sensitive.
Note, string can be empty or contain only a single character.
import java.util.*;
class Dna {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String dna = scanner.nextLine();
int counter = 1;
for(int i = 0; i < (dna.length()-1); i++){
if(dna.charAt(i) == dna.charAt(i+1)){
counter++;
} else {
System.out.print(dna.charAt(i) +""+ counter);
counter = 1;
}
}
if (!dna.isEmpty()){
System.out.print(dna.charAt(dna.length()-1) +""+ counter);
}else{
System.out.println("0");
}
}
}
Convert a date:
Write a program that takes a date string formatted as YYYY-MM-DD as input, then converts and outputs it as MM/DD/YYYY.
For instance, the input 2007-07-21 will result in the following output 07/21/2007.
The program must print "Incorrect input" if the date is not possible. Assume that every month has 31 days and that the year, month or day cannot be 0 (or 00).
import java.util.*;
class SimpleDateConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] dateInput = scanner.nextLine().split("-");
int dayMax = 31;
int monthMax = 12;
int year = Integer.valueOf(dateInput[0]);
int month = Integer.valueOf(dateInput[1]);
int day = Integer.valueOf(dateInput[2]);
if (year <= 0 || month <= 0 || month > monthMax || day <= 0 || day > dayMax){
System.out.println("Incorrect input");
} else {
String dateUs = String.format("%s/%s/%s", dateInput[1], dateInput[2], dateInput[0]);
System.out.println(dateUs);
}
}
}
Improved:
import java.util.*;
public class DateConverter {
public static void main(String []args){
Scanner scanner = new Scanner(System.in);
final int MONTH_MAX = 12;
int dayMax = 31;
boolean running = true;
// loop program until correct input is provided
while (true){
System.out.println("Please enter date to be converted (YYYY-MM-DD >>> mm/dd/yyyy):");
String dateIn = scanner.nextLine();
// check if date has required amount of signs
if (dateIn.length() == 10){
char delimiter1 = dateIn.charAt(4), delimiter2 = dateIn.charAt(7);
String digitsString = dateIn.substring(0, 4)+""+dateIn.substring(5, 7)+""+dateIn.substring(8);
char[] digits = digitsString.toCharArray();
// check if all signs apart from delimiters are numbers
for (char ch : digits) {
if (ch >= 48 && ch <= 57) {
running = true;
} else {
running = false;
break;
}
}
// check if delimiters are '-'
if (delimiter1 == '-' && delimiter2 == '-' && running){
String[] date = dateIn.split("-");
int year = Integer.valueOf(date[0]);
int month = Integer.valueOf(date[1]);
int day = Integer.valueOf(date[2]);
// check if this is a leap year, and adjust number of maximum days for February
if (year > 1582 && year <= 4500 && month == 2){
if(LeapYear.leapYearCheck(year)){
dayMax = 29;
} else {
dayMax = 28;
}
} else {
// if it is not February then adjust dayMax accordingly
if (month > 1 && month < 8 && month % 2 == 0 || month > 7 && month <= MONTH_MAX && month % 2 != 0){
dayMax = 30;
}
}
// verify if year, month and day exist
if (year <= 0 || month <= 0 || day <= 0 || month > MONTH_MAX || day > dayMax){
System.out.println("Incorrect input - there is no such day, or was, and there never will...");
continue;
} else {
String dateUs = String.format("%s/%s/%s",date[1] ,date[2] ,date[0]);
System.out.println(dateUs);
}
break;
} else {
System.out.println("Incorrect date format");
}
} else {
System.out.println("Incorrect input - date is to short");
continue;
}
}
}
}
// class verifying the leap year occurrence
class LeapYear {
public static boolean leapYearCheck (int y){
if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0){
return true;
} else {
return false;
}
}
}
Count the number of occurrences:
Write a program that counts the number of occurrences of a given character in a string.
The single input line contains a string and a character separated by a space.
import java.util.Scanner;
class SimpleCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[] input = scanner.next().toCharArray();
char key = scanner.next().charAt(0);
int counter = 0;
for (char ch : input){
if (ch == key){
counter++;
}
}
System.out.println(counter);
}
}
Count the number of times "ab" occur in a string:
Write a program that reads a string from the standard input and outputs the number of times that "ab" occurs in the string.
import java.util.*;
class AbCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String letters = scanner.nextLine();
int counter = 0;
for (int i = 0; i < letters.length()-1; i++){
if (letters.charAt(i) == 'a'){
if (letters.charAt(i+1) == 'b'){
counter++;
}
}
}
System.out.println(counter);
}
}
Count the number of times two chars occur in a string:
Write a program that counts the number of times that the two characters occur consecutively in a string. The order of characters should be the same as in the input.
Note, in the string "bbb" , the sequence "bb" occurs two times.
The single input line contains a string and two characters: abcd b c
.
import java.util.Scanner;
class TwoCharsCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[] input = scanner.next().toCharArray();
char key1 = scanner.next().charAt(0);
char key2 = scanner.next().charAt(0);
int counter = 0;
for (int i = 0; i < input.length - 1; i++){
if (input[i] == key1 && input[i+1] == key2){
counter++;
}
}
System.out.println(counter);
}
}
Cutting out the middle of a string:
Write a program that reads a string, and then outputs the string without its middle character when the length is odd, and without the middle 2 characters when the length is even.
import java.util.*;
class MiddleOut {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word = scanner.nextLine();
if(word.length() % 2 == 0){
String start = word.substring(0, word.length()/2-1);
String end = word.substring(word.length()/2+1);
word = start.concat(end);
} else {
String start = word.substring(0, word.length()/2);
String end = word.substring(word.length()/2+1);
word = start.concat(end);
}
System.out.println(word);
}
}
Double characters:
Write a program that reads a string and then output another string with doubled characters.
import java.util.*;
class Double {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word = scanner.nextLine();
String wordDouble = "";
for (int i = 0; i < word.length(); i++){
char temp = word.charAt(i);
wordDouble = wordDouble.concat(temp + "" + temp);
}
System.out.println(wordDouble);
}
}
Find the first occurrence of the word "the":
Write a program that takes a sentence as input and returns the index of the first occurrence of the word "the", regardless of the capitalization. If there is no occurrence of it must output -1.
For instance, if the sentence is “The apple is red.” the output should be 0, if the sentence is “I ate the red apple.” the output should be 6, and if the sentence is “I love apples.” the output should be -1.
Note, the and The are equal.
import java.util.*;
class TheFinder {
static Locale plLocale = new Locale.Builder().setLanguage("pl").setRegion("PL").build();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sentence = scanner.nextLine().toLowerCase(plLocale);
if (sentence.contains("the")){
int place = sentence.indexOf("the");
System.out.println(place);
} else {
System.out.println("-1");
}
}
}
Move the first N characters:
Write a program that reads a string s and an int n, and then moves the first n characters of s to the end of the string. The program must output the changed string. If n is greater than the length of the string, it must output the string unchanged.
Note, the substring
method can help you, but you may choose another way to solve the problem.
The single input line contains s and n separated by a space: Hello 3
import java.util.Scanner;
class Moving {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
int key = scanner.nextInt();
if (key < input.length()){
String firstPart = input.substring(0, key);
String secondPart = input.substring(key);
String output = secondPart.concat(firstPart);
System.out.println(output);
} else {
System.out.println(input);
}
}
}
Number of occurrences:
Write a program that finds the frequency of occurrences of substring in given string.
The first input line contains a string, the second one contains a substring.
import java.util.Scanner;
class Occurrence {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String sentence = scanner.nextLine();
String key = scanner.nextLine();
int counter = 0;
for (int i = 0; i < sentence.length(); i++){
i = sentence.indexOf(key, i);
if (i >= 0){
counter++;
} else {
break;
}
}
System.out.println(counter);
}
}
Palindrome:
Write a program that reads a string and checks whether it is a palindrome, i.e. it reads the same both left-to-right and right-to-left.
The program must output “yes” if the string is a palindrome and “no” otherwise.
import java.util.*;
class Palindrome {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
String output = "";
String palindrome = "no";
for (int i = input.length()-1; i >= 0; i--){
output = output +""+ input.charAt(i);
}
if (input.equalsIgnoreCase(output)){
palindrome = "yes";
}
System.out.println(palindrome);
}
}
or:
import java.util.*;
class Palindrome {
static Locale plLocale = new Locale.Builder().setLanguage("pl").setRegion("PL").build();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[] input = scanner.next().toLowerCase(plLocale).toCharArray();
String palindrome = "yes";
for (int i = 0; i < input.length/2 + 1; i++){
if (input[i] != input[input.length-1-i]){
palindrome = "no";
}
}
System.out.println(palindrome);
}
}
or:
import java.util.*;
class Palindrome {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StringBuilder word = new StringBuilder(scanner.next());
String input = word.toString();
String output = word.reverse().toString();
String palindrome = "no";
if (input.equalsIgnoreCase(output)){
palindrome = "yes";
}
System.out.println(palindrome);
}
}
The longest word:
In the given string find the first longest word and output it.
Given a string in a single line. Words in the string are separated by a single space.
Output the longest word. If there are several such words, you should output the one, which occurs earlier.
import java.util.*;
class Longest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sentence = scanner.nextLine();
String[] words = sentence.split(" ");
String longest = words[0];
for (int i = 0; i < words.length-1; i++){
if (longest.length() < words[i+1].length()){
longest = words[i+1];
}
}
System.out.println(longest);
}
}
The lucky ticket:
Paul loves to ride public transport and after receiving the ticket, he immediately checks whether he got the lucky one. A ticket is considered a lucky one if the sum of the first three numbers in this ticket matches the sum of the last three numbers in the same ticket.
However, Paul does not count well in head that is why he asks you to write the program, which will check the equality of the sums and display "Lucky" if the sums match, and "Regular" if the sums differ.
A string of six digits is provided as input to the program.
You need to print out only the word "Lucky" or "Regular" with a capital letter (without quotes).
import java.util.Scanner;
class LuckyNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] number = scanner.nextLine().split("");
int sumFirst = Integer.parseInt(number[0]) + Integer.parseInt(number[1]) + Integer.parseInt(number[2]);
int sumLast = Integer.parseInt(number[3]) + Integer.parseInt(number[4]) + Integer.parseInt(number[5]);
String ticket = "Regular";
if (sumFirst == sumLast){
ticket = "Lucky";
}
System.out.println(ticket);
}
}
or:
import java.util.Scanner;
class LuckyNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] number = scanner.nextLine().split("");
int sumFirst = 0;
int sumLast = 0;
String ticket = "Regular";
// for length 4 and more
for (int i = 0; i < number.length/2 && i < 3; i++){
sumFirst += Integer.parseInt(number[i]);
sumLast += Integer.parseInt(number[number.length-1 - i]);
}
if (sumFirst == sumLast){
ticket = "Lucky";
}
System.out.println(ticket);
}
}
The number of times two chars occur in a string:
Write a program that takes a string and two characters from the standard input and then prints the number of time the two characters occur consecutively in the string (in any order).
The single input line contains a string and two characters: abcd b c
.
import java.util.Scanner;
class TwoCharsCounterV2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[] input = scanner.next().toCharArray();
char key1 = scanner.next().charAt(0);
char key2 = scanner.next().charAt(0);
int counter = 0;
for (int i = 0; i < input.length - 1; i++){
if (input[i] == key1 && input[i+1] == key2 ||
input[i] == key2 && input[i+1] == key1){
counter++;
}
}
System.out.println(counter);
}
}
The percentage of G and C characters:
GC-content is an important feature of the genome sequences and is defined as the percentage ratio of the sum of all guanines and cytosines to the overall number of nucleic bases in the genome sequence. Write a program, which calculates the percentage of G characters (guanine) and C characters (cytosine) in the entered string. Your program should be case independent.
For example, in the string "acggtgttat" the percentage of characters G and C equals to 4/10 ⋅ 100 = 40.0, where 4 is the number of symbols G and C, and 10 is the length of the string.
The single input line contains a sequence.
Output: The percentage of G an C characters as a double. Do not round/format the value, output it as is.
import java.util.*;
class GCcontent {
static Locale localePL = new Locale.Builder().setLanguage("pl").setRegion("PL").build();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[] genom = scanner.next().toLowerCase(localePL).toCharArray();
int counter = 0;
double gcContent = 0;
for (char ch : genom){
if (ch == 'c' || ch == 'g'){
counter++;
}
}
gcContent = (double) counter/genom.length * 100;
System.out.println("gcContent);
}
}