Remix the String - java

I am stuck with this challenge, any help would be great.
'Create a function that takes both a string and an array of numbers as arguments. Rearrange the letters in the string to be in the order specified by the index numbers. Return the "remixed" string. Examples
remix("abcd", [0, 3, 1, 2]) ➞ "acdb"'
My attempt -
package edabitChallenges;
//Create a function that takes both a string and an array of numbers as arguments.
//Rearrange the letters in the string to be in the order specified by the index numbers.
//Return the "remixed" string.
public class RemixTheString {
public static String remix(String word, int[] array) {
char[] wordArray = word.toCharArray();
for (int i = 0; i < array.length; i++) {
char ch = ' ';
ch = wordArray[i];
wordArray[i] = wordArray[array[i]];
wordArray[array[i]] = ch;
}
String newString = new String(wordArray);
return newString;
}
public static void main(String[] args) {
System.out.println(remix("abcd", new int[] { 0, 3, 1, 2 }));
}
}

I would suggest just iterating the indices passed in the array[] input, and then building out the output string:
public static String remix(String word, int[] array) {
char[] wordArray = word.toCharArray();
StringBuilder output = new StringBuilder();
for (int i=0; i < array.length; i++) {
output.append(wordArray[array[i]]);
}
return output.toString();
}
public static void main(String[] args) {
System.out.println(remix("abcd", new int[] { 0, 3, 1, 2 })); // adbc
}
Here we use StringBuilder which exposes a handy append(char) method for adding one character at a time to the string in progress.

Related

How can I get the value of a variable from a class?

So I'm new to java and decided to mess around a little, I wrote a class that converts a string to an array made out of the ascii values of the characters in the string, but I don't know how to get the value of the variable i. I know it's easier to use a list but I'm really curious how to make this work. This is the code:
public class ToAscii {
static int[] toAscii(String txt){
int[] array = new int[1000];
int i = 0;
char[] ascii1 = txt.toCharArray();
for(char ch:ascii1){
array[i] = ch -1;
i++;
}
return array;
}
}
The problem with your code is ch -1 which should be just ch.
You should do it as follows:
import java.util.Arrays;
public class ToAscii {
public static void main(String[] args) {
// Test
System.out.println(Arrays.toString(toAscii("aBc")));
}
static int[] toAscii(String txt){
int[] array = new int[txt.length()];
int i = 0;
char[] ascii1 = txt.toCharArray();
for(char ch:ascii1){
array[i] = ch;
i++;
}
return array;
}
}
Output:
[97, 66, 99]
Alternatively, you can do it as follows:
import java.util.Arrays;
public class ToAscii {
public static void main(String[] args) {
// Test
System.out.println(Arrays.toString(toAscii("aBc")));
}
static int[] toAscii(String txt) {
int[] array = new int[txt.length()];
char[] ascii1 = txt.toCharArray();
for (int i = 0; i < array.length; i++) {
array[i] = ascii1[i];
}
return array;
}
}
Output:
[97, 66, 99]
txt.codePoints().toArray() will convert the String to codepoints (ie numbers of the characters).
For example:
import java.util.Arrays;
public class Main {
public static void main(final String[] args) {
System.out.println(Arrays.toString("abc".codePoints().toArray()));
}
}
will print:
[97, 98, 99]
where 97 corresponds to 'a', 98 to 'b' and 99 to 'c'.

Leetcode 833: String replacement depend upon index numbering

