public class Test {
public static String MakeSequence(int N)
{
int j;
N=5;
for (N=5;N>=1;--N)
{
for(j=1;j<N+1;++j)
{
return MakeSequence(5);
}
}
if (N<1)
{
String x = "";
System.out.println(x.isEmpty());
}
}
}
I want to return the sequence 555554444333221 when N=5 and return an empty string if the input parameter N is less than 1, but I'm not sure how to modify the code I made
Be simple and do not add additional checks:
public static String makeSequence(int N) {
StringBuilder buf = new StringBuilder();
while (N > 0) {
buf.append(String.valueOf(N).repeat(N));
N--;
}
return buf.toString();
}
public class Test {
public static String makeSequence(int n) {
String value = " ";
for (int i = n; i >= 1; --i) {
for (int j = 1; j < i + 1; ++j) {
value+= i;
}
}
return value;
}
public static void main(String[] args) {
final String s = makeSequence(5);
System.out.println(s);
}
}
In your code, you always try to assign 5 instead of considering the value send to the method. Above solution returns the sequence and if the parameter N(in code I use n) is less than 1 then returns the empty string.
FYI: As a best practice we start both variable and method names in simple letters.
Related
I'm trying to get my code to not only search if a char is present in an array, but also if it is present next to one another. So, if the input is hannah, the output should be hanah. It should only remove a char if it is next to the same char.
import java.util.*;
public class test {
static void removeDuplicate(char str[], int length) {
int index = 0;
for (int i = 0; i < length; i++) {
int j;
for (j = 0; j < i; j++) {
if (str[i] == str[j])
{
break;
}
}
if (j == i)
{
str[index++] = str[i];
}
}
System.out.println(String.valueOf(Arrays.copyOf(str, index)));
}
public static void main(String[] args) {
String info = "hannahmontana";
char str[] = info.toCharArray();
int len = str.length;
removeDuplicate(str, len);
}
}
This my solution
static String removeDuplicate(char str[], int length) {
if (length == 0) return "";
List<Character> list = new ArrayList<>();
list.add(str[0]);
for (int i = 1; i < length; i++) {
if (list.get(list.size() - 1) != str[i]) {
list.add(str[i]);
}
}
return list.stream()
.map(Object::toString)
.collect(Collectors.joining());
}
You can do a recursive call here:
import java.util.*;
public class test {
static String removeDuplicate(String input) {
if(input.length()<=1)
return input;
if(input.charAt(0)==input.charAt(1))
return removeDuplicate(input.substring(1));
else
return input.charAt(0) + removeDuplicate(input.substring(1));
}
public static void main(String[] args) {
String info = "hannahmontana";
System.out.println(removeDuplicate(info));
}
}
You can also try RegExp. Maybe not so fast, but I consider it simpler and more readable.
static String removeDuplicate(char[] chars, int ignored) {
return new String(chars).replaceAll("(.)\\1+", "$1")
}
Thanks for all the great answers! It turns out the solution was really simple. I just needed to change str[j] to str[i-1].
I would like to know why this code do not run. Is there something missing?
Count the number of "xx" in the given string. We'll say that overlapping is allowed, so "xxx" contains 2 "xx".
public class Drumkit {
int countXX(String str){
String a = "abcxxx";
int count = 0;
for (int i = 0; i < str.length() - 1; i++) {
if (a.substring(i, i + 2).equals("xx")) count++;
}
return count;
}
}
You are passing str and using its length() in your function. But, in the loop you're using a (local string variable) which seems like a logical mistake.
You need to pass the input string when your call this function and use str (the function argument) to count the matches.
Here's a functional example:
class Test
{
static int countXX( final String str ) {
int count = 0;
for (int i = 0; i < str.length() - 1; i++) {
if (str.substring(i, i + 2).equals("xx")) count++;
}
return count;
}
public static void main (String[] args)
{
final String s = "abcxxx";
final int count = countXX( s );
System.out.println( count );
}
}
Here's the live example: https://ideone.com/Lm6Ir4
Your problem is unclear. however, you can try this code
public static void main(String[] args) {
final int count = countXX("abcxx efjxx xyzxx xx xxxx xx","xx");
System.out.println(count);
}
static int countXX(final String text, final String occurrenceOf){
int count = 0;
int fromIndex=0;
for (int i = 0; i < text.length() - 1; i++) {
int index = text.indexOf(occurrenceOf,fromIndex);
if(index >-1) {
count++;
fromIndex=index+1;
}
}
return count;
}
I am trying to find all possible options of combining a string array with two elements. Let's say, the array has two elements {"we","are"}. The output should be:"we" "are" "we are" "are we"
I could manage, with some search, to put together this code:
public class Main {
public static void main(String[] args) {
String[] strings = {"we", "are"};
final int maxbit = 1 << strings.length;
for (int p = 0; p < maxbit; p++) {
String finalString = "";
for (int i = 0; i < strings.length; i++) {
if ((1 << i & p) > 0) {
finalString += strings[i] + " ";
}
}
System.out.println(finalString);
}
}
My problem is, that I am missing one solution, the output is following: "we" "are" "we are".
So I am missing the "are we" option, would I need to use recursion to solve this problem or can this code be modified to show the remaining option?
UPDATE: solution found with the help of answers
public static void main(String[] args) {
String[] test = { "are", "we"};
language(test.length, test, "");
}
private static void language(final int n, final String[] syllables, final String currentWord) { // example of N = 3
if (n == 0) {
System.out.println(currentWord);
} else {
for (int i = 0; i < syllables.length; i++) {
if (currentWord.equals(syllables[i])){
language(n - 1, syllables, "" + syllables[i]);
}else{
language(n - 1, syllables, currentWord + syllables[i]);
}
}
}
}
Another example
import java.util.Arrays;
public class HelloWorld{
public static void main(String[] args) {
String[] strings = {"we", "are"};
String str = Arrays.toString(strings);
System.out.println("Java String array to String = "+str.replace(",","").replace("[","").replace("]",""));
}
}
I looked over it for a while, and found 2 ways to make it based on your code:
this will print out every permutation once, and DOESN'T have to include all the words:
public static void recPerm(String... input) {
recHelper(input, input.length, "");
}
private static void recHelper(String[] input, int length, String currentWord) {
if (currentWord != "")
System.out.println(currentWord);
for (int i = 0; i < input.length; i++) {
if (!currentWord.contains(input[i]))
recHelper(input, length - 1, currentWord + input[i]);
}
}
this will print out every permutation once, and DOES have to include all the words:
public static void maxRecPerm(String... input) {
maxRecHelper(input, input.length, "");
}
private static void maxRecHelper(String[] input, int length, String currentWord) {
if (length == 0)
System.out.println(currentWord);
for (int i = 0; i < input.length; i++) {
if (!currentWord.contains(input[i]))
maxRecHelper(input, length - 1, currentWord + input[i]);
}
}
I want to scan a String and its content. I want to return an error message if there are any character in the string. For example: int a = myFunction("123"); will save "123" in a, but when the user tries to do something like int a = myFunction("12s32"); it should return the error, because there is a character in the string. This is what i got so far:
public class Parseint {
public static int parseInt(String str) {
if (str == null || str.isEmpty()) {
System.out.println("Der String enthaelt keine Zeichen");
return -1;
} else {
int sum = 0;
int position = 1;
for (int i = str.length() - 1; i >= 0; i--) {
int number = str.charAt(i) - '0';
sum += number * position;
position = position * 10;
}
return sum;
}
}
public static void main(String[] args) {
int a = parseInt("");
System.out.println(a);
}
}
Doing a try and catch like in this link suggests would work perfectly
A simple try and catch
I want to check for instance if string "ABCD" contains "DC" string in it in Java. But this is not a substring example, because every time my string and checking characters will change. and I store checking characters into an array, So substring failed, it only works if I have CD, or BC. and I couldn't do match since every time I call checking character from an array. SO what should I do any suggestion
here's some pseudocode to get you started
we'll call "ABCD" the source string and "DC" the target string
change source string to list of chars
change target string to list of chars
for each char in target list of char
if source list does not contain target char
return false;
return true
I use this method for char and byte array. After you got the index of the src array where the sub is matched with, you then can store it anywhere you want.
Try this:
public static int indexOf(char[] src, char[] sub) {
int limit = src.length - sub.length;
int i, j;
for(i = 0; i < limit +1; ++i) {
for(j = 0; j < sub.length; ++j) {
if (src[i+j] != sub[j]) {
break;
}
}
if (j == sub.length)
return i;
}
return -1;
}
Get all the permutation of the source string till it contains the desired sub string
Permutation Logic based on
public static void main(String[] args) {
System.out.println(Test.checkIfContains("ABCD", "DC"));
}
public static Boolean checkIfContains(String main, String check) {
return permutation("", main, check);
}
private static Boolean permutation(String prefix, String main, String check) {
int n = main.length();
if (n == 0) {
if (checkFor(prefix, check)) {
return true;
}
} else {
for (int i = 0; i < n; i++) {
if (permutation(prefix + main.charAt(i), main.substring(0, i) + main.substring(i + 1, n), check)) {
return true;
}
}
}
return false;
}
private static boolean checkFor(String prefix, String check) {
return prefix.contains(check);
}
As I understand it, you want to see if all of the characters of the second string (which I called checkString) are contained in the first string (refString). I would proceed using a function like this
private boolean checkString(String refString, String checkString) {
boolean a;
for (int i; i < checkString.length(); i++) {
for (int j; j < refString.length(); j++) {
a |= checkString.charAt(i) == refString.charAt(j);
}
if (!a) return false;
}
return true;
}
Which return true only when all the characters in checkString are in the reference string.