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
Related
Good night to everyone!
I am trying to compare 2 strings in c++, using the .compare() function. However, the result i see is not what is expected from this function. Take a look please.
#include <iostream>
#include <string>
using namespace std;
class game
{
private:
char mtx [2][2];
int i = 0, j = 0, a = 0;
std::string matrix1;
std::string xis = "xx";
public:
game();
char winner();
};
game::game()
{
for(i = 0; i<2; i++)
{
for (j = 0; j<2; j++)
{
mtx [i][j] = 'x';
}
}
char game::winner()
{
i = j = 0;
for (j=0; j<2; j++)
{
matrix1 = mtx [0][j]; //string recieve the first line of the matrix.
}
a = xis.compare(matrix1);
cout << a<<endl;
}
int main(void) {
velha game;
velha.winner;
}
When I compile the program the a value printed is neither a '0' nor any other integers. It prints #85.
Notes: I've also tried to use <string.h> and strncmp() using a char array instead of std:: string but with no success.
I was trying to create a game class and I did not put here the other methods because they are not relevant). (also, I use Linux Mint to code)
Can anyone help me please in this context?
#include <iostream>
#include <string>
int main(void) {
std::string first, second;
std::cout << "First String: ";
getline(std::cin, first);
std::cout << "Second Line: ";
getline(std::cin, second);
if (first == second)
std::cout << "Same strings.";
else
std::cout << "Different strings.";
return 0;
}
Explanation: Just taken two strings from the user and matches straightforward without using any much complexity, just used a conditional operation.
For string compare and even strcmp the value returned will be the lexicographical comparison of the two strings. The following are the values you should see:
negative if *this appears before the character sequence specified by the argument in lexicographical order
0 if *this and the character sequence specified are equivalent
positive if *this appears after the character sequence specified by the argument in lexicographical order
If you are looking to get the first column of your matrix, do a string comparison on, you would want to do something like:
for(int col = 0; col < 2; col++) {
matrix1.push_back(mtx[0][col]); // This appends that character to the end of your string
}
If you are looking to get the rows you can just do the following:
matrix1 = mtx[0];
// To ensure you have a null terminated string
// Otherwise you will have garbage.
matrix1.replace(matrix1.begin() + 2, matrix1.end(), 1, "\0");
I have ran through the test with comparing that the matrix contains "xx" and ended up receiving 0. However a much easier comparison is to us operator == to simply return a true or false value.
I have 20 digit strings ex: 12345678912345678912.
I want to turn this into an array of ints [1,2,3...2]
How would I do that?
(I kept getting errors with sstream, atoi/stoi)
Create a new array, and convert each number character to number. Just subtract '0' from the number character and you will get the number.
The number character - '0' = the ASCII value of that character - the ASCII value of '0' = the number.
std::vector<int> digits;
for (int i = 0; i < s.size(); i++)
digits.push_back(s[i] - '0');
Using ASCII is way to here.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string s;
cin>>s;
int len = s.length();
int arr[len];
for( int it=0; it<len; it++ ){
// using ascii value
arr[it] = s[it] - '0';
}
for(int it=0; it<len; it++){
cout<<arr[it]<<" ";
}
return 0;
}
// Example program
#include <iostream>
#include <string>
int main()
{
// convert char to int
std::string str = "12345678912345678912";
int digits[str.size()];
for (size_t i=0; i<str.size(); i++) {
digits[i] = str[i] - '0';
}
// print out the string
std::cout << str << std::endl;
// print out the digits
for (size_t i=0; i<str.size(); i++) {
std::cout << digits[i];
}
std::cout << std::endl;
}
You need to learn to work with C++ standard string and character strings. Then learn to use standard function to convert character to integer. Following are some useful references:
http://www.cplusplus.com/reference/string/string/c_str/
http://www.cplusplus.com/reference/cstdlib/atoi/
http://www.cplusplus.com/reference/cstring/strncpy/
Above mentioned solutions are correct. Here is another way to solve your problem.
int main()
{
string input = "123456789";
int sum = 0;
const char * icstring = input.c_str(); // input character string
for(int i = 0; i < input.size(); i++)
{
char scstring[2]; // single character string
// Copy first digit to scstring
strncpy_s(scstring, icstring, 1);
// Convert scstring to integer using C library function 'atoi'
int digit = atoi(scstring); // cout << "i = " << endl;
sum += digit;
icstring++; // process next character
}
cout << "Sum of integers : " << sum << endl;
return 0;
}
So, I am trying to read a string from cin, then loop through the string to count which characters in that string are actually letters in the English alphabet. I have wrote a program that works just fine, but I want to know if there is a more efficient way of doing this, without looping through the entire English alphabet.
#include <iostream>
#include <string>
using namespace std;
int main() {
string my_str; //will use to store user input
getline(cin, my_str); //read in user input to my_str
int countOfLetters = 0; //begine count at 0
string alphabet = "abcdefghijklmnopqrstuwxyz"; //the entire english alphabet
for(int i = 0; i < my_str.length(); i++){
for(int j = 0; j < alphabet.length(); j++){
if (tolower(my_str.at(i)) == alphabet.at(j)){ //tolower() function used to convert all characters from user inputted string to lower case
countOfLetters += 1;
}
}
}
cout << countOfLetters;
return 0;
}
EDIT: Here is my new and improved code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string my_str; //will use to store user input
getline(cin, my_str); //read in user input to my_str
int countOfLetters = 0; //begine count at 0
string alphabet = "abcdefghijklmnopqrstuwxyz"; //the entire english alphabet
for(unsigned int i = 0; i < my_str.length(); i++){
if (isalpha(my_str.at(i))){ //tolower() function used to convert all characters from user inputted string to lower case
countOfLetters += 1;
}
}
cout << countOfLetters;
return 0;
}
enter code here
Use isalpha() to see which characters are letters and exclude them.
So, you could modify your code like this:
#include <iostream>
#include <string>
using namespace std;
int main() {
string my_str;
getline(cin, my_str);
int countOfLetters = 0;
for (size_t i = 0; i < my_str.length(); i++) { // int i produced a warning
if (isalpha(my_str.at(i))) { // if current character is letter
++countOfLetters; // increase counter by one
}
}
cout << countOfLetters;
return 0;
}
You could perhaps use isalpha:
for(int i = 0; i < my_str.length(); i++)
if (isalpha(my_str.at(i))
countOfLetters++;
You can use the std::count_if() algorithm along with the iterator interface to count characters for which some predicate returns true. The predicate can use std::isalpha() to check for alphabetical characters. For example:
auto count = std::count_if(std::begin(str), std::end(str),
[&] (unsigned char c) { return std::isalpha(c); });
You could also check if the int cast is between 65-90 or 97-122
at example
(int)'a'
Should give 97
This will be the most performant method without any doubt.
Its better than using isalpha().
Check http://www.asciitable.com/ for ASCI Numbers
isalpha works well for this particular problem, but there's a more general solution if the list of characters to accept wasn't so simple. For example if you wanted to add some punctuation.
std::set<char> good_chars;
good_chars.insert('a'); good_chars.insert('A');
good_chars.insert('b'); good_chars.insert('B');
// ...
good_chars.insert('z'); good_chars.insert('Z');
good_chars.insert('_');
// the above could be simplified by looping through a string of course
for(int i = 0; i < my_str.length(); i++){
countOfLetters += good_chars.count(my_str[i]);
}
I wrote the following code to convert string of type 'aaadddbbbccc' to 'a3d3b3c3' :
#include <iostream>
#include <string.h>
using namespace std;
void stringCompression(char *str,char *newStr){
int a[256] = {0};
int newCount = 0;
for(int i = 0; i < strlen(str) ; i++){
int j = str[i];
if (a[j] == 0 && strlen(newStr) <= strlen(str)){
a[j] = 1 ;
newStr[newCount] = str[i];
newCount++;
int count = 0;
for (int n = i; n < strlen(str); n++){
if(str[i] == str[n]){
count = count + 1;
}
}
newStr[newCount] =(char) count;
newCount++ ;
} else if (strlen(newStr) > strlen(str)){
strcpy(newStr,str);
}
}
}
int main() {
char str[] = "abcdabcdabcd";
char *newStr = new char[strlen(str)+1];
stringCompression(str,newStr);
cout << newStr;
return 0;
}
My problem is at step
newStr[newCount] =(char) count;
even though it is inserted but the output is not a3b3c3d3 but a*squarebox*b*squarebox*c*squarebox*d*squarebox*. squarebox being 2*2 matrix with one value as the number that is desired. I am using eclipse IDE.
. I would really appreciate your help. How can I correct this. Am I using the correct approach?
Thanks in advance.
The problem is that
newStr[newCount] =(char) count;
converts the number "count" into the character corresponding to that number according to the ascii table (http://www.asciitable.com/), which is "end of text" for "3", that does not correspond to any number.
You should convert "count" into a string instead. See here for example:
Easiest way to convert int to string in C++
However, be aware that it might be longer than one digit, for example if count is "11", it will take two letters in string representation.
Hey you have to use http://www.cplusplus.com/reference/cstdlib/itoa/ to convert integer to char string
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I was asked this question in an interview:
Given an array with the input string, display the output as shown below
Input
INDIA
Output
INDA
****
*
I iterated through the array and stored each character as a key in std::map with value as number of occurrence. Later I iterate the map and print the asteriks and reduce the value in the map for each character.
Initially, I was asked not to use any library. I gave a solution which needed lot of iterations. For every character, iterate the complete array till the index to find previous occurrences and so on.
Is there any better way, e.g. better complexity, such as faster operation, by which this can be achieved?
Essentially what you are asking is how to implement map without using the STL code, as using some kind of data structure which replicates the basic functionality of map is pretty much the most reasonable way of solving this problem.
There are a number of ways of doing this. If your keys (here the possible characters) come from a very large set where most elements of the set don't appear (such as the full Unicode character set), you would probably want to use either a tree or a hash table. Both of these data structures are very important with lots of variations and different ways of implementing them. There is lots of information and example code about the two structures around.
As #PeterG said in a comment, if the only characters you are going to see are from a set of 256 8-bit chars (eg ASCII or similar), or some other limited collection like the upper-case alphabet you should just use an array of 256 ints and store a count for each char in that.
here is another one:
You can see it working HERE
#include <stdio.h>
int main()
{
int i,j=0,f=1;
char input[50]={'I','N','D','I','A','N','A','N'};
char letters[256]={0};
int counter[256]={0};
for(i=0;i<50;i++)
{
if(input[i])
counter[input[i]]++;
if(counter[input[i]]==1)
{
putchar(input[i]);
letters[j]=input[i];
j++;
}
}
putchar('\n');
while(f)
{
f=0;
for(i=0;i<j;i++)
if(counter[letters[i]])
{
putchar('*');
counter[letters[i]]--;
f=1;
}
else
{
putchar(' ');
}
putchar('\n');
}
return 0;
}
If the alphabet under consideration is fixed, it can be done in two passes:
Create an integer array A with the size of the alphabet, initialized with all zeros.
Create a boolean array B with size of the input, initialize with all false.
Iterate the input; increase for every character the corresponding content of A.
Iterate the input; output a character if its value it B is false and set its value in B to true. Finally, output a carriage return.
Reset B.
Iterate input as in 4., but print a star if if the character's count in A is positive, then decrease this count; print a space otherwise.
Output a carriage return; loop to 5 as long as there are any stars in the output generated.
This is interesting. You shouldnt use a stl::map because that is not a hashmap. An stl map is a binary tree. An unordered_map is actually a hash map. In this case we dont need either. We can use a simple array for char counts.
void printAstr(std::string str){
int array[256] ;// assumining it is an ascii string
memset(array, 0, sizeof(array));
int astrCount = 0;
for(int i = 0; i < str.length()-1; i++){
array[(int) str[i]]++;
if(array[(int) str[i]] > 1) astrCount++;
}
std::cout << str << std::endl;
for(int i = 0; i < str.length()-1;i++) std::cout << "* ";
std::cout << std::endl;
while(astrCount != 0){
for(int i= 0; i< str.length() - 1;i++){
if(array[(int) str[i]] > 1){
std::cout << "* ";
array[(int) str[i]]--;
astrCount--;
}else{
std::cout << " ";
}
}
std::cout << std::endl;
}
}
pretty simple just add all values to the array, then print them out the number of times you seem them.
EDIT: sorry just made some logic changes. This works now.
The following code works correctly. I am assuming that you can't use std::string and take note that this doesn't take overflowing into account since I didn't use dynamic containers. This also assumes that the characters can be represented with a char.
#include <iostream>
int main()
{
char input[100];
unsigned int input_length = 0;
char letters[100];
unsigned int num_of_letters = 0;
std::cin >> input;
while (input[input_length] != '\0')
{
input_length += 1;
}
//This array acts like a hash map.
unsigned int occurrences[256] = {0};
unsigned int max_occurrences = 1;
for (int i = 0; i < input_length; ++i)
{
if ((occurrences[static_cast<unsigned char>(input[i])] += 1) == 1)
{
std::cout<< " " << (letters[num_of_letters] = input[i]) << " ";
num_of_letters += 1;
}
if (occurrences[static_cast<unsigned char>(input[i])] > max_occurrences)
{
max_occurrences = occurrences[static_cast<unsigned char>(input[i])];
}
}
std::cout << std::endl;
for (int row = 1; row <= max_occurrences; ++row)
{
for (int i = 0; i < num_of_letters; ++i)
{
if (occurrences[static_cast<unsigned char>(letters[i])] >= row)
{
std::cout << " * ";
}
else
{
std::cout << " ";
}
}
std::cout << std::endl;
}
return 0;
}
The question is marked as c++ but It seems to me that the answers not are all quite C++'ish, but could be quite difficult to achieve a good C++ code with a weird requirement like "not to use any library". In my approach I've used some cool C++11 features like in-class initialization or nullptr, here is the live demo and below the code:
struct letter_count
{
char letter = '\0';
int count = 0;
};
int add(letter_count *begin, letter_count *end, char letter)
{
while (begin != end)
{
if (begin->letter == letter)
{
return ++begin->count;
}
else if (begin->letter == '\0')
{
std::cout << letter; // Print the first appearance of each char
++begin->letter = letter;
return ++begin->count;
}
++begin;
}
return 0;
}
int max (int a, int b)
{
return a > b ? a : b;
}
letter_count *buffer = nullptr;
auto testString = "supergalifragilisticoespialidoso";
int len = 0, index = 0, greater = 0;
while (testString[index++])
++len;
buffer = new letter_count[len];
for (index = 0; index < len; ++index)
greater = max(add(buffer, buffer + len, testString[index]), greater);
std::cout << '\n';
for (int count = 0; count < greater; ++count)
{
for (index = 0; buffer[index].letter && index < len; ++index)
std::cout << (count < buffer[index].count ? '*' : ' ');
std::cout << '\n';
}
delete [] buffer;
Since "no libraries are allowed" (except for <iostream>?) I've avoided the use of std::pair<char, int> (which could have been the letter_count struct) and we have to code many utilities (such as max and strlen); the output of the program avobe is:
supergaliftcod
**************
* ******* *
* *** *
* *
*
*
My general solution would be to traverse the word and replace repeated characters with an unused nonsense character. A simple example is below, where I used an exclamation point (!) for the nonsense character (the input could be more robust, some character that is not easily typed, disallowing the nonsense character in the answer, error checking, etc). After traversal, the final step would be removing the nonsense character. The problem is keeping track of the asterisks while retaining the original positions they imply. For that I used a temp string to save the letters and a process string to create the final output string and the asterisks.
#include <iostream>
#include <string>
using namespace std;
int
main ()
{
string input = "";
string tempstring = "";
string process = "";
string output = "";
bool test = false;
cout << "Enter your word below: " << endl;
cin >> input;
for (unsigned int i = 0; i < input.length (); i++)
{ //for the traversed letter, traverse through subsequent letters
for (unsigned int z = i + 1; z < input.length (); z++)
{
//avoid analyzing nonsense characters
if (input[i] != '!')
{
if (input[i] == input[z])
{ //matched letter; replace with nonsense character
input[z] = '!';
test = true; //for string management later
}
}
}
if (test)
{
tempstring += input[i];
input[i] = '*';
test = false; //reset bool for subsequent loops
}
}
//remove garbage symbols and save to a processing string
for (unsigned int i = 0; i < input.size (); i++)
if (input[i] != '!')
process += input[i];
//create the modified output string
unsigned int temp = 0;
for (unsigned int i = 0; i < process.size (); i++)
if (process[i] == '*')
{ //replace asterisks with letters stored in tempstring
output += tempstring[temp];
temp++;
}
else
output += process[i];
//output word with no repeated letters
cout << output << endl;
//output asterisks equal to output.length
for (unsigned int a = 0; a < output.length (); a++)
cout << "*";
cout << endl;
//output asterisks for the letter instances removed
for (unsigned int i = 0; i < process.size (); i++)
if (process[i] != '*')
process[i] = ' ';
cout << process << endl << endl;
}
Sample output I received by running the code:
Enter your word below:
INDIA
INDA
****
*
Enter your word below:
abcdefgabchijklmnop
abcdefghijklmnop
****************
***
It is possible just using simple array to keep count of values.
#include<iostream>
#include<string>
using namespace std;
int main(){
string s;
char arr[10000];
cin>>s;
int count1[256]={0},count2[256]={0};
for(int i=0;i<s.size();++i){
count1[s[i]]++;
count2[s[i]]++;
}
long max=-1;
int j=0;
for(int i=0;i<s.size();++i){
if(count1[s[i]]==count2[s[i]]){ //check if not printing duplicate
cout<<s[i];
arr[j++]=s[i];
}
if(count2[s[i]]>max)
max=count2[s[i]];
--count1[s[i]];
}
cout<<endl;
for(int i =1; i<=max;++i){
for(int k=0;k<j;++k){
if(count2[arr[k]]){
cout<<"*";
count2[arr[k]]--;
}
else
cout<<" ";
}
cout<<endl;
}
}