How can I concat two characters to form another character? - java

I have an arraylist which has a list of characters. Now I want to append another character to a certain character from the list (not to form a String,but a character). How do I do that?
Example- Suppose my arraylist has the elements [E,X,Y,M,...]. Now I want to concat another character called 'X' with E.
My code:
for (int i = 0; i < ar.length; i++) {
if (i == 1) {
list.add(ar[i-1]+'X');
}
}

How can I concat two characters to form another character?
You can't. A character is just that: one character.
When you want to concat characters, you automatically, by definition create a string (which represents a sequence of characters).
As you already know the index you care about, a simple
String result = yourList.get(0) + "X";
should do. (iterating a list to retrieve one element at a known index is a bad idea, just get the value at the index you already know).
And note: lists and array in java start at index 0, not 1. 'E' in your example list has index 0, not 1!

Try below code,
char[] ar = { 'E', 'X', 'Y', 'M' };
List<String> list = new ArrayList<>();
for (int i = 0; i < ar.length; i++) {
if (i == 1) {
list.add(String.valueOf(ar[i - 1]) + 'X');
}
}
System.out.println(list);
Output
[EX]

You can use this code
ArrayList<String> list = new ArrayList<String>();
list.add("E");
list.add("X");
list.add("Y");
list.add("M");
//Printing List
for(int i=0;i<list.size();i++)
{
System.out.print(list.get(i));
}
System.out.println();
//Adding Character X with E
list.add(1, "X");
//Printing List
for(int i=0;i<list.size();i++)
{
System.out.print(list.get(i));
}
It will make the list elements as follows - {E, X, X, Y, M}

"char" is just a "char"!
char holds up to 16-bits (2 bytes) of a single Unicode character.
That means you cannot combine two chars as a "char" (Impossible!)
Your list is qualified to hold "chars" only not "Strings".
"String" make sense!
You can use "StringBuilder" to concatenate two chars, but that would produce a "String", not a "char".
My advice to you is to strengthen your conceptual knowledge of Java.

Related

Alphabet Bucket 2

public static ArrayList<ArrayList<String>> hoops(ArrayList<String> a) {
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>(26);
for (char x = 'a'; x <= 'z'; x++) {
list.add(new ArrayList<String>());
}
for (int y = 0; y < a.size(); y++) {
for (char x = 'a'; x <= 'z'; x++) {
if (String.valueOf(x).equals(a.get(y).substring(0, 1))) {
list.get(x - 97).add(a.get(y));
}
}
}
return list;
}
This is code meant to "Write and test a method that takes a List words, which contains Strings of alphabetic characters, throws them into 26 "buckets", according to the first letter, and returns the ArrayList of buckets. Each bucket should be represented by an ArrayList. The first bucket should contain all the Strings from words that start with an 'a', in the same order as they appear in words; the second bucket should contain all the Strings that start with a 'b'; and so on. Your method should traverse the list words only once and leave it unchanged."
When I run the following code...
public static void main(String[] args) {
ArrayList<String> a = new ArrayList<String>(Arrays.asList("cat", "dog", "person", "beetle", "insect"));
ArrayList<Integer> b = new ArrayList<Integer>(Arrays.asList(1, 3, 2, 5, 3, 0, 1, 3));
System.out.print(hoops(a).get('a'));
}
I get an error message...
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 97, Size: 26
at java.util.ArrayList.rangeCheck(ArrayList.java:659)
at java.util.ArrayList.get(ArrayList.java:435)
at marcoB.Reverse.main(Reverse.java:13)
How can I fix this?
PS. I just asked a question similar to this but I edited my code and implemented x - 97
An 'IndexOutOfBoundsException' occurs when you try to reference or "get" a value at an index of the array that it doesn't have. You are seeing 97 come up in the error message because of this line in your main method:
System.out.print(hoops(a).get('a'));
'a' in this case turns into it's ASCII value of 97 (see http://www.asciitable.com/ for more), which is out of the range of the ArrayList you are referencing (26). So either do a get(0) or a get('a'-97) if you want to keep the rest of your implementation the same and get the list which contains the 'a' characters.
There are definitely fancier ways to go about printing the list at a certain character if you go deeper into this.
I would also suggest making your variable names more meaningful in your loops. For example, changing x to letter and y to word might be easier for you to keep track of rather than x and y, especially when you start working with more complicated looping structures.

