How would I splice and add these two char arrays? - java

I have this array.
char [] cornStrand = {'G','G','A','G','T','T','C','C','C','A'};
I also have this array, for which the values are inputted by the user running the program.
char [] bacteriaStrand = new char [5];
String strBases = scan.nextLine();
for (int s=0; s <bacteriaStrand.length; s++)
{
char c = strBases.charAt(s);
bacteriaStrand[s]= c ;
}
The second block of code essentially inputs the values that the user entered into the bacteria strand array.
Now comes the tricky part. I need to "splice" and combine both arrays. By this I mean:
If the first character of
char [] bacteriaStrand
is A, then I have to insert
char [] bacteriaStrand
After the first G in
char [] cornStrand
Now, after I splice this, I have to put what I spliced into a new array, called
char [] combinedStrand
This is where I am becoming confused. If anyone can help, please do so! I would gladly appreciate it!

Maybe do something like this:
public char[] combine(char[] bacteriaStrand, char[] cornStrand) {
char[] result = new char[bacteriaStrand.length + cornStrand.length];
if (bacteriaStrand[0] == 'A') {
for (int i = 0; i < cornStrand.length; i++) {
boolean insertedBacteria = false;
if (cornStrand[i] == 'G') {
insertedBacteria = true;
for (int j = 0; j < bacteriaStrand.length; j++) {
result[i + 1 + j] = bacteriaStrand[j];
}
if (insertedBacteria)
i += bacteriaStrand.length;
result[i] = cornStrand[i];
}
}
}
return result;
}

If that is the only rule, it seems pretty simple to do.
if (bacteriaStrand[0] == 'A') {
int totalLength = cornStrand.length + bacteriaStrand.length;
char [] combinedStrand = new char [totalLength];
for(int i=0; i<cornStrand.length; i++){
combinedStrand[i] = cornStrand[i]; //fill in corn until you find the first G
if (cornStrand[i] == 'G') {
int j = 0;
for(; j<bacteriaStrand.length; j++){
combinedStrand[i+j+1] = bacteriaStrand[j]; //fill in bacteria
}
i++;
for(;i<cornStrand.length;i++){
combinedStrand[i+j+1] = cornStrand[i] //fill in the rest of corn
}
}
}//now this loop will break, since you increased i, so you won't get duplicates
}

Related

Java program to find the letter that appears in the most words?

