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
Related
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
getline(cin , s) ; #input of string from user
int counter = 0;
int max_word = -1;
int len = s.length(); #length of string
string max = " ";
string counter_word = " ";
for (int i = 0; i < len; i++)
{
if(s[i] != ' ')
{
counter++;
}
if(s[i] == ' ' || i == len - 1)
{
if(counter > max_word)
{
max_word = counter;
//handling end of string.
if(i == len - 1)
max = s.substr(i + 1 - max_word, max_word); #sub string command that prints the longest word
else
max = s.substr(i - max_word, max_word);
}
counter = 0;
}
}
cout << max_word << " " << max << endl; #output
return 0;
}
The current output is '4 This' on entering the string "This is cool".
How do I get it to print '4 This; Cool' ?
On running it in Linux through the terminal, it gives me the error
" terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr Aborted (core dumped) "
If I have understood you correctly then you mean the following
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string s;
std::getline( std::cin, s );
std::string::size_type max_size;
std::string max_word;
std::string word;
std::istringstream is( s );
max_size = 0;
while ( is >> word )
{
if ( max_size < word.size() )
{
max_size = word.size();
max_word = word;
}
else if ( max_size == word.size() )
{
max_word += "; ";
max_word += word;
}
}
std::cout << max_size << ' ' << max_word << std::endl;
}
If to enter string
This is cool
then the output will be
4 This; cool
The basic idea here is to add each character to a temporary (initially empty) string until a space is encountered. At each instance of a space, the length of the temporary string is compared to the length of the "maxword" string, which is updated if it is found to be longer. The temporary string is emptied (reset to null using '\0') before proceeding to the next character in the input string.
#include <iostream>
#include <string>
using namespace std;
string LongestWord(string str) {
string tempstring;
string maxword;
int len = str.length();
for (int i = 0; i<=len; i++) {
if (tempstring.length()>maxword.length())
{
maxword=tempstring;
}
if (str[i]!=' ')
{
tempstring=tempstring+str[i];
}
else
{
tempstring='\0';
}
}
return maxword;
}
int main() {
cout << LongestWord(gets(stdin));
return 0;
}
#include <iostream>
using namespace std;
string longestWordInSentence(string str) {
// algorithm to count the number of words in the above string literal/ sentence
int words = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == ' ') {
words++;
}
}
// incrementing the words variable by one as the above algorithm does not take into account the last word, so we are incrementing
// it here manually just for the sake of cracking this problem
words += 1; // words = 5
// words would be the size of the array during initialization since this array appends only the words of the above string
// and not the spaces. So the size of the array would be equal to the number of words in the above sentence
string strWords[words];
// this algorithm appends individual words in the array strWords
short counter = 0;
for (short i = 0; i < str.length(); i++) {
strWords[counter] += str[i];
// incrementing the counter variable as the iterating variable i loops over a space character just so it does not count
// the space as well and appends it in the array
if (str[i] == ' ') {
counter++;
}
}
// algorithm to find the longest word in the strWords array
int sizeArray = sizeof(strWords) / sizeof(strWords[0]); // length of the strWords array
int longest = strWords[0].length(); // intializing a variable and setting it to the length of the first word in the strWords array
string longestWord = ""; // this will store the longest word in the above string
for (int i = 0; i < sizeArray; i++) { // looping over the strWords array
if (strWords[i].length() > longest) {
longest = strWords[i].length();
longestWord = strWords[i]; // updating the value of the longestWord variable with every loop iteration if the length of the proceeding word is greater than the length of the preceeding word
}
}
return longestWord; // return the longest word
}
int main() {
string x = "I love solving algorithms";
cout << longestWordInSentence(x);
return 0;
}
I have explained every line of the code in great detail. Please refer to the comments in front of every line of code. Here is a generalized approach:
Count the number of words in the given sentence
Initialize a string array and set the size of the array equal to the number of words in the sentence
Append the words of the given sentence to the array
Loop through the array and apply the algorithm of finding the longest word in the string. It is similar to finding the longest integer in an array of integers.
Return the longest word.
My original solution contained a bug: If you were to input 2 words of length n and 1 word of length n + k, then it would output those three words.
You should make a separate if condition to check whether the word length is the same as before, if yes, then you can append "; " and the other word.
This is what I would do:
Change if(counter > max_word) to if(counter >= max_word) so words of the same length are also taken into account.
Make the max string by default (so "" instead of " "). (See next point)
Add an if condition in the if(counter >= max_word)second if condition to see if the max string is not empty, and if it's not empty append "; "
Changing max = to max += so that it appends the words (in the second condition)
Wouldn't it be easier for you to split the whole line into a vector of string ?
Then you could ask the length of each element of the string and then print them. Because right now you still have all the words in a single string making each individual word hard to analyse.
It would also be hard, as you requested, to print all the words with the same length if you use a single string.
EDIT :
Start by looping through your whole input
Keep the greater length of word between the current one and the previously saved
Make a substring for each word and push_back it into a vector
Print the length of the bigger word
Loop through the vector and print each word of that size.
Look the following website for all references about vectors. dont forget to #include
www.cplusplus.com/reference/vector/vector/
#include <iostream>
#include <vector>
#include <string>
void LongestWord(std::string &str){
std::string workingWord = "";
std::string maxWord = "";
for (int i = 0; i < str.size(); i++){
if(str[i] != ' ')
workingWord += str[i];
else
workingWord = "";
if (workingWord.size() > maxWord.size())
maxWord = workingWord;
}
std::cout << maxWord;
}
int main(){
std::string str;
std::cout << "Enter a string:";
getline(std::cin, str);
LongestWord(str);
std::cout << std::endl;
return 0;
}
Source: http://www.cplusplus.com/forum/beginner/31169/
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s,a;
char ch;
int len,mlen=0;
getline(cin,s);
char* token=strtok(&s[0]," ");
string r;
while(token!=NULL)
{
r=token;
len=r.size();
if(mlen<len)
{
mlen=len;
a=token;
}
token = strtok(NULL, " ");
}
cout<<a;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
string str;
getline(cin,str);
cin.ignore();
int len =str.length();`
int current_len=0,max_len=0;
int initial=0,start=0;
int i=0;
while(1)
{
if(i==len+2)
{break;}
if(str[i]==' '|| i==len+1)
{
if(current_len>max_len)
{
initial=start;
max_len=current_len;
}
current_len=0;
start=i+1;
}
else
{
current_len++;
}
i++;
}
for (int i = 0; i < max_len; i++)
{
cout<<str[i+initial];
}
cout<<endl<<max_len<<endl;
return 0 ;
}
I have a working function that generates all possible “words” of a specific length, i.e.
AAAAA
BAAAA
CAAAA
...
ZZZZX
ZZZZY
ZZZZZ
I want to generalize this function to work for arbitrary lengths.
In the compilable C++ code below
iterative_generation() is the working function and
recursive_generation() is the WIP replacement.
Keep in mind that the output of the two functions not only differs slightly, but is also mirrored (which doesn’t really make a difference for my implementation).
#include <iostream>
using namespace std;
const int alfLen = 26; // alphabet length
const int strLen = 5; // string length
char word[strLen]; // the word that we generate using either of the
// functions
void iterative_generation() { // all loops in this function are
for (int f=0; f<alfLen; f++) { // essentially the same
word[0] = f+'A';
for (int g=0; g<alfLen; g++) {
word[1] = g+'A';
for (int h=0; h<alfLen; h++) {
word[2] = h+'A';
for (int i=0; i<alfLen; i++) {
word[3] = i+'A';
for (int j=0; j<alfLen; j++) {
word[4] = j+'A';
cout << word << endl;
}
}
}
}
}
}
void recursive_generation(int a) {
for (int i=0; i<alfLen; i++) { // the i variable should be accessible
if (0 < a) { // in every recursion of the function
recursive_generation(a-1); // will run for a == 0
}
word[a] = i+'A';
cout << word << endl;
}
}
int main() {
for (int i=0; i<strLen; i++) {
word[i] = 'A';
}
// uncomment the function you want to run
//recursive_generation(strLen-1); // this produces duplicate words
//iterative_generation(); // this yields is the desired result
}
I think the problem might be that I use the same i variable in all the recursions. In the iterative function every for loop has its own variable.
What the exact consequences of this are, I can’t say, but the recursive function sometimes produces duplicate words (e.g. ZAAAA shows up twice in a row, and **AAA gets generated twice).
Can you help me change the recursive function so that its result is the same as that of the iterative function?
EDIT
I realised I only had to print the results of the innermost function. Here’s what I changed it to:
#include <iostream>
using namespace std;
const int alfLen = 26;
const int strLen = 5;
char word[strLen];
void recursive_generation(int a) {
for (int i=0; i<alfLen; i++) {
word[a] = i+'A';
if (0 < a) {
recursive_generation(a-1);
}
if (a == 0) {
cout << word << endl;
}
}
}
int main() {
for (int i=0; i<strLen; i++) {
word[i] = 'A';
}
recursive_generation(strLen-1);
}
It turns out you don't need recursion after all to generalize your algorithm to words of arbitrary length.
All you need to do is "count" through the possible words. Given an arbitrary word, how would you go to the next word?
Remember how counting works for natural numbers. If you want to go from 123999 to its successor 124000, you replace the trailing nines with zeros and then increment the next digit:
123999
|
123990
|
123900
|
123000
|
124000
Note how we treated a number as a string of digits from 0 to 9. We can use exactly the same idea for strings over other alphabets, for example the alphabet of characters from A to Z:
ABCZZZ
|
ABCZZA
|
ABCZAA
|
ABCAAA
|
ABDAAA
All we did was replace the trailing Zs with As and then increment the next character. Nothing magic.
I suggest you now go implement this idea yourself in C++. For comparison, here is my solution:
#include <iostream>
#include <string>
void generate_words(char first, char last, int n)
{
std::string word(n, first);
while (true)
{
std::cout << word << '\n';
std::string::reverse_iterator it = word.rbegin();
while (*it == last)
{
*it = first;
++it;
if (it == word.rend()) return;
}
++*it;
}
}
int main()
{
generate_words('A', 'Z', 5);
}
If you want to count from left to right instead (as your example seems to suggest), simply replace reverse_iterator with iterator, rbegin with begin and rend with end.
You recursive solution have 2 errors:
If you need to print in alphabetic order,'a' need to go from 0 up, not the other way around
You only need to print at the last level, otherwise you have duplicates
void recursive_generation(int a) {
for (int i=0; i<alfLen; i++)
{ // the i variable should be accessible
word[a] = i+'A';
if (a<strLen-1)
// in every recursion of the function
recursive_generation(a+1); // will run for a == 0
else
cout << word << '\n';
}
}
As I am inspired from #fredoverflow 's answer, I created the following code which can do the same thing at a higher speed relatively.
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cmath>
void printAllPossibleWordsOfLength(char firstChar, char lastChar, int length) {
char *word = new char[length];
memset(word, firstChar, length);
char *lastWord = new char[length];
memset(lastWord, lastChar, length);
int count = 0;
std::cout << word << " -> " << lastWord << std::endl;
while(true) {
std::cout << word << std::endl;
count += 1;
if(memcmp(word, lastWord, length) == 0) {
break;
}
if(word[length - 1] != lastChar) {
word[length - 1] += 1;
} else {
for(int i=1; i<length; i++) {
int index = length - i - 1;
if(word[index] != lastChar) {
word[index] += 1;
memset(word+index+1, firstChar, length - index - 1);
break;
}
}
}
}
std::cout << "count: " << count << std::endl;
delete[] word;
delete[] lastWord;
}
int main(int argc, char* argv[]) {
int length;
if(argc > 1) {
length = std::atoi(argv[1]);
if(length == 0) {
std::cout << "Please enter a valid length (i.e., greater than zero)" << std::endl;
return 1;
}
} else {
std::cout << "Usage: go <length>" << std::endl;
return 1;
}
clock_t t = clock();
printAllPossibleWordsOfLength('A', 'Z', length);
t = clock() - t;
std:: cout << "Duration: " << t << " clicks (" << ((float)t)/CLOCKS_PER_SEC << " seconds)" << std::endl;
return 0;
}
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;
}
}
#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() );
}
How to solve this? https://code.google.com/codejam/contest/351101/dashboard#s=p1?
The code I ended up with is below, but it can only reverse strings up to one space because it was code keeping the literal logic in mind, Reverse the whole string, reverse the words, and done. The spaces are slightly messed up and when I tried a loop to detect number of spaces and act accordingly it failed. Please help! Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
char revwrd[100];
char revstr[100];
string str;
getline(cin, str);
cout<<str;
int sps[10];
int len,y=0;
len = str.length();
cout<<"\n"<<"The Length of the string is:"<<len;
for(int x=len-1;x>-1;x--)
{
revstr[x] = str[y];
y++;
}
cout<<"\n"<<"The inverse of the string is:"<<"\n";
for(int z = 0;z<len;z++)
{
cout<<revstr[z];
}
cout<<"\n";
int no=0;
int spaces=0;
for(int a=0;a<len;a++)
{
if(revstr[a]== ' ')
{
sps[no]=a;
no++;
spaces++;
}
}
int rinc=0;
int spinc;
cout<<"\n";
spinc=sps[0];
int spinc2 = sps[0]+1;
int lend;
for(rinc=0;rinc<sps[0]+1;rinc++)
{
revwrd[rinc] = revstr[spinc];
spinc--;
}
for(lend=len;lend>sps[0];lend--)
{
revwrd[spinc2] = revstr[lend];
spinc2++;
}
cout<<"Spaces in the string:"<<spaces<<"\n";
cout<<"The words inversed are:"<<"\n";
for(int inc=1;inc<len+1;inc++)
{
cout<<revwrd[inc];
}
return 0;
}
The conditions of the challenge are that there is only a single space between words, and that spaces don't appear at the beginning or the end of the line, so for this particular exercise you don't have to worry about preserving spacing; as long as you write the output with a single space between each word, you're good.
With that in mind, you can read each word using regular formatted input:
std::string word;
...
while ( stream >> word )
// do something with word
You don't have to worry about buffer size, you don't have to worry about detecting spaces, etc. You do have to worry about detecting the newline character, but that's easily done using the peek method:
while ( stream >> word )
{
// do something with word;
if ( stream.peek() == '\n' )
break;
}
The above loop will read individual words from the input stream stream until it sees a newline character (there's probably a better way to do that, but it works).
Now, in order to reverse each line of input, you obviously need to store the strings somewhere as you read them. The easiest thing to do is store them to a vector:
std::vector< std::string > strings;
...
while ( stream >> word )
{
strings.push_back( word );
if ( stream.peek() == '\n' )
break;
}
So now you have a vector containing all the strings in the line, you just have to print them out in reverse order. You can use a reverse iterator to walk through the vector:
std::vector< std::string >::reverse_iterator it;
for ( it = strings.rbegin(); it != strings.rend(); ++it )
{
std::cout << *it << " ";
}
std::cout << std::endl;
The rbegin() method returns an iterator that points to the last element in the vector; the rend() method returns an iterator that points to an element before the first element of the vector; ++it advances the iterator to point to the next item in the vector, going back to front; and *it gives the string that the iterator points to. You can get a little more esoteric and use the copy template function:
std::copy( strings.rbegin(),
strings.rend(),
std::ostream_iterator<std::string>( std::cout, " " )
);
That single method call replaces the loop above. It creates a new ostream_iterator that will write strings to cout, separated by a single space character.
For the conditions of this particular exercise, this is more than adequate. If you were required to preserve spacing, or to account for punctuation or capitalization, then you'd have to do something a bit lower-level.
Just few loops and if's:
// Reverse Words
#include <iostream>
#include <string>
using namespace std;
int main() {
int tc; cin >> tc; cin.get();
for(int t = 0; t < tc; t++) {
string s, k; getline(cin, s);
for(int i = (s.length()- 1); i >= 0; i--) {
if(s[i] == ' ' || (i == 0)) {
if(i == 0) k += ' ';
for(int j = i; j < s.length(); j++) {
k += s[j];
if(s[j+1] == ' ' ) break;
}
}
}
cout << "Case #" << t + 1 << " " << k << endl;
}
return 0;
}
This might handle multi spaces:
std::string ReverseSentence(std::string in)
{
std::vector<string> words;
std::string temp = "";
bool isSpace = false;
for(int i=0; in.size(); i++)
{
if(in[i]!=' ')
{
if(isSpace)
{
words.push_back(temp);
temp = "";
isSpace = false;
}
temp+=in[i];
}
else
{
if(!isSpace)
{
words.push_back(temp);
temp = "";
isSpace = true;
}
temp += " ";
}
}
std::reverse(words.begin(),words.end());
std::string out = "";
for(int i=0; i<words.size(); i++)
{
out+=words[i];
}
return out;
}
you can follow this method :
step 1 : just check for spaces in input array store their index number in an integer array.
step 2 : now iterate through this integer array from end
step a : make a string by copying characters from this index to previous index .
note : since for first element there is no previous element in that case you will copy from this index to end of the input string .
step b : step a will give you a word from end of input string now add these word with a space to make your output string .
I hope this will help you .
This problem is really made for recursion:
void reverse()
{
string str;
cin >> str;
if (cin.peek() != '\n' || cin.eof()) {
str = " " + str;
reverse();
}
cout << str;
}
int main(int argc, const char * argv[])
{
int count = 0;
cin >> count;
for (int i = 0; i < count; i++) {
cout << "Case #" << (i + 1) << ": ";
reverse();
cout << endl;
}
return 0;
}
So I read word by word and add one space in front of the word until end of line or file is reached. Once end of line is reached the recursion unwraps and prints the read strings in reversed order.
I went for the brute force, and I badly wanted to use pointers!
get the sentence
detect every word and put them in a container.
read backwards the container.
This is it:
#include <iostream>
#include <string>
#include <vector>
int main()
{
char *s1 = new char[100];
std::cin.getline(s1, 100);
std::vector<std::string> container;
char* temp = new char[100];
char *p1, *p0;
p1 =p0 = s1;
int i;
do{
if (*p1==' ' || *p1=='\0'){
//std::cout<<p1-p0<<' ';
for(i=0;i<p1-p0;++i) temp[i]=p0[i]; temp[i]='\0';
p0 = p1+1;
container.push_back(temp);
std::cout<<temp;
}
p1++;
}while(*(p1-1)!='\0');
std::cout<<std::endl;
for(int i=container.size()-1;i>=0;i--) std::cout<<container[i]<<' ';
return 0;
}