String index value accessThis question is a part of my previous question .
Example 1:
Input: S = "abcd", indexes = [0,2], sources = ["a","cd"], targets = ["eee","ffff"]
Output: eeebffff
Explanation: a starts at index 0 in S, so it's replaced by eee.
cd starts at index 2 in S, so it's replaced by ffff.
Example 2:
Input: S = "abcd", indexes = [0,2], sources = ["ab","ec"], targets = ["eee","ffff"]
Output: "eeecd"
Explanation: "ab" starts at index 0 in S, so it's replaced by "eee".
"ec" doesn't starts at index 2 in the original S, so we do nothing.
public class Q833 {
public static void main(String args[]){
String S="abcd";
int[] indexes = {0, 2};
String[]sources={"ab","cd"};
String[] targets = {"eee", "ffff"};
Solve833 ob833=new Solve833();
System.out.println(ob833.findReplaceString(S,indexes,sources,targets));
}
}
class Solve833{
public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) {
char[] array = S.toCharArray();
StringBuilder result = new StringBuilder();
int counter = 0;
String s = "";
for (String n:sources)
s+= n;
char[] c = s.toCharArray();
for (int i = 0; i < array.length; i++) {
if(array[indexes[counter]]==c[counter]){
result.append(targets[counter]);
if(counter<=indexes.length) {
counter++;
}
}
else
result.append(array[i]);
}
return result.toString();
}
}
Code Output: for 1st example
Expected output:Output: "eeebffff".
My output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Leetcode.Solve833.findReplaceString(Q833.java:30) at
Leetcode.Q833.main(Q833.java:16)
Code Output:2nd example
Expected Output: "eeecd"
My Output: eeebcd. So here a b missing. How can I handle it?
Your problem is that you should NOT do array[indexes[counter]]==c[counter] to determine that if the i-thsource string is presented in the S at index i. Your juegement only check for the first character of the source string.
The key of this problem is how can we find the index correctly, as when we are trying to get the result, the index(where to replce the source string with target string) may change.
try this code:
public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) {
StringBuilder sb=new StringBuilder(S);
int[] offsets=new int[indexes.length];
for(int i=0;i<indexes.length;i++){
if(S.substring(indexes[i],indexes[i]+sources[i].length()).equals(sources[i])){
int offset=0;
for(int j=0;j<i;j++){
if(indexes[j]<indexes[i])
offset+=offsets[j];
}
sb.replace(indexes[i]+offset,indexes[i]+sources[i].length()+offset,targets[i]);
offsets[i]=targets[i].length()-sources[i].length();
}
}
return sb.toString();
}
You can change your method like this to print the result,
public class Q833 {
public static void main(String args[]) {
String S = "abcd";
int[] indexes = {0, 2};
String[] sources = {"a", "cd"};
String[] targets = {"eee", "ffff"};
Solve833 ob833 = new Solve833();
System.out.println(ob833.findReplaceString(S, indexes, sources, targets));
}
}
class Solve833 {
public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) {
StringBuffer result = new StringBuffer(S);
for (int i = 0; i < indexes.length; i++) {
if (sources[i].equals(result.substring(indexes[i], indexes[i] + sources[i].length()))) {
result.replace(indexes[i], indexes[i] + sources[i].length(), targets[i]);
if (i < indexes.length - 1)
indexes[i + 1] = indexes[i + 1] + targets[i].length() - sources[i].length();
}
}
return result.toString();
}
}

Java Algorithm regarding taking array of String and Integers to

