I was trying out this question :
Write a function using Recursion to display all anagrams of a string entered by the user, in such a way that all its vowels are located at the end of every anagram. (E.g.: Recursion => Rcrsneuio, cRsnroieu, etc.) Optimize it.
From this site :
http://erwnerve.tripod.com/prog/recursion/magic.htm
This is what i have done :
public static void permute(char[] pre,char[] suff) {
if (isEmpty(suff)) {
//result is a set of string. toString() method will return String representation of the array.
result.add(toString(moveVowelstoEnd(pre)));
return;
}
int sufflen = getLength(suff); //gets the length of the array
for(int i =0;i<sufflen;i++) {
char[] tempPre = pre.clone();
char[] tempSuf = suff.clone();
int nextindex = getNextIndex(pre); //find the next empty spot in the prefix array
tempPre[nextindex] = tempSuf[i];
tempSuf = removeElement(i,tempSuf); //removes the element at i and shifts array to the left
permute(tempPre,tempSuf);
}
}
public static char[] moveVowelstoEnd(char[] input) {
int c = 0;
for(int i =0;i<input.length;i++) {
if(c>=input.length)
break;
char ch = input[i];
if (vowels.contains(ch+"")) {
c++;
int j = i;
for(;j<input.length-1;j++)
input[j] = input[j+1];
input[j]=ch;
i--;
}
}
return input;
}
Last part of the question is 'Optimize it'. I am not sure how to optimize this. can any one help?
Group all the vowels into v
Group all consonants into w
For every pair of anagrams, concat the results
Related
I have to create a vowel counter and sorter, where someone can input a word or phrase and the program picks out, counts, and sorts the vowels. I have the code to where it counts and sorts the variables and shows their counts to the user, but it doesn't say which vowel has which count and I have exhausted all of my resources. I am very new to coding and know very little, so if there's anything anyone can do to help, I would appreciate it endlessly.
int[] vowelcounter = {a, e, i, o, u}; //This is the count of the vowels after reading the input.
boolean hasswapped = true;
while(hasswapped)
{
hasswapped = false;
for(int j = 0; j<vowelcounter.length; j++)
{
for(int k = j+1; k<vowelcounter.length; k++)
{
if(vowelcounter[j] > vowelcounter[k])
{
int temp = vowelcounter[j];
vowelcounter[j] = vowelcounter[j+1];
vowelcounter[j+1] = temp;
hasswapped = true;
}
}
}
}
for(int j=0; j<vowelcounter.length; j++)
{
System.out.println(vowelcounter[j]);
}
Instead of int value to represent a counter, a class may be introduced to store and print both the vowel character and its count:
class VowelCount {
private final char vowel;
private int count = 0;
public VowelCount(char v) {
this.vowel = v;
}
public void add() { this.count++; }
public int getCount() { return this.count; }
public char getVowel() { return this.vowel; }
#Override
public String toString() { return "Vowel '" + vowel + "' count = " + count;}
}
Then instead of int[] count an array of VowelCount is created and sorted:
VowelCount[] vowelcounter = {
new VowelCount('a'), new VowelCount('e'), new VowelCount('i'),
new VowelCount('o'), new VowelCount('u')
};
Sorting may be implemented using standard method Arrays::sort with a custom comparator instead of home-made bubble sorting
Arrays.sort(vowelcounter, Comparator.comparingInt(VowelCount::getCount));
Then printing of the stats is as follows (using for-each loop along with the overriden toString):
for (VowelCount v: vowelcounter) {
System.out.println(v); // print sorted by count
}
More advanced ways of calculating the frequencies is to use a map of vowels to their frequencies and sort the map by counter value.
You can use something that is called HashMap
HashMap<String, Integer> vowelCounts = new HashMap<>();
To add data to it just do:
vowelCounts.put("a", 1); // The vowel "a" is once in the sentence
vowelCounts.put("e", 2); // The vowel "e" is 2 times in the sentence
To print to the console:
for(String vowel : vowelCounts.keySet() ) {
System.out.println(vowel + ": " + vowelCounts.get(vowel));
}
For more info: click me!
Have a char[] vowels = { 'a', 'e', 'i', 'o', 'u' }. Every time you swap the counters, make an identical swap in the vowels array.
int temp = vowelcounter[j];
vowelcounter[j] = vowelcounter[j+1];
vowelcounter[j+1] = temp;
char temp2 = vowel[j];
vowel[j] = vowel[j+1];
vowel[j+1] = temp2;
hasswapped = true;
At the end, print out vowel[j] next to vowelcounter[j];
I am trying to write a method which returns the number of times the first character of a string appears throughout the string. This is what I have so far,
public int numberOfFirstChar0(String str) {
char ch = str.charAt(0);
if (str.equals("")) {
return 0;
}
if ((str.substring(0, 1).equals(ch))) {
return 1 + numberOfFirstChar0(str.substring(1));
}
return numberOfFirstChar0(str);
}
however, it does not seem to work (does not return the correct result of how many occurrences there are in the string). Is there anything wrong with the code? Any help is appreciated.
This uses 2 functions, one which is recursive. We obtain the character at the first index and the character array from the String once instead of doing it over and over and concatenating the String. We then use recursion to continue going through the indices of the character array.
Why you would do this I have no idea. A simple for-loop would achieve this in a much easier fashion.
private static int numberOfFirstChar0(String str) {
if (str.isEmpty()) {
return 0;
}
char[] characters = str.toCharArray();
char character = characters[0];
return occurrences(characters, character, 0, 0);
}
private static int occurrences(char[] characters, char character, int index, int occurrences) {
if (index >= characters.length - 1) {
return occurrences;
}
if (characters[index] == character) {
occurrences++;
}
return occurrences(characters, character, ++index, occurrences);
}
Java 8 Solution
private static long occurrencesOfFirst(String input) {
if (input.isEmpty()) {
return 0;
}
char characterAtIndexZero = input.charAt(0);
return input.chars()
.filter(character -> character == characterAtIndexZero)
.count();
}
Here is a simple example of what you are looking for.
Code
public static void main(String args[]) {
//the string we will use to count the occurence of the first character
String countMe = "abcaabbbdc";
//the counter used
int charCount=0;
for(int i = 0;i<countMe.length();i++) {
if(countMe.charAt(i)==countMe.charAt(0)) {
//add to counter
charCount++;
}
}
//print results
System.out.println("The character '"+countMe.charAt(0)+"' appears "+ charCount+ " times");
}
Output
The character 'a' appears 3 times
Question:
Write a function to find the longest common prefix string among an array of strings. If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Code:
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs==null || strs.length==0)
return "";
for(int i=0;i<strs[0].length();i++) {
char x = strs[0].charAt(i);
for(int j=0;j<strs.length;j++) {
if((strs[j].length()==i)||(strs[j].charAt(i)!=x)) {
return strs[0].substring(0,i);
}
}
}
return strs[0];
}
}
This is the second solution, but I don't understand the inner loop.
I think if the second element in strs returns a string and ends the for loop, the third element will not have a chance to be compared.
You have to check same position in all of the words and just compare it.
positions
word 0 1 2 3 4 5
=====================
w[0] F L O W E R
w[1] F L O W
w[2] F L I G H T
In Java:
class Main {
public static void main(String[] args) {
String[] words = {"dog","racecar","car"};
String prefix = commonPrefix(words);
System.out.println(prefix);
// return empty string
String[] words2 = {"dog","racecar","car"};
String prefix2 = commonPrefix(words2);
System.out.println(prefix2);
// Return "fl" (2 letters)
}
private static String commonPrefix(String[] words) {
// Common letter counter
int counter = 0;
external:
for (int i = 0; i < words[0].length(); i++) {
// Get letter from first word
char letter = words[0].charAt(i);
// Check rest of the words on that same positions
for (int j = 1; j < words.length; j++) {
// Break when word is shorter or letter is different
if (words[j].length() <= i || letter != words[j].charAt(i)) {
break external;
}
}
// Increase counter, because all of words
// has the same letter (e.g. "E") on the same position (e.g. position "5")
counter++;
}
// Return proper substring
return words[0].substring(0, counter);
}
}
Your first loop is itterating over all chars in the first string of array. Second loop is checking char at i posistion of all strings of array. If characters do not match, or length of string is the same as i it returns substring result.
I think the best way to understand is debug this example.
If the char in the second string is different than the char in the first one, then it is correct to return, since it means that the common prefix ends there. Checking the third and following strings is not necessary.
Basically it returns as soon as it finds a mismatch char.
If we first sort them then it would be very easy we have to only go and compare the first and the last element in the vector present there so,
the code would be like,This is C++ code for the implementation.
class Solution {
public:
string longestCommonPrefix(vector<string>& str) {
int n = str.size();
if(n==0) return "";
string ans = "";
sort(begin(str), end(str));
string a = str[0];
string b = str[n-1];
for(int i=0; i<a.size(); i++){
if(a[i]==b[i]){
ans = ans + a[i];
}
else{
break;
}
}
return ans;
}
};
public class Solution {
public string LongestCommonPrefix(string[] strs) {
if(strs.Length == 0)
{
return string.Empty;
}
var prefix = strs[0];
for(int i=1; i<strs.Length; i++) //always start from 1.index
{
while(!strs[i].StartsWith(prefix))
{
prefix = prefix.Substring(0, prefix.Length-1);
}
}
return prefix;
}
}
Hi biologist here with a little bit of coding background. my goal is to be able to input a string of characters and the code to be able to tell me how many times they occur and at what location in the string.
so ill be entering a string and i want the location and abundance of sq and tq within the string. with the location being the first character e.g njnsqjjfl sq would be located at postition 4.
This is what ive come up with so far (probably very wrong)
string S = "...";
int counter =0;
for(int i=0; i<s.length; i++){
if(s.charAt (i) == 'sq')}
counter++;})
string S = "...";
int counter =0;
for(int i=0; i<s.length; i++){
if(s.charAt (i) == 'tq')}
counter++;})
any input will help, thankyou
So , you can have multiple occurrences of "sq" and "tq" in your code, so you can have 2 arraylists to save these two separately(or one to save them together).
ArrayList<Integer>sqLocation = new ArrayList<>();
ArrayList<Integer>tqLocation = new ArrayList<>();
for(int i =0;i<s.length()-1;i++){
if(s.charAt(i)=='s' && s.charAt(i+1)=='q'){
sqLocation.add(i);
}
else if(s.charAt(i)=='t' && s.charAt(i+1)=='q'){
tqLocation.add(i);
}
}
System.out.println("No. of times sq occurs = "+sqLocation.size());
System.out.println("Locations ="+sqLocation);
System.out.println("No. of times tq occurs = "+tqLocation.size());
System.out.println("Locations ="+tqLocation);
This can be achieved using regex. Your use case is to count occurrences and position of those occurrences. The method match returns an integer list which is position and count is size of list
Exmaple code
public class RegexTest {
public static List<Integer> match(String text, String regex) {
List<Integer> matchedPos = new ArrayList<>();
Matcher m = Pattern.compile("(?=(" + regex + "))").matcher(text);
while(m.find()) {
matchedPos.add(m.start());
}
return matchedPos;
}
public static void main(String[] args) {
System.out.println(match("sadfsagsqltrtwrttqsqsqsqsqsqs", "sq"));
System.out.println(match("sadfsagsqltrtwrttqksdfngjfngjntqtqtqtqtqtq", "tq"));
}
}
what you want is a HashMap <String, List <Integer>>
this will hold, the String that you are looking for e.g. sq or tq, and a List of the positions that they are at.
You want to loop around using String.indexOf see https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String,%20int)
psuedocode being
String contents = "sadfsagsqltrtwrttqksdfngjfngjntqtqtqtqtqtq";
map.add (lookFor, new ArrayList ());
int index = 0;
while ((index = contents.indexOf (lookFor, index)) != -1) {
list = map.get (lookFor);
list.add (index);
}
You should use not charAt but substring to get a part of String.
int count(String s, String target) {
int counter = 0;
int tlen = target.length();
for (int i = tlen; i < s.length(); i++) {
if (s.substring(i - tlen, i).equals(target)) {
counter++;
}
}
return counter;
}
// in some method
count("...", "sq");
count("...", "tq");
I'm trying to find all permutations of a word and add that to an Arraylist and return the array list. But, I believe my recursion is right but, there is a problem with adding the results to the ArrayList.This is what I have so far. The parameters I passed were "eat" and "" and what is returned is "tea" three times
public static ArrayList<String> permutations(String word, String beginning)
{
int l = word.length();
ArrayList<String> temp = new ArrayList<String>();
if(l == 0)
temp.add(beginning + word);
else
{
char c = word.charAt(l-1);
String blah = (beginning + c);
word = word.substring(0, l-1);
for(int i = 0; i < l; i++)
{
permutations(word, blah);
temp.add(blah + word);
}
}
return temp;
}
Probably I didn't have the right idea of your approach to find an easy fix and by the time I got things working I ended up with this. I hope it isn't too much of a departure and that it's still helpful. The output is:
[tea, tae, eta, eat, ate, aet]
import java.util.ArrayList;
public class Perm {
public static void main(String[] args) {
ArrayList<String> perms = new ArrayList<String>();
permutations("tea", perms);
System.out.println(perms);
}
public static ArrayList<String> permutations(String word, ArrayList<String> perms)
{
int l = word.length();
// If the word has only a single character, there is only
// one permutation -- itself. So we add it to the list and return
if (l == 1) {
perms.add(word);
return perms;
}
// The word has more than one character.
// For each character in the word, make it the "beginning"
// and prepend it to all the permutations of the remaining
// characters found by calling this method recursively
for (int i=0; i<word.length(); ++i) {
char beginning = word.charAt(i);
// Create the remaining characters from everything before
// and everything after (but not including) the beginning char
String blah = word.substring(0,i)+word.substring(i+1);
// Get all the permutations of the remaining characters
// by calling recursively
ArrayList<String> tempArray = new ArrayList<String>();
permutations(blah, tempArray);
// Prepend the beginning character to each permutation and
// add to the list
for (String s : tempArray) {
perms.add(beginning + s);
}
}
return perms;
}
}