I have a sentence, and I want to find the char that appears in the most words, and how many words it appears in.
For example: "I like visiting my friend Will, who lives in Orlando, Florida."
Which should output I 8.
This is my code:
char maxChar2 = '\0';
int maxCount2 = 1;
for (int j=0; j<strs2.length; j++) {
int charCount = 1;
char localChar = '\0';
for (int k=0; k<strs2[j].length(); k++) {
if (strs2[j].charAt(k) != ' ' && strs2[j].charAt(k) != maxChar2) {
for (int l=k+1; l<strs2[j].length(); l++) {
if (strs2[j].charAt(k)==strs2[j].charAt(l)) {
localChar = strs2[j].charAt(k);
charCount++;
}
}
}
}
if (charCount > maxCount2) {
maxCount2 = charCount;
maxChar2 = localChar;
}
}
, where strs2 is a String array.
My program is giving me O 79. Also, uppercase and lowercase do not matter and avoid all punctuation.
As a tip, try using more meaningful variable names and proper indentation. This will help a lot especially when your program is not doing what you thought it should do. Also starting smaller and writing some tests for it will help a bunch. Instead of a full sentence, get it working for 2 words, then 3 words, then a more elaborate sentence.
Rewriting your code to be a bit more readable:
// Where sentence is: "I like".split(" ");
private static void getMostFrequentLetter(String[] sentence) {
char mostFrequentLetter = '\0';
int mostFrequentLetterCount = 1;
for (String word : sentence) {
int charCount = 1;
char localChar = '\0';
for (int wordIndex = 0; wordIndex < word.length(); wordIndex++) {
char currentLetter = word.charAt(wordIndex);
if (currentLetter != ' ' && currentLetter != mostFrequentLetter) {
for (int l = wordIndex + 1; l < word.length(); l++) {
char nextLetter = word.charAt(l);
if (currentLetter == nextLetter) {
localChar = currentLetter;
charCount++;
}
}
}
}
if (charCount > mostFrequentLetterCount) {
mostFrequentLetterCount = charCount;
mostFrequentLetter = localChar;
}
}
}
Now all I did was rename your variables and change your for loop to a for-each loop. By doing this you can see more clearly your algorithm and what you're trying to do. Basically you're going through each word and comparing the current letter with the next letter to check for duplicates. If I run this with "I like" i should get i 2 but instead I get null char 1. You aren't properly comparing and saving common letters. This isn't giving you the answer, but I hope this makes it more clear what your code is doing so you can fix it.
Here is a somewhat more elegant solution
public static void FindMostPopularCharacter(String input)
{
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
input = input.toUpperCase();
HashMap<Character, Integer> charData = new HashMap<>();
char occursTheMost = 'A'; //start with default most popular char
int maxCount = 0;
//create the map to store counts of all the chars seen
for(int i = 0; i < alphabet.length(); i++)
charData.put(alphabet.charAt(i), 0);
//first find the character to look for
for(int i = 0; i < input.length(); i++)
{
char c = input.charAt(i);
//if contained in our map increment its count
if(charData.containsKey(c))
charData.put(c, charData.get(c) + 1);
//check for a max count and set the values accordingly
if(charData.containsKey(c) && charData.get(c) > maxCount)
{
occursTheMost = c;
maxCount = charData.get(c);
}
}
//final step
//now split it up into words and search which contain our most popular character
String[] words = input.split(" ");
int wordCount = 0;
CharSequence charSequence;
for(Character character : charData.keySet())
{
int tempCount = 0;
charSequence = "" + character;
for(int i = 0; i < words.length; i++)
{
if(words[i].contains(charSequence))
tempCount++;
}
if(tempCount > wordCount)
{
occursTheMost = character;
wordCount = tempCount;
}
}
System.out.println(occursTheMost + " " + wordCount);
}
Output of
String input = "I like visiting my friend Will, who lives in Orlando, Florida.";
FindMostPopularCharacter(input);
is
I 8
Note: If there are ties this will only output the character that first reaches the maximum number of occurrences.
FindMostPopularCharacter("aabb aabb aabb bbaa");
Outputs
B 4
because B reaches the max first before A due to the last word in the input.
FindMostPopularCharacter("aab aab b")
B 3

Reverse a string then swap every nth letter

I've been stuck on this problem for two hours now. Basically I need to reverse a string (which I've done no problem), then swap every nth letter (which is where im stuck).
Here is what I have so far:
public class StringMethods {
public static void main(String[] args) {
String s = "Hey there";
int n = 2;
System.out.println(reverseString(s));
System.out.println(reverseStringChallenge(s, n));
}
private static String reverseString(String s) {
String reversed = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed = reversed + s.charAt(i);
}
return reversed;
}
private static String reverseStringChallenge(String s, int n) {
String reversed = "";
String swapped = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed = reversed + s.charAt(i); // normal reverse
}
char [] charArray = reversed.toCharArray(); //Strings are immutable, convert string to char array
for(int i = 0; i < charArray.length; i++) {
if(i%n == 0) {
//this is where im stuck
}
}
return swapped;
}
}
I know that strings are immutable in java so I need to convert the reversed string into a char array, and then loop through the array but not sure what to do here.
Any advice would be really appreciated. its doing my head in.
Edit: sorry what I mean by swap every nth letter is that say n = 2. then every second letter gets swapped with its previous one.
You didn't clarify the swap logic, but how about something like this:
for(int i = n; i < charArray.length; i += n) {
char a = charArray[i-n];
char b = charArray[n];
charArray[i-n] = b;
charArray[n] = a;
}
Here's a basic swap
int n = 1;
int n1 = 2;
int temp = n; // variable to hold n value
n = n2; // make n = n2
n2 = temp; // make n2 = n
// now n = 2
// and n2 = 1
Not really sure from your question what it is you're trying to do, so I can't really give a definite answer
If you are swapping the current char with the next char you could do something like:
private static String reverseStringChallenge(String s, int n)
{
String reversed = StringUitls.reverse(s);
StringBuilder sb = new StringBuilder();
char [] charArray = reversed.toCharArray();
for(int i = 0; i < charArray.length; i++) {
if(i%n == 0)
{
sb.append(charArray[i+1]).append(charArray[i]);
i++;
}else{
sb.append(charArray[i]);
}
}
return sb.toString();
}
I'm excuse null and out of bound checks =) good luck