Find every possible subset given a string [duplicate]

This question already has answers here:
Memory efficient power set algorithm
(5 answers)
Closed 8 years ago.
I'm trying to find every possible anagram of a string in Java - By this I mean that if I have a 4 character long word I want all the possible 3 character long words derived from it, all the 2 character long and all the 1 character long. The most straightforward way I tought of is to use two nested for loops and iterare over the string. This is my code as of now:
private ArrayList<String> subsets(String word){
ArrayList<String> s = new ArrayList<String>();
int length = word.length();
for (int c=0; c<length; c++){
for (int i=0; i<length-c; i++){
String sub = word.substring(c, c+i+1);
System.out.println(sub);
//if (!s.contains(sub) && sub!=null)
s.add(sub);
}
}
//java.util.Collections.sort(s, new MyComparator());
//System.out.println(s.toString());
return s;
}
My problem is that it works for 3 letter words, fun yelds this result (Don't mind the ordering, the word is processed so that I have a string with the letters in alphabetical order):
f
fn
fnu
n
nu
u
But when I try 4 letter words, it leaves something out, as in catq gives me:
a
ac
acq
acqt
c
cq
cqt
q
qt
t
i.e., I don't see the 3 character long word act - which is the one I'm looking for when testing this method. I can't understand what the problem is, and it's most likely a logical error I'm making when creating the substrings. If anyone can help me out, please don't give me the code for it but rather the reasoning behind your solution. This is a piece of coursework and I need to come up with the code on my own.
EDIT: to clear something out, for me acq, qca, caq, aqc, cqa, qac, etc. are the same thing - To make it even clearer, what happens is that the string gets sorted in alphabetical order, so all those permutations should come up as one unique result, acq. So, I don't need all the permutations of a string, but rather, given a 4 character long string, all the 3 character long ones that I can derive from it - that means taking out one character at a time and returning that string as a result, doing that for every character in the original string.
I hope I have made my problem a bit clearer
It's working fine, you just misspelled "caqt" as "acqt" in your tests/input.
(The issue is probably that you're sorting your input. If you want substrings, you have to leave the input unsorted.)
After your edits: see Generating all permutations of a given string Then just sort the individual letters, and put them in a set.
Ok, as you've already devised your own solution, I'll give you my take on it. Firstly, consider how big your result list is going to be. You're essentially taking each letter in turn, and either including it or not. 2 possibilities for each letter, gives you 2^n total results, where n is the number of letters. This of course includes the case where you don't use any letter, and end up with an empty string.
Next, if you enumerate every possibility with a 0 for 'include this letter' and a 1 for don't include it, taking your 'fnu' example you end up with:
000 - ''
001 - 'u'
010 - 'n'
011 - 'nu'
100 - 'f'
101 - 'fu' (no offense intended)
110 - 'fn'
111 - 'fnu'.
Clearly, these are just binary numbers, and you can derive a function that given any number from 0-7 and the three letter input, will calculate the corresponding subset.
It's fairly easy to do in java.. don't have a java compiler to hand, but this should be approximately correct:
public string getSubSet(string input, int index) {
// Should check that index >=0 and < 2^input.length here.
// Should also check that input.length <= 31.
string returnValue = "";
for (int i = 0; i < input.length; i++) {
if (i & (1 << i) != 0) // 1 << i is the equivalent of 2^i
returnValue += input[i];
}
return returnValue;
}
Then, if you need to you can just do a loop that calls this function, like this:
for (i = 1; i < (1 << input.length); i++)
getSubSet(input, i); // this doesn't do anything, but you can add it to a list, or output it as desired.
Note I started from 1 instead of 0- this is because the result at index 0 will be the empty string. Incidentally, this actually does the least significant bit first, so your output list would be 'f', 'n', 'fn', 'u', 'fu', 'nu', 'fnu', but the order didn't seem important.
This is the method I came up with, seems like it's working
private void subsets(String word, ArrayList<String> subset){
if(word.length() == 1){
subset.add(word);
return;
}
else {
String firstChar = word.substring(0,1);
word = word.substring(1);
subsets(word, subset);
int size = subset.size();
for (int i = 0; i < size; i++){
String temp = firstChar + subset.get(i);
subset.add(temp);
}
subset.add(firstChar);
return;
}
}
What I do is check if the word is bigger than one character, otherwise I'll add the character alone to the ArrayList and start the recursive process. If it is bigger, I save the first character and make a recursive call with the rest of the String. What happens is that the whole string gets sliced in characters saved in the recursive stack, until I hit the point where my word has become of length 1, only one character remaining.
When that happens, as I said at the start, the character gets added to the List, now the recursion starts and it looks at the size of the array, in the first iteration is 1, and then with a for loop adds the character saved in the stack for the previous call concatenated with every element in the ArrayList. Then it adds the character on its own and unwinds the recursion again.
I.E., with the word funthis happens:
f saved
List empty
recursive call(un)
-
u saved
List empty
recursive call(n)
-
n.length == 1
List = [n]
return
-
list.size=1
temp = u + list[0]
List = [n, un]
add the character saved in the stack on its own
List = [n, un, u]
return
-
list.size=3
temp = f + list[0]
List = [n, un, u, fn]
temp = f + list[1]
List = [n, un, u, fn, fun]
temp = f + list[2]
List = [n, un, u, fn, fun, fu]
add the character saved in the stack on its own
List = [n, un, u, fn, fun, fu, f]
return
I have been as clear as possible, I hope this clarifies what was my initial problem and how to solve it.
This is working code:
public static void main(String[] args) {
String input = "abcde";
Set<String> returnList = permutations(input);
System.out.println(returnList);
}
private static Set<String> permutations(String input) {
if (input.length() == 1) {
Set<String> a = new TreeSet<>();
a.add(input);
return a;
}
Set<String> returnSet = new TreeSet<>();
for (int i = 0; i < input.length(); i++) {
String prefix = input.substring(i, i + 1);
Set<String> permutations = permutations(input.substring(i + 1));
returnSet.add(prefix);
returnSet.addAll(permutations);
Iterator<String> it = permutations.iterator();
while (it.hasNext()) {
returnSet.add(prefix + it.next());
}
}
return returnSet;
}

multiply string element per int element from two arrays Java

I am learning Java and looking for a comprehensive code of multiplying the elements from 2 arrays, possibly without importing anything to achieve it.
In Python it's quite easy:
a=['a','b','c','d']
b=[1,2,3,4]
[x*y for x,y in zip(a,b)]
['a', 'bb', 'ccc', 'dddd']
How can I achieve the same thing in Java, when the first array is an array of strings and the second is integers?
I'm afraid Java isn't going to support this kind of thing natively, and you'll need to perform some of your own logic to implement it. Let's say you've got your String[]..
String[] a = {"a", "b", "c", "d"};
And you've got your int[]..
int[] b = {1,2,3,4};
Next, you'll need to check that the arrays are the same size.
if(a.length == b.length) {
// Continue.
}
Then you need to implement a loop, to go through each item in the arrays.
for(int x = 0; x < a.length; x++)
{
// Some looping code.
}
And you're going to grab each item.
String value = a[x];
int multiplier = b[x];
If you're not importing anything, you declare the total value:
String total = "";
But if you're allowing for a StringBuilder, then you'll import it and declare..
StringBuilder total = new StringBuilder();
NOTE: StringBuilder is strongly recommended here.
And then you're looping multiplier amount of times..
for(int y = 0; y < multiplier; y++)
{
// If you use StringBuilder..
total.append(value);
// If you don't..
total += value;
}
// If you use StringBuilder..
a[x] = total.toString();
// If you don't...
a[x] = total;
This will set the value of a[x] to the repeated String.
NOTE: Something that's also important is leaning good practise. If you're using Java code, it's considered terrible practise to repeatedly concatenate String objects. StringBuilder is more efficient, and is the Java standard. I would strongly recommend using this.
Have fun putting it all together!!
To create string filled with multiple instances of same character like "ccc" you can firs create array of characters which will hold only 3 characters like
char[] myCharacters = new char[3];
Now this array is filled with zeroes ('\0'), so you need to fill it with desired character 'c'. You simply do it using for loop
for (int i = 0; i<myCharacters; i++){
myCharacters[i] = 'c';
}
After this your array will contain ['c', 'c', 'c'].
Now you can use this array to create string using characters from it. To do so you just need to pass this array to String constructor like
String myString = new String(myCharacters);
And there you go. Now you have "ccc" String. Repeat these steps for each pair of elements from a and b arrays.
You can also use shorter version which kinds of do the same
String myString = new String(new char[3]).replace('\0','c');//will produce "ccc"

Count of Each Alphabet using Array

I have a string as an input eg. Testerty. I want to find the count of each alphabet in the string. I have tried using a HashMap. But I want to implement this using array.
Can you please suggest some way.
You can use ASCII to assign the letters number values:
int[] letters = new int[128]; // There are 128 different possible characters.
for(int i = 0; i < input.length; i++) {
char current = input.charAt(i);
int index = Character.getNumericValue(char);
letters[index]++;
}
ArrayList<Character> ch = new ArrayList<Character>();
ArrayList<Integer> count = new ArrayList<Integer>();
someMethod(String input) {
for(char c : input.toCharArray()) {
if(ch.indexOf(c) != -1) {
i.set(ch.indexOf(c), i.get(ch.indexOf(c))+1);
} else {
ch.add(c);
i.add(1);
}
}
}
doing it with a Map is easier, where the letters are keys and the values are counts. Using an array is more tricky; you could assign each letter a number, and use that number as an index into the array, and store the counts in the array. So 'A' is 1, 'B' is 2, etc....The algorithm is
Get next letter of string.
Get the index for the letter.
Increment the value at that index in the array by 1.
Of course you need to do null checking and whatever.
Note that this is logically a Map. It's just when you use a Map, the Map does step 2 above for you.
You should use a collection implementing Multiset iunterface, i.e. HashMultiset (both taken from Google Guava library). Multiset is designed to hold counts for objects in collection:
Multiset<String> m = HashMultiset.create(Arrays.asList("a", "a", "b", "c", "b", "a"));
// m.toString() prints "a x 3, b x 2, c x 1"
// m.count() gives 6
One way could be, you first create an array, then traverse string using charAt(index) method ,match the current char against those in the array.If you find the match ,increment the value there,or add it as a new entry in the array.

Replace substring with a regex combination

Since I'm not that familiar with java, I don't know if there's a library somewhere that can do this thing. If not, does anybody have any ideas how can this be accomplished?
For instance I have a string "foo" and I want to change the letter f with "f" and "a" so that the function returns a list of strings with values "foo" and "aoo".
How to deal with it when there's more of the same letters? "ffoo" into "ffoo", "afoo", "faoo", "aaoo".
A better explanation:
(("a",("a","b)),("c",("c","d")))
Above is a group of characters that need to be replaced with a character from the other element. "a" is to be replaced with "a" and with "b". "c" is to be replaced with "c" and "d".
If I have a string "ac", the resulting combinations I need are:
"ac"
"bc"
"ad"
"bd"
If the string is "IaJaKc", the resulting combinations are:
"IaJaKc"
"IbJaKc"
"IaJbKc"
"IbJbKc"
"IaJaKd"
"IbJaKd"
"IaJbKd"
"IbJbKd"
The number of combinations can be calculated like this:
(replacements_of_a^letter_amount_a)*(replacements_of_c^letter_amount_c)
first case: 2^1*2^1 = 4
second case: 2^2*2^1 = 8
If, say, the group is (("a",("a","b)),("c",("c","d","e"))), and the string is "aac", the number of combinations is:
2^2*3^1 = 12
Here is the code for your example with foo and aoo
public List<String> doSmthTricky (String str) {
return Arrays.asList("foo".replaceAll("(^.)(.*)", "$1$2 a$2").split(" "));
}
For the input "foo" this method returns a list with 2 strings "foo" and "aoo".
It works only if there is no whitespaces in your input string ("foo" in your example). Otherwise it's a bit more complicated.
How to deal with it when there's more of the same letters? "ffoo" into "ffoo", "afoo", "faoo", "aaoo".
I doubt that regular expressions could help here, you want to generate strings based on initial string, it's not a task for regexp.
UPD: I've created a recursive function (actually it's half-recursive half-iterative) which generates strings based on the template string by replacing its first characters with characters from a specified set:
public static List<String> generatePermutations (String template, String chars, int depth, List<String> result) {
if (depth <= 0) {
result.add (template);
return result;
}
for (int i = 0; i < chars.length(); i++) {
String newTemplate = template.substring(0, depth - 1) + chars.charAt(i) + template.substring(depth);
generatePermutations(newTemplate, chars, depth - 1, result);
}
generatePermutations(template, chars, depth - 1, result);
return result;
}
Parameter #depth means how many characters from the beginning of string should be replaced. Number of permutations (chars.size() + 1) ^ depth.
Tests:
System.out.println(generatePermutations("ffoo", "a", 2, new LinkedList<String>()));
Output: [aaoo, faoo, afoo, ffoo]
--
System.out.println(generatePermutations("ffoo", "ab", 3, new LinkedList<String>()));
Output: [aaao, baao, faao, abao, bbao, fbao, afao, bfao, ffao, aabo, babo, fabo, abbo, bbbo, fbbo, afbo, bfbo, ffbo, aaoo, baoo, faoo, aboo, bboo, fboo, afoo, bfoo, ffoo]
I'm not sure what you need. Please specify source and the result you expect. Anyway, you should use standard java classes for that purpose: java.util.regex.Pattern, java.util.regex.Matcher. If you need to deal with the repeating letters in the beginning, then there is two ways, use symbol "^" - which means beginning of the line, or for the same purpose you can use "\w" shortcut, which means beginning of the word. In more sophisticated cases, please take a look at "lookbehind" expressions. There are more than complete descriptions of these techniques you can find in java doc for java.util.regex and if it's not enough look at www.regular-expressions.info good luck.
Here it is:
public static void returnVariants(String input){
List<String> output = new ArrayList<String>();
StringBuffer word = new StringBuffer(input);
output.add(input);
String letters = "ac";
int lettersLength = letters.length();
int wordLength = word.length();
String replacement = "";
for (int i = 0; i < lettersLength; i++) {
for (int j = 0; j < wordLength; j++) {
if(word.charAt(j)==letters.charAt(i)){
if (word.charAt(j)=='a'){
replacement = "ab";
}else if (word.charAt(j)=='c'){
replacement = "cd";
}
List<String> tempList = new ArrayList<String>();
for (int k = 0; k < replacement.length(); k++) {
for (String variant : output){
StringBuffer tempBuffer = new StringBuffer(variant);
String combination = tempBuffer.replace(j, j+1, replacement.substring(k, k+1)).toString();
tempList.add(combination);
}
}
output.addAll(tempList);
if (j==0){
output.remove(0);
}
}
}
}
Set<String> uniqueCombinations = new HashSet(output);
System.out.println(uniqueCombinations);
}
If input is "ac", the combinations returned are "ac", "bc", "ad", "bd". If it can be optimized further, any additional help is welcome and appreciated.

Categories