I'm currently doing an activity that requires me to write this:
Write a definition for a static method stringHeads that inputs an array of ints p and a String s. For each of the ints n in p, the method builds the substring consisting of the first n characters in s (or the whole of s, if n is greater than the length of s). The method returns the array of these substrings.
My code is currently something like this:
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
for (int b : p)
e = b - 1
for (int de = 0; rad.length > de; de++)
rad[de] = s.substring(0,e);
for (String str : rad)
return str;
}
//Just ignore the rest
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon"
stringHeads(a,b)
The output should be "Rado" , "Ra", "Rad", "Ra", "".
The error that I'm currently getting is that String cannot be converted to String[].
Basically my question is how to fix this error and if a better code can be written.
Three things:
e would be constant if you enter the second loop.
e could be larger than s.length() - you didn't handle this case.
You return a String instead of a String[]
And please always use braces if you use loops, even if the loop only contains one statement. It is much more readable and can avoid errors.
I think you will have to rethink your whole function. Don't know if it would be helpful to write the function for you.
Hints:
Write only one loop!
String[] rad = new String[p.length];
for (int i=0; i < p.length; i++) {
if (s.length() < ??) {
rad[i] = s.substring(0,??);
} else {
??
}
}
return rad;
I hope this will help you to get the answer yourself.
See my code below hope it helps:-
I provided the comments instead of explaining it in paragraph.
As for your error, you are returning String from method but expected is an array of String.
public static void main(String[] args){
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon";
String[] output=stringHeads(a,b);
for(String s:output){
System.out.println(s);
}
}
Your method can be like below:
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
//Iterate over integer array
for(int index=0; index<p.length; index++){
//Extracting the integer value from array one by one
e=p[index];
//If integer value is greater than String length
if(e>s.length()){
//Put the entire String in String array
rad[index]=s;
}else{
//Put the Substring value with range 0 to e i.e. integer value
rad[index]=s.substring(0,e);
}
}
return rad;
}
You could simplify you code by just using a single iteration with an alternative variable.
public static void main (String[] args) throws java.lang.Exception
{
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon";
String[] result = stringHeads(a,b);
for(String x : result) System.out.println(x);
//Or you can write a separate display method instead.
}
public static String[] stringHeads(int[] p, String s)
{
String[] rad = new String[p.length];
//Use this variable for array allocation/iteration.
int i=0;
//Simply iterate using this for-each loop.
// This takes care of array allocation/ substring creation.
for (int x : p)
rad[i++] = s.substring(0,x);
return rad;
}
Please check the code below
public static String[] stringHeads(int[] intArray, String str) {
String[] result = new String[intArray.length];
int count=0;
for (int intValue : intArray)
{
result[count] = str.substring(0,intValue);
count++;
}
return result;
} //Just ignore the rest
public static void main(String[] args) {
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon";
String[] strArray=stringHeads(a,b);
int count=0;
for(String str:strArray)
System.out.println(++count+"" +str);
}
Change your method like this
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
for (int b : p) {
rad[e] = s.substring(0, b);
e++;
}
return rad;
}
For use this method
public static void main(String[] args) {
int[] a = {4, 2, 3, 2, 0};
String b = "Radon";
String[] stringHeads = stringHeads(a, b);
for (String stringHead : stringHeads) {
System.out.println(stringHead);
}
}
Output is
Rado
Ra
Rad
Ra
There is no need for the for loop that iterates through the integer array p
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
for (int de = 0; de < p.length; de++){
if (p[de] < s.length())
rad[de] = s.substring(0,p[de]);
else
rad[de]=s;
}
return rad;
}
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
for (int b : p) {
if(b<=s.length()){
rad[e] = s.substring(0, b);
}
e++;
}
return rad;
}

Is there any method or idea that can select characters from a string at indices which are multiple of given 'n' to get the result string?

If I have this string
String str="characters";
the result would like following
result="caatr";
what I have done is selecting char by char from the given string until we get the result. The chars are selected at indices which are multiples of given n. Example: if n=2, the relevant indices to be selected are 0, 2, 4 ... and for n = 3, the indices are 0, 3, 6...
I have solved it in two ways and are almost the same but is there any other ways?
char[] arr = str.toCharArray();
String s="";
for(int i=0;i<str.length();i=i+n)
s=s+arr[i]+"";
the other one is
String result = "";
for (int i=0; i<str.length(); i = i + n)
result = result + str.charAt(i);
public static void main(String args[]) {
System.out.println(getResultOf("characters"));
}
private static String getResultOf(String input) {
boolean skip = false;
StringBuilder sb = new StringBuilder();
for (char ch : input.toCharArray()) {
if (!skip) {
sb.append(ch);
}
skip = !skip;
}
return sb.toString();
}

String concatenation as character array (without library method)

