I am trying to get the numbers bigger than 4 after I loop in every other number, but the problem is that it keeps giving me bigger than 4 even tho the number isn't bigger than 4. thank you!
#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool isvalidcc(const string& s)
{
vector<char> v (s.begin(), s.end());
for(auto i=0 ; i<v.size();i+=2)
{
if (v.at(i)>'4')
{
cout<<v.at(i)<<"bigger than 4"<<endl;
}
else
{
cout<<v.at(i)<<"smaller than 4"<<endl;
}
}
return false;
}
int main()
{
vector<string> cardnumbers = {
"371449635398431"
};
int i;
vector<string>::iterator itr;
for (i = 1, itr = cardnumbers.begin(); itr != cardnumbers.end(); ++itr, i++) {
// cout << i << " "
// << *itr
((isvalidcc(*itr)));
}
return 0;
}
I figured it out
Because v.at(i) is a char instead of an int it converts it into ascii code.
this means u have to convert the char in to an int the right way.
if (v.at(i) - '0' >4)
the - '0' will convert it to an int the right way otherwise it will return the wrong values, u can check this by making a new int variable and cout <<
int n = v.at(i);
cout << n;
Related
I am trying to do is display all the suffixes of a word as such:
word: house
print:
h
ho
hou
hous
house
What I did is:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char cuvant[100];
int i,k;
cin>>cuvant;
for(i=0;i<strlen(cuvant);i++)
{
for(k=0;k<i;k++)
{
if(k==0)
{
cout<<cuvant[k]<<endl;
}else
{
for(k=1;k<=i;k++){
if(k==i) cout<<endl;
cout<<cuvant[k];
}
}
}
}
}
What am I doing wrong?
You're over-complicating it. Here's a simpler way:
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string s;
std::cin >> s;
for (std::string::size_type i = 0, size = s.size(); i != size; ++i)
std::cout << std::string_view{s.c_str(), i + 1} << '\n';
}
If you don't have access to a C++17 compiler, you can use this one:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
int main() {
std::string s;
std::cin >> s;
for (auto const& ch : s) {
std::copy(s.c_str(), (&ch + 1),
std::ostream_iterator<decltype(ch)>(std::cout));
std::cout << '\n';
}
}
Even so, I think it would be better for your learning progress to use a debugger to finger out the problem yourself. Here the problems with your code:
For the i=0 (the first iteration of your outer loop) the for(k=0;k<i;k++) will not be executed at all, as k<0 evaluates to false.
And having a running variable (k) that you change in two for loops that are nested, is most of the time also an indication that something is wrong.
So what you want to do: You want to create each possible prefix, so you want to create n strings with the length of 1 to n. So your first idea with the outer loop is correct. But you overcomplicate the inner part.
For the inner part, you want to print all chars from the index 0 up to i.
int main() {
char cuvant[100];
std::cin >> cuvant;
// loop over the length of the string
for (int i = 0, size = strlen(cuvant); i < size; i++) {
// print all chars from 0 upto to i (k<=0)
for (int k = 0; k <= i; k++) {
std::cout << cuvant[k];
}
// print a new line after that
std::cout << std::endl;
}
}
But instead of reinventing the wheel I would use the functions the std provides:
int main() {
std::string s;
std::cin >> s;
for (std::size_t i = 0, size = s.size(); i < size; i++) {
std::cout << s.substr(0, i + 1) << std::endl;
}
}
For this very simple string suffix task you can just use:
void main()
{
std::string s = "house";
std::string s2;
for(char c : s)
{
s2 += c;
cout << s2 << endl;
}
}
For more complicated problems you may be interested to read about Suffix Tree
Your code is wrong, the following code can fulfill your requirements
#include <iostream>
using namespace std;
int main()
{
char cuvant[100];
int i,k;
cin>>cuvant;
for(i=0;i<strlen(cuvant);i++)
{
for (k = 0; k <= i; ++k)
{
cout<<cuvant[k];
}
cout<<endl;
}
}
Hi guys I'm trying to write a code where when i type a binary string I need to mind the most consecutive numbers of occurrence 1 has occurred. For example, if i type 00111001, it should be 3, 1100111011111, it should be 5 etc. This is my code so far.
int main () {
string s1;
cin >> s1;
int l1=s1.size()-1; // length-1 hence the for loop array doesnt go out of bounds
int max=0; // this tells us the max number of occurrence
int count=0;
for (int i=0;i<l1;i++) {
if (s1[i]=='1' && s1[i+1]=='1') { // if s[0] and s[1] are both 1, it adds 1
count++;}
if (count>0 && count>max)
{max=count; // storing the count value in max.
}
if (s1[i]=='0' || s1[i+1]=='0'){ //resetting count if it encounters 0
count=0;
}
}
max=max+1;
cout << max << '\n' << endl;
The issue is if I write 1111001 it runs (I get 4), but when i type 1100111001 I get 2. Don't get why there's ambiguity. Please let me know what I need to do
Thanks
I'd only increment the count in case of 1, and zero it when 0 is reached.
whenever count is bigger than max, assign count to max and that's it.
btw, I get 3 for the input 1100111001 with your program.
#include <iostream>
using namespace std;
int main() {
string s1;
cin >> s1;
int l1 = s1.size();
int max = 0;
int count = 0;
for (int i = 0; i < l1; i++)
{
if (s1[i] == '1')
{
count++;
}
else
{
count = 0;
}
if (count > max)
{
max = count;
}
}
cout << max << '\n' << endl;
}
Let's solve this using find, given string s1 which contains your input string you can just do:
auto max = 0;
for(auto start = find(cbegin(s1), cend(s1), '1'); start != cend(s1); start = find(start, cend(s1), '1')) {
const auto finish = find(start, cend(s1), '0');
const auto count = distance(start, finish);
if(count > max) {
max = count;
}
start = finish;
}
Live Example
I want to offer you such an option for calculating through tokens and sorting:
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
string s1;
cin>>s1;
istringstream s(s1);
vector<string> result;
while (std::getline(s,s1,'0')) {
result.push_back(s1);
}
sort(result.begin(),result.end(),[](const string &a, const string &b){ return a.length()>b.length();});
cout << result.at(0).length() << endl;
return 0;
}
I know that you probably gona again vote me down, I really don't understand this but im really stuck at something and cant figure it out , there is no such information anywhere in the web , neither in my book for the course, so I have this assignment where I need make 2 sums of containers where the difference between 2 sums is the lowest , so the program is done is working perfectly calculated everything however , in my assignment:
The user enter on one row unkwonw length numbers so after that I do all kind of sums between them and find the one with lowest difference between.
Ok but the way I wrote the code I use one while(true) so that to work with infinity testcases(as from assignment) and in this while(true) I have another while(cin>>(SOMEINT)) loop and push it back in a vector , and after it reads new line it just break the wile and continue with the calculation.
However in our test software this one give runtime error since after finding some cases then it start print infinity 0 0 since there is nothing to enter but the while(true) just continues.
I mean I just want to make it that way that the while is till user enters something , for instance you enter 30 50 90 it will return 80 90 , then wiat for another entry and so on.
CODE:
#include <iostream>
#include <string>
#include<vector>
#include <sstream>
#include <cmath>
#include <string.h>
#include <stdio.h>
#include <climits>
using namespace std;
const int length = 17000;
int power(int x){
int sum =2;
for(int i = 0;i<x;i++) {
sum *= 2;
}
return sum;
}
bool ison(int i,int x)
{
if((i>>x) & 1)return true;
return false;
}
int main()
{
while(true){
vector<int> Vec;
int cur = 0;
while (cin >> cur) {
Vec.push_back(cur);
if (cin.get() == '\n') {
break;
}
}
int * sumOfarr1 = new int[length];
int * sumOfarr2 = new int[length];
for(int i = 0; i<length;i++){
sumOfarr1[i] = 0;
}
for(int i = 0; i<length;i++){
sumOfarr2[i] = 0;
}
int index=0;
for(int i=1;i<length;i++)
{
for(int j=0;j<Vec.size();j++)
{
if(ison(i,j))
{
sumOfarr1[index]+=Vec[j];
}
else
{
sumOfarr2[index]+=Vec[j];
}
}index++;
}
int ans=INT_MAX;
int ii;
for(int i=0;i<index;i++)
{
if(abs(sumOfarr1[i]-sumOfarr2[i])<ans)
{
ii=i;
ans=abs(sumOfarr1[i]-sumOfarr2[i]);
}
}
if(sumOfarr1[ii]<sumOfarr2[ii]){
cout << sumOfarr1[ii] << " " << sumOfarr2[ii];
}
else{
cout << sumOfarr2[ii] << " " << sumOfarr1[ii];
}
cout << endl;
delete[] sumOfarr1;
delete[] sumOfarr2;
Vec.clear();
}
return 0;
}
Yes I found the solution just using getline and stringstream.
aka this
vector<int> Vec;
string line;
while(getline( cin, line ))
{
istringstream iss( line );
int number;
while( iss >> number )
Vec.push_back(number);
}
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;
}
This program reads strings of numbers from a txt file, converts them to integers, stores them in a vector, and then tries to output them in an organized fashion like so....
If txt file says:
7 5 5 7 3 117 5
The program outputs:
3
5 3
7 2
117
so if the number occurs more than once it outputs how many times that happens. Here is the code so far.
#include "std_lib_facilities.h"
int str_to_int(string& s)
{
stringstream ss(s);
int num;
ss >> num;
return num;
}
int main()
{
cout << "Enter file name.\n";
string file;
cin >> file;
ifstream f(file.c_str(), ios::in);
string num;
vector<int> numbers;
while(f>>num)
{
int number = str_to_int(num);
numbers.push_back(number);
}
sort(numbers.begin(), numbers.end());
for(int i = 0; i < numbers.size(); ++i)
{
if(i = 0 && numbers[i]!= numbers[i+1]) cout << numbers[i] << endl;
if(i!=0 && numbers[i]!= numbers[i-1])
{
cout << numbers[i] << '\t' << counter << endl;
counter = 0;
}
else ++counter;
}
}
Edit: Program is getting stuck. Looking for an infinite loop right now.
You could use a map of numbers to counters:
typedef map<int,unsigned int> CounterMap;
CounterMap counts;
for (int i = 0; i < numbers.size(); ++i)
{
CounterMap::iterator it(counts.find(numbers[i]));
if (it != counts.end()){
it->second++;
} else {
counts[numbers[i]] = 1;
}
}
... then iterate over the map to print results.
EDIT:
As suggested by lazypython: if you have the TR1 extensions [wikipedia.org] available, unordered_map should have better performance...
typedef std::tr1::unordered_map<int,unsigned int> CounterMap;
CounterMap counts;
for (int i = 0; i < numbers.size(); ++i)
{
CounterMap::iterator it(counts.find(numbers[i]));
if (it != counts.end()){
it->second++;
} else {
counts[numbers[i]] = 1;
}
}
How about using a map, where the key is the number you're tracking and the value is the number of occurrences?
If you must use a vector, you've already got it sorted. So just keep track of the number you previously saw. If it is the same as the current number, increment the counter. Every time the number changes: print out the current number and the count, reset the count, set the last_seen number to the new number.
Using a map is the practical solution. What you should do is to solve this problem :)
This is called frequency counter. So, you have a sorted vector and all what you have to do is to count successive equal numbers. In other words, you have to check each number with its successor.
for(size_t i = 0; i < numbers.size(); i++)
{
size_t count = 1;
size_t limit = numbers.size() - 1;
while(i < limit && numbers[i] == numbers[i+1])
{
count++;
i++;
}
std::cout << numbers[i] << "\t" << count << std::endl;
}
This program reads strings of numbers
from a txt file, converts them to
integers, stores them in a vector, and
then tries to output them in an
organized fashion like so....(emphasis added)
What is the point of this storage step? If you are reading the numbers from a file, then you already have them in order, ready to be processed (counted) one at time, as you encounter them.
However, I would need a way for it to know when it sees a new number.
I advise you to have a look at std::set or std::map. I expect either of these containers would do what you're looking for.
Std::count() fits the bill nicely.
std::vector<int>::const_iterator cur = numbers.begin();
std::vector<int>::const_iterator last = numbers.end();
while (cur != last) {
unsigned cnt = std::count(cur, last, *cur);
std::cout << *cur;
if (cnt != 1) {
std::cout << " " << c;
}
std::cout << std::endl;
int saved = *cur;
while (*cur == saved) {
++cur;
}
}
Of course there are a bunch of other algorithms out there that will do the same job. Play with things like std::equal_range() in conjunction with std::distance() will do the job just as nicely.
That was fun:
#include <map>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
struct IncrementMap
{
IncrementMap(std::map<int,int>& m): m_map(m) {}
void operator()(int val) const
{
++m_map[val];
}
std::map<int,int>& m_map;
};
struct SpecialPrint
{
SpecialPrint(std::ostream& s): m_str(s) {}
void operator()(std::map<int,int>::value_type const& value) const
{
m_str << value.first;
if (value.second != 1)
{
m_str << "\t" << value.second;
}
m_str << "\n";
}
std::ostream& m_str;
};
int main()
{
std::fstream x("Plop");
std::map<int,int> data;
std::for_each( std::istream_iterator<int>(x),
std::istream_iterator<int>(),
IncrementMap(data)
);
std::for_each( data.begin(),
data.end(),
SpecialPrint(std::cout)
);
}