Access number that corresponds to string - c++

Let's say I have the following variables:
int number1 = 2;
int number2 = 4;
...
int numbern = 43;
Now what I want is to access these elements in a for loop over number 'i', so something like the following:
for (int i = 0; i < n; i++)
{
if(number1 == someFunc("number" + to_string(i)))
{
// do stuff
}
}
Here 'someFunc' should make sure that it recognizes that I want to use the number that the string corresponds to. How could I do this?

For using std::map you can do something like this:
#include <iostream>
#include <stdlib.h>
#include <map>
#include <string>
using namespace std;
int main (void)
{
map<string,int> mymap;
mymap["number1"] = 2;
mymap["number2"] = 4;
/* ... */
char number[2];
number[1] = '\0';
for(int ii=1; ii<=2; ii++)
{
number[0] = (char)(ii+48);
cout << string("number")+string(number) << ": ";
mymap[string("number")+string(number)] += 1;
cout << mymap[string("number")+string(number)] << endl;
}
return 0;
}
Here is the string the key through which you can access the actual number. In this example I didn't ensure that the key actually exists anyway this should be done normally.

If the number of numbers is not big then you can write
int i = 0;
for ( int x : { number1, number2, /* other numbers */ numbern } )
{
if ( x == someFunc( "number" + to_string( i ) ) )
{
// do stuff
}
++i;
}
Otherwise you should place the numbers in some container.

I can think of the following two options:
Use an array.
int numbers[] = {/* Put the initialization data*/};
....
if(number1 == someFunc(numbers[i]))
Use a map. This option is useful if the size of the array is open to change or the key is expected to not follow the usual array index values.
std::map<int, int> numbers;
// Add code to initialize the map.
....
if(number1 == someFunc(numbers[i]))

Related

How do I print the following array to show number 1 - 1000000

I want to initialize an array and fill it from 1-1000000. How do I then print the array?
#include<iostream>
using namespace std;
const int holder = 1000000;
int main()
{
int i = 0;
int nums[holder] = {0};
for( int i = 0; i < holder; i++)
{
nums[i] = i+1;
}
return 0;
}
How about something like this:
// First create a vector containing holder elements
std::vector<int> nums(holder);
// Then set each element to the number from 1 to holder, inclusive
std::iota(begin(nums), end(nums), 1);
Then to print it:
// Print each number in the vector, separated by newlines
for (auto num : nums)
{
std::cout << num << '\n';
}
Many parts of this answer should really be part of any decent beginners book. The only "new" thing would be the std::iota call.

C++ How to find out most consecutive digits in an array?

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;
}

How to check that all random array elements are different

I'm trying to pass random integers (between 0 and 11) to the Numbers[] array, but i have to make sure that all 10 of its elements are different. I've tried to pass the numbers first in the array, and then check if there are any numbers that are equal but its not working this way. Here's my code:
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
int Numbers[10];
srand( time(NULL) );
for (int i = 0; i < 10; i++ )
{
Numbers[i] = rand() % 12; // First, the integers are passed
to the array (They must be between 0 and 11)
cout << Numbers[i] << endl; // and printed to the screen
}
cout << endl << endl;
for (int u = 0; u < 10; u++)
{
if(Numbers[u] == Numbers[u - 1]) // If there are two equal
numbers
{
switch (Numbers[u]) // One of them is incremented (But that
causes problems as well because it can lead to another pair of equals)
{
case 11: // In case one of them is 11
Numbers[u]--;
break;
default:
Numbers[u]++;
break;
}
}
cout << Numbers[u] << endl;
}
return 0;
}
Halp!
Just use std::vector, std::iota and std::shuffle:
std::vector<int> v( 12 );
std::iota( v.begin(), v.end(), 0 ); // initialize with values 0..11
std::shuffle(v.begin(), v.end(), std::mt19937{std::random_device{}()}); // make em random
v.resize( 10 ); // remove extra elements
and you do not need to validate that all elements are unique
What I understood from your question that you are trying to read random numbers till all 10 numbers are different. Have a look on code below:
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <bitset>
using namespace std;
int main()
{
int Numbers[10] ;
srand(time(NULL));
//Keep flag with all the bits '0' initially
bitset<12> flags;
flags.reset();
// keep taking input till all bits are not '1'
int i = 0;
do
{
int in_num = rand() % 12;
// check if the bit at position "in_num" is 0
if (!flags[in_num])
{
Numbers[i++] = in_num;
flags.set(in_num);// set the bit 1
}
} while (i < 10);
for (int u = 0; u < 10; u++)
{
cout << endl << Numbers[u];
}
return 0;
}

How to implement infinite multidimensional array?

