i want to count all possible anagram of input words i want to add counter that count all anagrams
for ex. the string farm have 28 possible anagram
i want this output
Enter String: abc
here are all the anagrams of : abc
abc
acb
bac
bca
cba
cab
the String "abc" have 6 possible anagram
"this is the code "
import java.util.Scanner;
public class Anagrams1 {
public static void main (String args[]) {
Scanner r = new Scanner(System.in);
System.out.print("Enter a string:");
String s = r.next();
char[] text = new char[s.length()];
for (int i=0; i<s.length(); i++)
text[i] = s.charAt(i);
System.out.println("Here are all the anagrams of " + s);
makeAnagram(text,0);
System.out.println("Goodbye!");
}
static void makeAnagram(char[] a, int i) {
if (i == a.length-1) {
printArray(a);
}
else {
for (int j=i; j< a.length; j++) {
char c = a[i];
a[i] = a[j];
a[j] = c;
makeAnagram(a, i+1);
c = a[i];
a[i] = a[j];
a[j] = c;
}
}
}
static void printArray(char [] a)
{
for (int i=0; i< a.length; i++)
System.out.print(a[i]);
System.out.println();
}
}
If you are counting the number of anagrams of input str, the number is factorial(str.length()) where
public static final int factorial(int base) {
return (base == 1) ? (1) : (factorial(base - 1));
}
Related
Given a list of words, a list of single letters (might be repeating), and score of every character.
Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).
It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a', 'b', 'c', ... ,'z' is given by score[0], score[1], ... , score[25] respectively
My approach is
finding score of a word
then can that word be formed or not
and finally, get the result code is given below
class Solution {
public:
// score finder func
int scoreFinder(vector<int>& score , string s){
int ans = 0;
for(int i = 0; i < s.size(); i++){
char ch = s[i];
ans += score[ch -'a'];
}
return ans;
}
// word can be formed or not
bool canFormed(string s , unordered_map<char,int>& myMap){
for(int i = 0; i < s.size(); i++){
if(myMap.count(s[i]) <= 0){
return false;
break;
}else{
myMap[s[i]]--;
}
}
return true;
}
int maxScoreWords(vector<string>& words, vector<char>& letters, vector<int>& score){
// freq Count of letters
/* unordered_map<char,int> map;
for(int i = 0; i < letters.size(); i++){
map[letters[i]]++;
}*/
int result = 0; // final score is stored in it
int idx = 0;
while(idx < words.size()){
// creating new map every time so that check for all possible words combinations
unordered_map<char,int> myMap;
for(int j = 0; j < letters.size(); j++){
myMap[letters[j]] ++; //= map[letters[j]];
}
int tempResult = 0;
for(int i = idx; i < words.size(); i++){
string temp = words[i];
if(canFormed(temp , myMap)){
tempResult += scoreFinder(score , temp);
}
}
result = max(result , tempResult);
idx++;
}
return result;
}
};
Input:
words = ["dog","cat","dad","good"],
letters = ["a","a","c","d","d","d","g","o","o"],
score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]
Output:
23
but I am getting the wrong output and I am unable to find the error in my code, my output is 33 for this testcase.
There is a minor bug in your code.
In the function canFormed you decrement the counter als in the case where it is 0 already. We could simply add an additional if-statement or rewrite the whole condition.
Please see one possible solution below:
// word can be formed or not
bool canFormed(string s, unordered_map<char, int>& myMap) {
for (int i = 0; i < s.size(); i++) {
if (myMap.count(s[i]) <= 0) {
return false;
}
else {
if (myMap[s[i]] > 0) {
myMap[s[i]]--;
}
else return false;
}
}
return true;
}
Then it should work.
Solved with backtracking in JAVA
public int maxScoreWords(String[] words, char[] letters, int[] score) {
int[] counts = new int[26];
for (char letter : letters) {
counts[letter - 'a']++;
}
return wordHelper(words, counts, score, 0);
}
static int wordHelper(String[] words, int[] counts, int[] score, int index) {
// base case
if (index > words.length - 1) {
return 0;
}
// recursive case - exclude
int excludedSum = wordHelper(words, counts, score, index + 1);
// recursive case - include
int includedSum = 0;
boolean recursionCall = true;
int wordScore = 0;
for (char c : words[index].toCharArray()) {
counts[c - 'a']--;
if (counts[c - 'a'] < 0) {
recursionCall = false;
}
wordScore += score[c - 'a'];
}
if (recursionCall) {
includedSum = wordScore + wordHelper(words, counts, score, index + 1);
}
for (char c : words[index].toCharArray()) {
counts[c - 'a']++;
}
return Math.max(excludedSum, includedSum);
}
I want to convert a big number (100,000 digits) from any base to base 10. I'm using this code:
this is reading file method
string* ReadFile(string fileName) {
ifstream inFile(fileName);
string line;
string* myArray = new string[1000000];
if (inFile.is_open()) {
int count = 0;
while (getline(inFile, line)) {
myArray[count] = line;
count++;
}
inFile.close();
}
else
{
cout << "file is not open";
}
return myArray;}
convert every character to base 10 method
int val(char c){
if (c >= '0' && c <= '9')
return (int)c - '0';
else
return (int)c - 'A' + 10; }
any base to decimal
int Base2Dec(string* arr) {
int base = stoi(arr[0]);
string str = "";
int size = 0;
while (!arr[size].empty())
++size;
for (int i = size; i > 0; i--) {
str += arr[i];
}
int len = str.length();
int power = 1;
int num = 0;
for (int i = len - 1; i >= 0; i--)
{
if (val(str[i]) >= base)
{
printf("Invalid Number");
}
num += val(str[i]) * power;
power = power * base;
}
return num;}
and main method
int main(){
string* A = ReadFile("A2.txt"); cout << Base2Dec(A);
string* B = ReadFile("B.txt"); Base2Dec(B);
cin.get();}
it works but not for 100,000 digits ?! I know int type is limited and I am not allowed to use int64 so, I want to know what the solution is?!
How to generate ordered combinations for an array of characters?
For example, given an array ['a','b','c','d'], write a program for all possible combinations ordered ascendingly by length, then ascendingly by lexicographic order - in other words:
ab ac ad bc bd cd abc abd acd bcd abcd
Try this one. Although I have written it in Console application, by changing static void Main(string[] args) into a method it works.
static void Main(string[] args)
{
Dictionary<string, int> s = new Dictionary<string, int>();
Dictionary<string, int> dict = new Dictionary<string, int>();
bool bln = false;
string[] str = new string[5] { "a", "b", "c", "d","e"};
int len = str.Length;
string lastWord = "";
// a,b,c,d - count=1, aa,ab,ac,ad,ba,bb,bc,bd - count=2 etc
int count = 1;
foreach(string sa in str)
{
dict.Add(sa,1);
}
for(int m=0;m<len;m++)
{
// Gets last word as eeeee in this example
lastWord += str[4];
}
for (int i = 0; i < len; i++)
{
foreach (KeyValuePair<string, int> kvp in dict)
{
for (int j = 0; j < str.Length; j++)
{
if (kvp.Value == count)
{
s.Add(kvp.Key + str[j],count + 1);
// If last combination has reached
if (s.Keys.Contains(lastWord))
bln = true;
}
}
}
foreach (KeyValuePair<string, int> kvp in s)
{
if (kvp.Value == count + 1)
{
dict.Add(kvp.Key,kvp.Value);
}
}
if (bln)
break;
count++;
// a,b,c,d - 4 combinations. aa,ab,ac,ad,ba,bb,bc,bd...4*4=16, then 64 etc
len = len * str.Length;
}
dict.Clear();
foreach (KeyValuePair<string, int> kvp in s)
{
string s1 = SortWord(kvp.Key);
if(!dict.Keys.Contains(s1))
dict.Add(s1, kvp.Value);
}
foreach (KeyValuePair<string, int> kvp in s)
{
// abdc will get sorted to abcd
string s1 = SortWord(kvp.Key);
// If aabc then false becz 'a' is repeated two times
bool b = IsWordsRepeat(s1);
if (dict.Keys.Contains(s1) && !b)
{
dict.Remove(SortWord(kvp.Key));
}
}
Console.ReadLine();
}
Gets a boolean status to check whether a character is repeated more than 1 time
public static bool IsWordsRepeat(string text)
{
int count = 0;
foreach(char c in text)
{
count = 0;
foreach (char c1 in text)
{
if (c == c1)
{
count++;
}
if (count == 2)
return false;
}
}
return true;
}
Get word after sorting(ie, abdc to abcd)
static string SortWord(string str)
{
char[] chars = str.ToArray();
Array.Sort(chars);
return new string(chars);
}
You will get your results in dict at last in the sorted manner.
RESULT
According to your question you had asked to order the string like
ab ac ad bc bd cd abc abd acd bcd abcd
which is not in alphabetical/lexicographic order and which forms the result as follows
And as of now you are required to order in another order. Just add the below code before Console.ReadLine() which generates your desired result
var list = dict.Keys.ToList();
list.Sort();
foreach (var key in list)
{
Console.WriteLine("{0}", key);
}
which shows the below result
import java.util.*;
import java.math.*;
public class combPowerSet {
//printing the charachters as per the number sent.
void printNumber(int number, char [] items)
{
String digitString = Integer.toString(number);
char [] digitStringArray = digitString.toCharArray();
int length = digitStringArray.length;
for ( int i=0; i<length; i++)
{
System.out.print(items[Character.getNumericValue(digitStringArray[i])-1]);
}
System.out.println();
}
//checking if the number follows the required pattern.
boolean checkCondition(int number, int itemSize)
{
boolean validNumber = true;
String digitString = Integer.toString(number);
char [] digitStringArray = digitString.toCharArray();
int length = digitStringArray.length;
for ( int i=0; i<length; i++)
{
for( int j = i+1; j < length; j++)
{
int x = Character.getNumericValue(digitStringArray[i]);
int y = Character.getNumericValue(digitStringArray[j]);
if (x > itemSize-1 || y > itemSize || x > y || x==y)
{
validNumber = false;
break;
}
}
if (validNumber == false) break;
}
return validNumber;
}
void printCombinations(char [] items)
{
double maxDigit = 0;
int itemSize = items.length;
for(int i=1; i<=itemSize; i++)
{
maxDigit = maxDigit + i*Math.pow(10,itemSize-i);
}
for(int x=12; x<=maxDigit; x++)
{
if(checkCondition(x, itemSize))
{
printNumber(x, items);
}
}
}
public static void main(String [] args)
{
char [] arr = { 'a','b', 'c','d', 'e'};
combPowerSet obj = new combPowerSet();
obj.printCombinations(arr);
}
}
I have written a small program for run length encoding.
void runLengthEncoding (string& str)
{
int k=0;
int count =1;
for (unsigned i=1, count=1; i<str.size(); ++i)
{
if ( str[i] == str[k])
{
count +=1;
}
else
{
str[++k] = count+'0';
str[++k] = str[i];
count = 1;
}
}
str[++k] = count + '0';
str.resize(k);
}
When I call this function using
string s = "wwwwaaadexxxxxx";
runLengthEncoding (s);
cout << endl << s;
It is printing - "w4a3d1e1x"
It should print - "w4a3d1e1x6"
My doubt is why it is not printing the last count?
Instead of using
str.resize(k)
i need to use
str.resize(k+1);
If you delete for count initialization, and resize correctly, you got it:
void runLengthEncoding (string& str)
{
int k=0;
int count =1;
for (unsigned i=1; i<str.size(); ++i)
{
if ( str[i] == str[k])
{
count +=1;
}
else
{
str[++k] = count+'0';
str[++k] = str[i];
count = 1;
}
}
str[++k] = count + '0';
str.resize(++k);
}
I'm trying to solve a problem that asks to find the largest palindrome in a string up to 20,000 characters. I've tried to check every sub string whether it's a palindrome, that worked, but obviously was too slow. After a little googling I found this nice algorithm
http://stevekrenzel.com/articles/longest-palnidrome. I've tried to implement it, however I can't get it to work. Also the given string contains illegal characters, so I have to convert it to only legal characters and output the longest palindrome with all characters.
Here's my attempt:
int len = original.length();
int longest = 0;
string answer;
for (int i = 0; i < len-1; i++){
int lower(0), upper(0);
if (len % 2 == 0){
lower = i;
upper = i+1;
} else {
lower = i;
upper = i;
}
while (lower >= 0 && upper <= len){
string s2 = original.substr(lower,upper-lower+1);
string s = convert(s2);
if (s[0] == s[s.length()-1]){
lower -= 1;
upper += 1;
} else {
if (s.length() > longest){
longest = s.length();
answer = s2;
}
break;
}
}
}
I can't get it to work, I've tried using this exact algorithm on paper and it worked, please help. Here's full code if you need it : http://pastebin.com/sSskr3GY
EDIT:
int longest = 0;
string answer;
string converted = convert(original);
int len = converted.length();
if (len % 2 == 0){
for (int i = 0; i < len - 1; i++){
int lower(i),upper(i+1);
while (lower >= 0 && upper <= len && converted[lower] == converted[upper]){
lower -= 1;
upper += 1;
}
string s = converted.substr(lower+1,upper-lower-1);
if (s.length() > longest){
longest = s.length();
answer = s;
}
}
} else {
for (int i = 0; i < len; i++){
int lower(i), upper(i);
while (lower >= 0 && upper <= len && converted[lower] == converted[upper]){
lower -= 1;
upper += 1;
}
string s = converted.substr(lower+1,upper-lower-1);
if (s.length() > longest){
longest = s.length();
answer = s;
}
}
}
Okay so I fixed the problems, it works perfectly fine but only if the length of converted string is odd. Please help.
I can see two major errors:
Whether you initialise your upper/lower pointers to i,i or i,i+1 depends on the parity of the palindrome's length you want to find, not the original string. So (without any further optimisations) you'll need two separate loops with i going from 0 to len (len-1), one for odd palindrome lengths and another one for even.
The algorithms should be executed on the converted string only. You have to convert the original string first for it to work.
Consider this string: abc^ba (where ^ is an illegal character), the longest palindrome excluding illegal characters is clearly abcba, but when you get to i==2, and move your lower/upper bounds out by one, they will define the bc^ substring, after conversion it becomes bc, and b != c so you concede this palindrome can't be extended.
#include <iostream>
using namespace std;
int main()
{
string s;
cin >> s;
signed int i=1;
signed int k=0;
int ml=0;
int mi=0;
bool f=0;
while(i<s.length())
{
if(s[i]!=s[i+1])
{
for(k=1;;k++)
{
if(!(s[i-k]==s[i+k] && (i-k)>=0 && (i+k)<s.length()))
{
break;
}
else if(ml < k)
{
ml=k;
mi=i;
f=1;
}
}
}
i++;
}
i=0;
while(i<s.length())
{
if(s[i]==s[i+1])
{
for(k=1;;k++)
{
if(!(s[i-k]==s[k+1+i] && (i-k)>=0 && (k+i)<s.length()))
{
break;
}
else if(ml < k)
{
ml=k;
mi=i;
}
}
}
i++;
}
if(ml < 1)
{
cout << "No Planidrom found";
return 0;
}
if(f==0)
{
cout << s.substr(mi-ml,2*ml+2);
}
else
{
cout << s.substr(mi-ml,2*ml+1);
}
return 0;
}
#biziclop : As you said.. i used 2 while loops. one for even and one for old palindrom string. finally i was able to fix it. thanks for your suggestion.
public void LongestPalindrome()
{
string str = "abbagdghhkjkjbbbbabaabbbbbba";
StringBuilder str1=new StringBuilder();
StringBuilder str2= new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
str1.Append((str[i]));
for (int j = i + 1; j < str.Length; j++)
{
str1.Append((str[j]));
if (Checkpalindrome(str1))
{
str2.Append(str1);
str2.Append(" ");
}
}
str1.Clear();
}
var Palstr = str2.ToString().Split(' ');
var Longestpal = Palstr.Where(a => a.Length >= (Palstr.Max(y => y.Length)));
foreach (var s in Longestpal)
{
Console.WriteLine(s);
}
}
public bool Checkpalindrome(StringBuilder str)
{
string str1 = str.ToString();
StringBuilder str2=new StringBuilder();
var revstr = str1.Reverse();
foreach (var c in revstr )
{
str2.Append(c);
}
if (str1.Equals(str2.ToString()))
{
return true;
}
return false;
}