I want to store the value of 2 strings str1, str2 respectively into 3rd string strContainer (without using library method).
My Algorithm is:
1. convert str1 and str2 into character array charArray1 and charArray2 respectively.
2. Count the sum of the length of both character array in counter variable (sum of the length charArray and charArray2)
3. Sum of the both char Arrays (as counter) is equivalent to a new char Array charContainer.
4. Iterate a loop as below
charContainer[ith index] += charArray1[ith index];
and
charContainer[ith index] += charArray2[ith index];
5. Convert charContainer into string and display as strContainer.
My code so far:
public class StringConcat{
int counter; // counting the length of char arrays
String str1 = "FirstString";
String str2 = "SecondString";
//for counting the length of both char arrays
public int countingLength(String str){
char[] strToCharArray = str.toCharArray();
for(char temp : strToCharArray){
counter++;
}
}
//converting string into char array
char[] charArray1 = str1.tocharArray();
char[] charArray2 = str1.tocharArray();
//stores both char array
char[] charContainer=new char[counter];//how to take counter as an index value here
//for storing charArray1 into charContainer
for(int i=0; i<charContainer.length; i++) {
if(charArray1 != null){
charContainer[i] += charArray1[i];
} else
return charArray2;
}
//for storing charArray2 into charContainer
for(int i=0; i<charContainer.length; i++) {
if(charArray2 != null){
charContainer[i] += charArray1[i];
} else
return charArray1;
}
//converting charContainer char array into string strContainer.
String strContainer = new String(charContainer);
//alternative : String strContainer = String.valueOf(charContainer);
public static void main(String args[]){
/*Here i can call (As i'm not sure)
StringConcat obj1 = new StringConcat();
obj1.countingLength(str1);
StringConcat obj2 = new StringConcat();
obj2.countingLength(str2);
*/
System.out.println("String Container : " +strContainer);
}
}//end of the class
Issues:
How to call countingLength() method for both strings str1 and str2 ?
How to assign as an index value of charContainer as counter (sum of the both char arrays) ?
How to call StringLengthCounter() method? I can't see any method with that name.. I'm sorry but that is not the problem here, the problem is that this is not even valid code.
I don't mean to be harsh but there are sintax error all around and the program logic is wrong in many ways.
Please take a look at the following code and try to figure out how it works, I think it does what you want.
If something isn't clear just ask.
public class StringConcat{
public static String strcat(String str1, String str2){
//converting string into char array
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
int counter=charArray1.length+charArray2.length;
//stores both char array
char[] charContainer=new char[counter];
//for storing charArray1 into charContainer
int i=0;
for(; i<charArray1.length; i++) {
charContainer[i]=charArray1[i];
}
//for storing charArray2 into charContainer
for(int j=0; i<counter; j++,i++) {
charContainer[i]=charArray2[j];
}
//converting charContainer char array into string
return new String(charContainer);
}
public static void main(String args[]){
String str1 = "FirstString";
String str2 = "SecondString";
String strContainer = strcat(str1,str2);
System.out.println("String Container : " +strContainer);
}
}//end of the class
import java.io.*;
class Concatenation
{
public static void main(String []args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i=0;
String s1,s2;
System.out.print("Enter the first string:");
s1=br.readLine();
System.out.print("Enter the Second string:");
s2=br.readLine();
char s3[]=new char[s1.length()+s2.length()];
for(;i<s1.length();i++)
s3[i]=s1.charAt(i);
for(int j=0;j<s2.length();j++)
s3[i++]=s2.charAt(j);
System.out.println("Result:"+new String(s3));
}
}
public class Conc {
String s1="java",s2="programming",s3="";
int l=s1.length(),m=s2.length(),i,j;
public String conca(String s1,String s2){
for(i=0;i<=l-1;i++){
s3+=s1.charAt(i);
}
for(j=0;j<=m-1;j++){
s3+=s2.charAt(j);
}
System.out.println(s3);
return s3;
}
public static void main(String[] args) {
Conc obj1=new Conc();
obj1.conca("java","programming");
}
}
public class StringConcatination {
public static String concate(String s1,String s2){
String s3="";
for(int i=0;i<s1.length();i++){
s3+=s1.charAt(i);
}
for(int j=0;j<s2.length();j++){
s3+=s2.charAt(j);
}
return s3;
}
public static void main(String[] args) {
System.out.println(concate("java","programming"));
}
}
public static void concat(String a, String b) {
/**
* String result = a + b;
*/
/**
* Logic goes here.
*
* Need to iterate through chars
*
* Need to get total length
*/
int totalLength = a.length();
totalLength += b.length();
char[] result = new char[totalLength];
char[] arrayFromA = a.toCharArray();
char[] arrayFromB = b.toCharArray();
int count = 0;
System.out.println("Total Length of String: "+ totalLength);
for (int i = 0; i < arrayFromA.length; i++) {
result[i] = arrayFromA[i];
count++;
}
for (int j = 0; j < arrayFromB.length; j++) {
result[count] = arrayFromB[j];
count++;
}
System.out.println(new String(result));
}

Categories