Java: Creating a Delimiter Method that has Input/Output

I'm working on a study problem from class and essentially it reads a string, and a character. The character is the delimiter. It will then search the string for the delimiter and create an array in equal length to the number of times the delimiter is found. It then assigns each character or string to its own spot in the array and returns it.
Maybe I am over thinking things, but the just of it is to not rely on the various string methods and to sort of create your own. How can I get this method to only assign the string/char found in the one that is read to one position in the array and not all as well as stop it from adding unnecessary output? Help/Suggestions greatly appreciated
public static String[] explode(String s, char d){
String []c;
int count = 1;
//checks to see how many times the delimter appears in the string and creates an array of corresponding size
for(int i = 0; i < s.length(); i++){
if(d == s.charAt(i))
count ++;
}
c = new String [count];
//used for checking to make sure the correct number of elements are found
System.out.println(c.length);
//goes through the the input string "s" and checks to see if the delimiter is found
//when it is found it makes c[j] equal to what is found
//once it has cycled through the length of "s" and filled each element for c, it returns the array
for(int i = 0; i < s.length(); i++){
for(int j = 0; j < c.length; j++){
if(d == s.charAt(i))
c[j] += s.substring(i-1);
}
}
//provides output for the array [c] just to verify what was found
for(int y = 0; y < c.length; y++)
System.out.println(c[y]);
return c;
}
public static void main(String [] args){
String test = "a,b,c,d";
char key = ',';
explode(test,key);
}
^The following will output:
4
nulla,b,c,db,c,dc,d
nulla,b,c,db,c,dc,d
nulla,b,c,db,c,dc,d
nulla,b,c,db,c,dc,d
I'm aiming for:
4
a
b
c
d
Thank you
Perhaps you could try something like this:
public static void main(String[] args){
explode("a,b,c,d", ',');
}
public static void explode(final String string, final char delimiter){
int length = 1;
for(final char c : string.toCharArray())
if(delimiter == c)
length++;
if(length == 1)
return;
final String[] array = new String[length];
int index, prev = 0, i = 0;
while((index = string.indexOf(delimiter, prev)) > -1){
array[i++] = string.substring(prev, index);
prev = index+1;
}
array[i] = string.substring(prev);
System.out.println(length);
for(final String s : array)
System.out.println(s);
}
Output of the program above is:
4
a
b
c
d
Or if you want to utilize a List<String> instead (and Java 8), you could remove a couple of lines by doing something like this:
public static void explode(final String string, final char delimiter){
final List<String> list = new LinkedList<>();
int index, prev = 0;
while((index = string.indexOf(delimiter, prev)) > -1){
list.add(string.substring(prev, index));
prev = index+1;
}
list.add(string.substring(prev));
System.out.println(list.size());
list.forEach(System.out::println);
}

How do I find out the position of a char

