As mentioned in the title, how do I iterate through every letter in a vector of strings?
If someone types in some words like
hello
random
stack
and then enters a letter like e
I want to print out which words contains the letter "e" which is "hello". So how do I check every character in the vector for that character and then print the word(s) out?
for (int i {}; i < gift_bag.gifts.size(); ++i)
{
if (gift_bag.gifts[i] == letter)
{
cout << gift_bag.gifts[i] << endl;
}
}
This is what I've done but it is wrong because it check if a string is equal a character. I want to iterate through the letters in each word.
gift_bag is defined as Gift_Bag_Type which is a struct containing a vector<string> named gifts. And letter is char
The ranged for loop and find function in std::string will help you.
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> vec = { "hello", "random", "stack" };
constexpr char letter = 'e';
for (const auto &str : vec)
if (str.find(letter) != std::string::npos)
std::cout << str << '\n'; // hello
}
You'll need two loops, one to iterate through the vector, then a nested loop to iterate through the string.
const size_t vector_size = gift_bag.size();
for (unsigned int i = 0u; i < vector_size; ++i)
{
std::string& s(gift_bag[i]);
const size_t string_size = s.length();
for (unsigned int j = 0U; j < string_size; ++j)
{
Process_Character(s[j]);
}
}
There may be other methods, but you will need to consider that the strings may not be all the same length.
Related
I've written a code that removes all vowels from a string in c++ but for some reason it doesn't remove the vowel 'o' for one particular input which is: zjuotps.
Here's the code:
#include<iostream>
#include<string>
using namespace std;
int main(){
string s;
cin >> s;
string a = "aeiouyAEIOUY";
for (int i = 0; i < s.length(); i++){
for(int j = 0; j < a.length(); j++){
if(s[i] == a[j]){
s.erase(s.begin() + i);
}
}
}
cout << s;
return 0;
}
When I input: zjuotps
The Output I get is: zjotps
This is a cleaner approach using the C++ standard library:
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::string input = "zjuotps";
std::string vowels = "aeiouyAEIOUY";
auto predicate = [&vowels](char c) { return vowels.find(c) != std::string::npos; };
auto iterator = std::remove_if(input.begin(), input.end(), predicate);
input.erase(iterator, input.end());
cout << input << endl;
}
Edit:
as #RemyLebeau pointed out, std::erase_if can be used which is introduced in c++20 and the answer becomes one line of code:
std::erase_if(input, [&vowels](char c) { return vowels.find(c) != std::string::npos; });
You can develop a solution by adding the matching characters to the new string object. The eliminate() method writes the character to the result object if the characters in the input object doesn't match the characters in the remove object.
#include <iostream>
/**
* #brief This method scans the characters in the "input" object and writes
* the characters not in the "remove" object to the "result" object.
* #param input This object contains the characters to be scanned.
* #param remove This object contains characters that will not match.
* #param result Non-match result data is writed to this object.
*/
void eliminate(std::string input, std::string remove, std::string &result);
int main()
{
std::string input = "zjuotpsUK", remove = "aeiouyAEIOUY", result;
eliminate(input, remove, result);
std::cout << result << std::endl;
return 0;
}
void eliminate(std::string input, std::string remove, std::string &result)
{
for (size_t i = 0, j = 0; i < input.length(); i++)
{
for(j = 0; j < remove.length(); j++)
if(input[i] == remove[j])
break;
if(j == remove.length())
result += input[i];
}
}
In your code here, I replaced s with input_str, and a with vowels, for readability:
for (int i = 0; i < input_str.length(); i++){
for(int j = 0; j < vowels.length(); j++){
if(input_str[i] == vowels[j]){
input_str.erase(input_str.begin() + i);
}
}
}
The problem with your current code above is that each time you erase a char in the input string, you should break out of the vowels j loop and start over again in the input string at the same i location, checking all vowels in the j loop again. This is because erasing a char left-shifts all chars which are located to the right, meaning that the same i location would now contain a new char to check since it just left-shifted into that position from one position to the right. Erroneously allowing i to increment means you skip that new char to check in that same i position, thereby leaving the 2nd vowel in the string if 2 vowels are in a row, for instance. Here is the fix to your immediate code from the question:
int i = 0;
while (i < s.length()){
bool char_is_a_vowel = false;
for(int j = 0; j < a.length(); j++){
if(s[i] == a[j]){
char_is_a_vowel = true;
break; // exit j loop
}
}
if (char_is_a_vowel){
s.erase(s.begin() + i);
continue; // Do NOT increment i below! Skip that.
}
i++;
}
However, there are many other, better ways to do this. I'll present some below. I personally find this most-upvoted code difficult to read, however. It requires extra study and looking up stuff to do something so simple. So, I'll show some alternative approaches to that answer.
Approach 1 of many: copy non-vowel chars to new string:
So, here is an alternative, simple, more-readable approach where you simply scan through all chars in the input string, check to see if the char is in the vowels string, and if it is not, you copy it to an output string since it is not a vowel:
Just the algorithm:
std::string output_str;
for (const char c : input_str) {
if (vowels.find(c) == std::string::npos) {
output_str.push_back(c);
}
}
Full, runnable example:
#include <iostream> // For `std::cin`, `std::cout`, `std::endl`, etc.
#include <string>
int main()
{
std::string input_str = "zjuotps";
std::string vowels = "aeiouyAEIOUY";
std::string output_str;
for (const char c : input_str)
{
if (vowels.find(c) == std::string::npos)
{
// char `c` is NOT in the `vowels` string, so append it to the
// output string
output_str.push_back(c);
}
}
std::cout << "input_str = " << input_str << std::endl;
std::cout << "output_str = " << output_str << std::endl;
}
Output:
input_str = zjuotps
output_str = zjtps
Approach 2 of many: remove vowel chars in input string:
Alternatively, you could remove the vowel chars in-place as you originally tried to do. But, you must NOT increment the index, i, for the input string if the char is erased since erasing the vowel char left-shifs the remaining chars in the string, meaning that we need to check the same index location again the next iteration in order to read the next char. See the note in the comments below.
Just the algorithm:
size_t i = 0;
while (i < input_str.length()) {
char c = input_str[i];
if (vowels.find(c) != std::string::npos) {
input_str.erase(input_str.begin() + i);
continue;
}
i++;
}
Full, runnable example:
#include <iostream> // For `std::cin`, `std::cout`, `std::endl`, etc.
#include <string>
int main()
{
std::string input_str = "zjuotps";
std::string vowels = "aeiouyAEIOUY";
std::cout << "BEFORE: input_str = " << input_str << std::endl;
size_t i = 0;
while (i < input_str.length())
{
char c = input_str[i];
if (vowels.find(c) != std::string::npos)
{
// char `c` IS in the `vowels` string, so remove it from the
// `input_str`
input_str.erase(input_str.begin() + i);
// do NOT increment `i` here since erasing the vowel char above just
// left-shifted the remaining chars in the string, meaning that we
// need to check the *same* index location again the next
// iteration!
continue;
}
i++;
}
std::cout << "AFTER: input_str = " << input_str << std::endl;
}
Output:
BEFORE: input_str = zjuotps
AFTER: input_str = zjtps
Approach 3 of many: high-speed C-style arrays: modify input string in-place
I borrowed this approach from "Approach 1" of my previous answer here: Removing elements from array in C
If you are ever in a situation where you need high-speed, I'd bet this is probably one of the fastest approaches. It uses C-style strings (char arrays). It scans through the input string, detecting any vowels. If it sees a char that is NOT a vowel, it copies it into the far left of the input string, thereby modifying the string in-place, filtering out all vowels. When done, it null-terminates the input string in the new location. In case you need a C++ std::string type in the end, I create one from the C-string when done.
Just the algorithm:
size_t i_write = 0;
for (size_t i_read = 0; i_read < ARRAY_LEN(input_str); i_read++) {
bool char_is_a_vowel = false;
for (size_t j = 0; j < ARRAY_LEN(input_str); j++) {
if (input_str[i_read] == vowels[j]) {
char_is_a_vowel = true;
break;
}
}
if (!char_is_a_vowel) {
input_str[i_write] = input_str[i_read];
i_write++;
}
}
input_str[i_write] = '\n';
Full, runnable example:
#include <iostream> // For `std::cin`, `std::cout`, `std::endl`, etc.
#include <string>
/// Get the number of elements in an array
#define ARRAY_LEN(array) (sizeof(array)/sizeof(array[0]))
int main()
{
char input_str[] = "zjuotps";
char vowels[] = "aeiouyAEIOUY";
std::cout << "BEFORE: input_str = " << input_str << std::endl;
// Iterate over all chars in the input string
size_t i_write = 0;
for (size_t i_read = 0; i_read < ARRAY_LEN(input_str); i_read++)
{
// Iterate over all chars in the vowels string. Only retain in the input
// string (copying chars into the left side of the input string) all
// chars which are NOT vowels!
bool char_is_a_vowel = false;
for (size_t j = 0; j < ARRAY_LEN(input_str); j++)
{
if (input_str[i_read] == vowels[j])
{
char_is_a_vowel = true;
break;
}
}
if (!char_is_a_vowel)
{
input_str[i_write] = input_str[i_read];
i_write++;
}
}
// null-terminate the input string at its new end location; the number of
// chars in it (its new length) is now equal to `i_write`!
input_str[i_write] = '\n';
std::cout << "AFTER: input_str = " << input_str << std::endl;
// Just in case you need it back in this form now:
std::string str(input_str);
std::cout << " C++ str = " << str << std::endl;
}
Output:
BEFORE: input_str = zjuotps
AFTER: input_str = zjtps
C++ str = zjtps
See also:
[a similar answer of mine in C] Removing elements from array in C
I am writing a Caesar cipher decoding program that sorts the frequency of letters of a message in descending order. My issue is when I print out the results the positions of the frequencies in the array no longer match the letters I have set up. How do I fix this? I have other code that removes punctuation and capitals, all characters besides spaces and lowercase letters from the message being decoded.
I have trimmed down the code to just what is being questioned.
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
void sortArray(int*, int);
int main()
{
string fileContent = "a coded message which is several hundreds of characters long is being passed into the program";
int count[26];
// This code is skipping over spaces and other characters
for(int f = 0; f < fileContent.length(); f++)
{
if(fileContent[f] == 32)
{
continue;
}
if(fileContent[f] >= 48 && fileContent[f] <= 57)
{
continue;
}
count[(fileContent[f]-'a')%26]++;
}
// Here is where my issue begins. In sortArray, the position of the characters are being changed.
cout << "Letter frequency: Most common to least common" << endl;
sortArray(count, 26);
for(int p = 0; p < 26; p++)
{
cout << char(p + 97) << ": " << count[p] << endl;
}
return 0;
}
void sortArray(int* srcArray, int numElements)
{
for(int x = 0; x < numElements; x++)
{
int max = srcArray[x];
int maxIndex = x;
int hold;
for(int y = x + 1; y < numElements; y++)
{
if(srcArray[y] > max)
{
max = srcArray[y];
maxIndex = y;
}
}
hold = srcArray[x];
srcArray[x] = max;
srcArray[maxIndex] = hold;
hold = 0;
}
}
Please kindly let me know how I can solve this issue, I've been theorizing but I cannot seem to figure out a viable solution.
After you compute the frequency in count array.
std::array<std::pair<char, int>, 26> pairArray;
for (int i = 0; i < 26; ++i)
{
pairArray[i] = std::make_pair('a' + i, count[i]);
}
std::sort(pairArray.begin(), pairArray.end(), myCompare);
for (int i = 0; i < 26; ++i)
std::cout << pairArray[i].first << ": " << pairArray[i].second << std::endl;
For myCompare,
bool myCompare(const std::pair<char, int>& p1, const std::pair<char, int>& p2)
{
return p1.second > p2.second;
}
This should sort the array in descending order.
The problem you are facing is because you have frequencies in the array but the frequencies are not mapped to corresponding character. When the frequencies are sorted,the array is rearranged but your printing of the frequencies is not character dependent,you are printing characters from a-z and assigning frequencies as they are in sorted array.
What you can do is map the frequencies with corresponding character. One solution can be using an unordered map,char being key. An unordered map because it won't internally sort the map on character value,so u can maintain frequency ordering as well.
You can also use vector with pair as #lamandy suggested.
vector< pair <char, int> > vect;
for (int i = 0; i < 26; i++)
{
vect.push_back(make_pair(char(i + 97), count[i]));
}
sort(vect.begin(), vect.end(), sortbysecVal);
// Printing the sorted vector(after using sort())
cout << "The vector after sort operation is:\n";
for (int i = 0; i<26; i++)
{
// "first" and "second" are used to access
// 1st and 2nd element of pair respectively
cout << vect[i].first << " "
<< vect[i].second << endl;
}
sort by second value of pair
bool sortbysecVal(const pair<int, int> &a, const pair<int, int> &b)
return (a.second > b.second);
Once after you have calculated frequencies,you can use this,this will solve your purpose and you wont need your sort function.
P.S : One more thing,you must initialize your (array)count to 0,like int count[26] = {0},because initially it contains garbage if uninitialized and adding up 1 ( count[(fileContent[f]-'a')%26]++;) to a garbage will not produce result(frequency) u expect
The answer is probably a three-liner for a standard library guru, which I am not quite yet. I hate the standard library. It makes programming so easy that anyone can do it.
Here are two versions that I hacked out. This is fun.
#include <map>
#include <string_view>
#include <vector>
#include <algorithm>
using counted = std::pair<char, unsigned>;
std::vector<counted>
counted_chars(const std::string_view input) {
// Return a vector of <char, count> pairs, where char is an uppercase
// letter, and count is the number of occurrences of the letter (upper or lower).
// It is sorted from highest count to lowest.
using namespace std;
map<char, unsigned> count;
// Count them.
for(char next: input) {if (isalpha(next)) {count[toupper(next)] += 1;}}
// Sort them
vector<counted> sorted(count.size());
copy(count.cbegin(), count.cend(), sorted.begin());
sort(sorted.begin(), sorted.end(), [](counted c1, counted c2)
{ return c1.second > c2.second; });
return sorted;
}
int main() {
std::string str = "a coDed; MESSage which_is several hundreds of characters long is being passed into the program";
auto result = counted_chars(str);
return 0;
}
Another one that doesn't use std::map.
#include <map>
#include <vector>
#include <algorithm>
using counted = std::pair<char, unsigned>;
std::vector<counted> counted_chars(std::string input) {
using namespace std;
input.resize(remove_if(input.begin(), input.end(), [](char ch) { return !isalpha(ch); })-input.begin());
for(char &ch: input) { ch = toupper(ch); }
sort(input.begin(), input.end());
string present {input};
present.resize(unique(present.begin(), present.end())-present.begin());
std::vector<counted> sorted;
for (char ch:present) {sorted.push_back(make_pair(ch, count(input.begin(), input.end(), ch)));}
sort(sorted.begin(), sorted.end(), [](counted c1, counted c2) { return c1.second > c2.second; });
return sorted;
}
int main() {
std::string str = " -- I have always wished for my computer to be as easy to use as my telephone; My wish has come true because I can no longer figure out how to use my telephone.";
auto result = counted_chars(std::move(str));
return 0;
}
I would like to know if there is already an implementation in CPP to find all permutations of n characters of length k(1,2,3,4 etc) with repetitions. I hope there is but i could not find.
For example if string= (A,B,C,D) and i want find all permutations of string with repetitions of length k =2.
The output will be something like :
AA
AB
AC
AD
.
.
.
DD
total permutations of 16.
Simple recursive solution which will work for you for sure.
Let me first re-write your specification: Print all permutations with repetition of characters
Given a string of length n, print all permutation of the given string.
Repetition of characters is allowed
For a given string of size n, there will be n^k possible strings of length "length". The idea is to start from an empty output string (we call it prefix in following code). One by one add all characters to prefix. For every character added, print all possible strings with current prefix by recursively calling for "length" equals to "length"-1.
#include <string>
#include <iostream>
void print_str(const char*,std::string,const int, const int);
int main()
{
int lenght = 2;
char str[] = {'A', 'B', 'C', 'D'};
int n = sizeof str;
print_str(str, "", n, lenght); //Note: this function works on all cases and not just the case above
return 0;
}
// The main recursive method to print all possible strings of length "length"
void print_str(const char str[],std::string prefix,const int n, const int lenght)
{
if (lenght == 1)
{
for (int j = 0; j < n; j++)
std::cout << prefix + str[j] << std::endl;
}//Base case: lenght = 1, print the string "lenght" times + the remaining letter
else
{
// One by one add all characters from "str" and recursively call for "lenght" equals to "lenght"-1
for (int i = 0; i < n; i++)
// Next character of input added
print_str(str, prefix + str[i], n, lenght - 1);
// "lenght" is decreased, because we have added a new character
}
}
Here is the execution of the code above:
References:
http://www.geeksforgeeks.org/print-all-permutations-with-repetition-of-characters/
http://www.geeksforgeeks.org/print-all-combinations-of-given-length/
Update: this update is writen answring the following spec.
I need one more help!! as i am new to CPP programming. Suppose if
length = 3 how can i make it to get all permutations starting from
length = 1 to length = 3 together in an array. Means to get all the
permutations of length =1, length =2 and length = 3 together stored in
an array
#include <string>
#include <iostream>
#include <vector>
void print_str(const char*,std::string,const int, const int);
std::vector<std::string> permutations ; // the vector permutations which will hold all the permutations,
//if you want you can use it for later use or you can use the array below which is nothing than a copy of this vector.
int NumberOfPermutations = 0; // this variable holds the number of permutations
int main()
{
int lenght = 3;
char str[] = {'A', 'B', 'C', 'D'};
int n = sizeof str;
//here we loop through all the possible lenghts 1, 2 and 3
for (int k = 1; k <= lenght; k++)
{
print_str(str, "", n, k); //Note: this function works on all cases and not just the case above
}
std::string* permut_array = new std::string[NumberOfPermutations]; // the array that we will use to store the permutations in
std::copy(permutations.begin(), permutations.end(), permut_array); // here we copy the vector into the array
//if you want you can use your array to print the permutation as folow
for (int k = 0; k < NumberOfPermutations; k++)
{
std::cout << permut_array[k] << std::endl;
}
return 0;
}
// The main recursive method to print all possible strings of length "length"
void print_str(const char str[],std::string prefix,const int n, const int lenght)
{
if (lenght == 1)
{
for (int j = 0; j < n; j++)
{
// i commented this ligne so that if you want to use your array to print your permutations you will not get a screnn with permutations printed 2 times
//std::cout << prefix + str[j] << std::endl;
permutations.push_back(prefix + str[j]); // the vector that we will use to store the permutations in
}
}//Base case: lenght = 1, print the string "lenght" times + the remaining letter
else
{
// One by one add all characters from "str" and recursively call for "lenght" equals to "lenght"-1
for (int i = 0; i < n; i++)
// Next character of input added
print_str(str, prefix + str[i], n, lenght - 1);
// "lenght" is decreased, because we have added a new character
}
NumberOfPermutations = permutations.size();
}
you can use std::next_permutation() as πάντα ῥεῖ said, but since you want to define the length and the char with repetitions, you can do something easy to realize it, as:
std::string s = "aabbccdd";
std::set<std::string> string_set;
std::sort(s.begin(), s.end());
do {
string_set.insert(s.substr(0, 2));
} while(std::next_permutation(s.begin(), s.end()));
for(auto i = string_set.begin(); i != string_set.end(); ++i)
std::cout << *i << std::endl;
This just isn't a permutation, which probably explains why you can't find an answer.
What you are actually asking is how to print the numbers 0..k-1 in base n, using digits A,B,C,D. I'll rewrite your example with familiar digits 0,1,2,3 :
00
01
02
03
10
11
12
13
..
33
There's no standard C++ method for this, but now that you know what it's called there's plenty of code on the web. Or just write it yourself. Hint: the last digit of i has value i % n.
This solution works out for all standard container and also static arrays. I think this can be used also for classes and structures
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <list>
#include <iterator>
template<typename InputIt, typename T>
bool nextPermutationWithRepetition(InputIt begin, InputIt end, T from_value, T to_value) {
auto it = std::find_if_not(std::make_reverse_iterator(end),
std::make_reverse_iterator(begin),
[&to_value](auto current) { return to_value == current; });
if (it == std::make_reverse_iterator(begin))
return false;
auto bound_element_iterator = std::prev(it.base());
(*bound_element_iterator)++;
std::fill(std::next(bound_element_iterator), end, from_value);
return true;
}
int main() {
std::list<int> vec(3, 0);
do {
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
} while (nextPermutationWithRepetition(vec.begin(), vec.end(), 0, 2));
return 0;
}
#include <iostream>
using namespace std;
int main()
{
string str = "cab";
string d = "";
char s[] = {'a', 'b', 'c', 'd', 'e'};
for(int i = 0; i < sizeof(s) / sizeof(s[0]); i++){
for(int j = 0; j < str.length(); j++){
if(str[j] == s[i]){
d += s[i];
}
}
}
cout << d << endl;
return 0;
}
I wanna check if the string "cab" for example exists in array of chars like in my case, it should exist, no matter of position in the element in the array of chars.
Assuming that your sub string will not have duplicates, you could use an unordered_set. So you essentially iterate over your s[] and for each character, you will check if the set contains that particular character.
The unordered_set allows O(1) searching, so your algorithm should run in O(n) (n = size of s).
When you find a character in the set which is also within the array, you remove it and continue traversing the array. If by the time your are done traversing the array the set is empty, then you know that your array contains that substring. You can also check to see that the set is not empty each time you remove a character from it, this should reduce execution time.
Not my code:
#include <string>
#include <iostream>
#include <algorithm>
void print(std::string::size_type n, std::string const &s)
{
if (n == std::string::npos) {
std::cout << "not found\n";
} else {
std::cout << "found: " << s.substr(n) << '\n';
}
}
int main()
{
std::string str = "cab";
std::string::size_type n;
std::string const s = "This is a string";
// search from beginning of string
n = s.find("is");
print(n, s);
// search from position 5
n = s.find("is", 5);
print(n, s);
// find a single character
n = s.find('a');
print(n, s);
// find a single character
n = s.find('q');
print(n, s);
//not the best way
for(char c : s)
s.find(c); //will be npos if it doesn't exist
//better
std::includes( s.begin(), s.end(),
str.begin(), str.end() );
}
i had my midterm today. this was the first question. i could not solve this.
the exact requirement is as follows :
we have to determine if a string , lets say , "DA" is subset of another, "ABCD". the number of letters is crucial, for exmaple "DAD" is not a subset of "ABCD". because "D" is repeated twice whereas in the parent string "D" occurs once. also it can be assumed that that no. of letters of parent string is always equal to or greater than the other.
i thought a lot about this. my approach towards this was that i will compare the characters of the to-be-found substring with the parent string. if a match is found i will store its index in a third array. so in the end i will have the arrays of characters of the parent array which matched characters from the other array.this is how far i have been able to get.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char array[] = "ABCD";
char array1[] = "AB";
int size = strlen(array);
int size1 = strlen(array1);
int temp[size];
int no = 0;
for (int i = 0; i< size1; i++)
{
for (int j = 0; j< size; j++)
{
if (array1[i]==array[j])
{
for(int k = 0; k<size ; k++)
{
if (temp[k] != j)
{
temp[no] = j;
no++;
}
}
}
}
}
for (int i = 0; i<size; i++)
cout<<endl<<temp[i]<<" ";
return 0;
}
kindly help in solving this and do tel me if you have another approach to this.
also, are arrays or a string a better approach to this problem.
i am writing in c++
thanks in advance
(I recently used this as a quiz for my students but we're using Groovy and Java.)
A simple aproach: create a copy of the string ("ABCD") and strike matched letters so that they won't match again, for example after matching a "D" and "A", the copy would be "_BC_" and it would not match another "D".
You can also count the number of occurrences of each letter in each string and make sure the count of each letter in the second string is less than or equal to the count of each letter in the first string. This might be better in the case where you want to compare multiple potential substrings to a single collection of letters (e.g. comparing all the words in the dictionary to the current letters in Boggle).
This code will do that. It has the primary limitation that it only works with strings containing the 26 capital letters in the English alphabet. But it gets the idea across.
#include <iostream>
#include <cstring>
using namespace std;
void stringToArray(char *theString, int *countArray) {
int stringLength = strlen(theString);
for (int i=0; i<26; i++) {
countArray[i] = 0;
}
for (int i=0; i<stringLength; i++) {
countArray[theString[i] - 'A']++;
}
}
bool arrayIsSubset(int *superCount, int *subCount) {
//returns true if subCount is a subset of superCount
bool isSubset = true;
for (int i=0; i<26 && isSubset; i++) {
isSubset = subCount[i] <= superCount[i];
}
return isSubset;
}
int main()
{
char array[] = "ABCD";
char array1[] = "AB";
char array2[] = "ABB";
int letterCount[26], letterCount1[26], letterCount2[26];
stringToArray(array, letterCount);
stringToArray(array1, letterCount1);
stringToArray(array2, letterCount2);
cout << "array1 is " << (arrayIsSubset(letterCount, letterCount1) ? "" : "not ") << "a subset" << endl;
cout << "array2 is " << (arrayIsSubset(letterCount, letterCount2) ? "" : "not ") << "a subset" << endl;
}
produces:
array1 is a subset
array2 is not a subset