I want to use the code below and I want to use it for "unknown size of input". For example there is an array int cac[1000][1000]. I can use vector<vector<int> > array;, then how can i initialize it with -1 ? Any suggestions?
#include <sstream>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <memory.h>
using namespace std;
int cac[1000][1000];
string res[1000][1000];
vector<string> words;
int M;
int go(int a, int b){
if(cac[a][b]>= 0) return cac[a][b];
if(a == b) return 0;
int csum = -1;
for(int i=a; i<b; ++i){
csum += words[i].size() + 1;
}
if(csum <= M || a == b-1){
string sep = "";
for(int i=a; i<b; ++i){
res[a][b].append(sep);
res[a][b].append(words[i]);
sep = " ";
}
return cac[a][b] = (M-csum)*(M-csum);
}
int ret = 1000000000;
int best_sp = -1;
for(int sp=a+1; sp<b; ++sp){
int cur = go(a, sp) + go(sp,b);
if(cur <= ret){
ret = cur;
best_sp = sp;
}
}
res[a][b] = res[a][best_sp] + "\n" + res[best_sp][b];
return cac[a][b] = ret;
}
int main(int argc, char ** argv){
memset(cac, -1, sizeof(cac));
M = atoi(argv[1]);
string word;
while(cin >> word) words.push_back(word);
go(0, words.size());
cout << res[0][words.size()] << endl;
}
What you can do is to use a associative array, where the key is a pair (rowPosition, ColumnPosition). When you want to set array[i][j] you just add or update the value assoArray[Pair(i,j)]. You can assume that any element which is not in the associative array has the initial value.
In general infinite multidimensional arrays are used for theoretical purpose.I hope i didn't misunderstood the question.
Using std::vector from the STL is much more straightforward than the following solution, which was pointed out in the comments for this post. I find that this site explains that topic effectively: http://www.learncpp.com/cpp-programming/16-2-stl-containers-overview/
An array of infinite size is not actually possible. However, you can achieve basically that effect using dynamic allocation. Here's some sample code:
int counter = 0;
int* myArray = new int[1000];
Fill the array with data, incrementing counter each time you add a value. When counter reaches 1000, do the following:
int* largerArray = new int[2000];
for( int i = 0; i < 1000; i++ )
{
largerArray[i] = myArray[i];
}
delete[] myArray;
myArray = largerArray;
With this method, you create the closest thing possible to an infinitely sized array, and I don't believe performance will be an issue with the copy piece

Algorithm to generate all permutation by selecting some or all charaters

I need to generate all permutation of a string with selecting some of the elements. Like if my string is "abc" output would be { a,b,c,ab,ba,ac,ca,bc,cb,abc,acb,bac,bca,cab,cba }.
I thought a basic algorithm in which I generate all possible combination of "abc" which are {a,b,c,ab,ac,bc,abc} and then permute all of them.
So is there any efficient permutation algorithm by which I can generate all possible permutation with varying size.
The code I wrote for this is :
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <map>
using namespace std;
int permuteCount = 1;
int compare (const void * a, const void * b)
{
return ( *(char*)a - *(char*)b);
}
void permute(char *str, int start, int end)
{
// cout<<"before sort : "<<str;
// cout<<"after sort : "<<str;
do
{
cout<<permuteCount<<")"<<str<<endl;
permuteCount++;
}while( next_permutation(str+start,str+end) );
}
void generateAllCombinations( char* str)
{
int n, k, i, j, c;
n = strlen(str);
map<string,int> combinationMap;
for( k =1; k<=n; k++)
{
char tempStr[20];
int index =0;
for (i=0; i<(1<<n); i++) {
index =0;
for (j=0,c=0; j<32; j++) if (i & (1<<j)) c++;
if (c == k) {
for (j=0;j<32; j++)
if (i & (1<<j))
tempStr[ index++] = str[j];
tempStr[index] = '\0';
qsort (tempStr, index, sizeof(char), compare);
if( combinationMap.find(tempStr) == combinationMap.end() )
{
// cout<<"comb : "<<tempStr<<endl;
//cout<<"unique comb : \n";
combinationMap[tempStr] = 1;
permute(tempStr,0,k);
} /*
else
{
cout<<"duplicated comb : "<<tempStr<<endl;
}*/
}
}
}
}
int main () {
char str[20];
cin>>str;
generateAllCombinations(str);
cin>>str;
}
I need to use a hash for avoiding same combination, so please let me know how can I make this algorithm better.
Thanks,
GG
#include <algorithm>
#include <iostream>
#include <string>
int main() {
using namespace std;
string s = "abc";
do {
cout << s << '\n';
} while (next_permutation(s.begin(), s.end()));
return 0;
}
Next_permutation uses a constant size, but you can add a loop to deal with varying size. Or just store in a set to eliminate the extra dupes for you:
#include <set>
int main() {
using namespace std;
string s = "abc";
set<string> results;
do {
for (int n = 1; n <= s.size(); ++n) {
results.insert(s.substr(0, n));
}
} while (next_permutation(s.begin(), s.end()));
for (set<string>::const_iterator x = results.begin(); x != results.end(); ++x) {
cout << *x << '\n';
}
return 0;
}
I don't think you can write much faster program than you have already. The main problem is the output size: it has order of n!*2^n (number of subsets * average number of permutations for one subset), which is already > 10^9 for a string of 10 different characters.
Since STL's next_permutation adds very limited complexity for such small strings, your program's time complexity is already nearly O(output size).
But you can make your program a bit simpler. In particular, for( k =1; k<=n; k++) loop seems unnecessary: you already calculate size of subset in variable c inside. So, just have int k = c instead of if (c == k). (You'll also need to consider case of empty subset: i == 0)
edit
Actually, there's only 9864100 outputs for n == 10 (not ~ 10^9). Still, my point remains the same: your program already wastes only "O(next_permutation)" time for each output, which is very, very little.