I've got an String ("Dinosaur") and I don't exactly know how, but how do I get the position of the char "o" and is it in all possible to get two positions like if my String was ("Pool")
As for your first question, you can use String#indexOf(int) to get the index of every 'o' in your string.
int oPos = yourString.indexOf('o');
As for your second question, it is possible to get all positions of a given char by making a method which uses String.indexOf(int, int), tracking the previous index so that you don't repeat searched portions of the string. You could store the positions in an array or list.
Use indexOf with a loop:
String s = "Pool";
int idx = s.indexOf('o');
while (idx > -1) {
System.out.println(idx);
idx = s.indexOf('o', idx + 1);
}
Simply:
public static int[] getPositions(String word, char letter)
{
List<Integer> positions = new ArrayList<Integer>();
for(int i = 0; i < word.length(); i++) if(word.charAt(i) == letter) positions.add(i);
int[] result = new int[positions.size()];
for(int i = 0; i < positions.size(); i++) result[i] = positions.get(i);
return result;
}
This is probably going a little over board, but hey ;)
String master = "Pool";
String find = "o";
Pattern pattern = Pattern.compile(find);
Matcher matcher = pattern.matcher(master);
String match = null;
List<Integer[]> lstMatches = new ArrayList<Integer[]>(5);
while (matcher.find()) {
int startIndex = matcher.start();
int endIndex = matcher.end();
lstMatches.add(new Integer[] {startIndex, endIndex});
}
for (Integer[] indicies : lstMatches) {
System.out.println("Found " + find + " # " + indicies[0]);
}
Gives me
Found o # 1
Found o # 2
The great thing is, you could also find "oo" as well
Have you tried converting the String to a char array?
int counter = 0;
String input = "Pool";
for(char ch : input.toCharArray()) {
if(ch == 'o') {
System.out.println(counter);
}
counter += 1;
}
Try this
String s= "aloooha";
char array[] = s.toCharArray();
Stack stack = new Stack();
for (int i = 0; i < array.length; i++) {
if(array[i] == 'o'){
stack.push(i);
}
}
for (int i = 0; i < stack.size(); i++) {
System.out.println(stack.get(i));
}

Counting the number of common chars in a string and a vector of strings

My problem is how to count but not count the same character twice. Like comparing 'aba' to 'are' should give 1 as result since it has only one char in common.
This is where I got so far:
public int sameChars (Vector<String> otherStrs){
int result = 0;
String original = "aba";
for (int h= 0; h< otherStrs.size(); h++) {
String targetStr = otherStrs.get(h);
for (int i=0; i< original.length(); i++) {
char aux = original.charAt(i);
for (int j=0; j< Math.min(original.length(), targetStr.length()); j++) {
char targetAux = targetStr.charAt(j);
if (aux == targetAux) {
result++;
break;
}
}
}
}
return result;
}
Ideas are welcome, thanks.
You can create a hash of character count from the original string. Then for each target string, check if it has a char that has a non-zero value in your hash. This will prevent scanning your original string more than once.
Pseudocode:
For each char c in original string {
hash[c]++
}
For each target string str {
For each char c_ in str {
if hash[c_] > 0 {
result++;
}
}
}
This smells like homework, so here's the just the basic idea: You need to keep track of the distinct characters you've already counted as being in both places. A Set might be a good way to do this. Before incrementing your counter, check to see if the character you're looking at is already in that Set.
I am not sure to understand your requirement: do you want to count the number of times the distinct characters found in the reference string original, here "aba" thus 'a' and 'b', are found in a set of strings stored in the Vector otherStrs?
If that's the case, I would advise first to reduce the original string to distinct characters (looking for and removing duplicates, or using a Map). Then loop over the strings in the Vector and do the same for each string (removing duplicates or using a Map) before incrementing your counter each time a character is found in common.
Just out of curiosity, what is the end goal of this computation?
Here's my implementation:
public static int commonChars(String s1, String s2) {
if (s1 == null || s1.isEmpty())
throw new IllegalArgumentException("Empty s1");
if (s2 == null || s2.isEmpty())
throw new IllegalArgumentException("Empty s2");
char[] a1 = s1.toCharArray();
char[] a2 = s2.toCharArray();
Arrays.sort(a1);
a1 = removeDups(a1);
Arrays.sort(a2);
a2 = removeDups(a2);
int count = 0;
for (int i = 0, j = 0; i < a1.length && j < a2.length;) {
if (a1[i] == a2[j]) {
i++;
j++;
count++;
}
else if (a1[i] > a2[j])
j++;
else
i++;
}
return count;
}
public static char[] removeDups(char[] array) {
char[] aux = new char[array.length];
int c = 1;
aux[0] = array[0];
for (int i = 1 ; i < array.length; i++) {
if (array[i] != array[i-1])
aux[c++] = array[i];
}
return Arrays.copyOf(aux, c);
}

Categories