Adding strings of integers - c++

I'm trying to write an algorithm for a larger project that will take two strings which are both large integers (only using 10 digit numbers for the sake of this demo) and add them together to produce a final string that accurately represents the sum of the two original strings. I realize there are potentially better ways to have gone about this from the beginning but I am supposed to specifically use strings of large integers as opposed to a long integer.
My thinking was to take the two original strings, reverse them so their ones position, tens position, and so on all line up properly for adding. Then one position at a time, convert the characters from the strings to single integers and add them together and then use that sum as the ones position or otherwise for the final string, which once completed will also be reversed back to the correct order of characters.
Where I'm running into trouble I think is in preparing for the event in which the two integers from the corresponding positions in their strings add to a sum greater than 9, and I would then have carry over some remainder to the next position. For example, if I had 7 and 5 in my ones positions that would add to 12, so I would keep the 2 and add 1 to the tens position once it looped back around for the tens position operation.
I'm not getting results that are in any way accurate and after spending a large amount of time stumbling over myself trying to rectify my algorithm, I am not sure what I need to do to fix this.
Hopefully my intended process is clear and someone will be able to point me in the right direction or correct some mistake I may have in my program.
Thanks in advance.
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
string str1 = "1234567890", str2 = "2345678901"; //Two original strings of large integers
string rev_str1, rev_str2;
int int1 = 0, int2 = 0;
string final; //Final product string, sum of two original strings
int temp_int = 0, buffer_int, remainder = 0;
string temp_str = "", buffer_str;
char buffer[100] = {0};
cout << "str1 = " << str1 << endl;
cout << endl;
cout << "str2 = " << str2 << endl;
cout << endl;
rev_str1 = string(str1.rbegin(), str1.rend());
rev_str2 = string(str2.rbegin(), str2.rend());
for (int i = 0; i < 10; i++)
{
buffer_str = rev_str1.at(i);
int1 = atoi(buffer_str.c_str());
buffer_str = rev_str2.at(i);
int2 = atoi(buffer_str.c_str());
buffer_int += (int1 + int2 + remainder);
remainder = 0;
while (buffer_int > 9)
{
buffer_int -= 10;
remainder += 10;
}
temp_str = itoa(buffer_int, buffer, 10);
final += temp_str;
}
final = string(final.rbegin(), final.rend());
cout << "final = " << final << endl;
cout << endl;
}

Here's what I came up with. It is just for two summands; if you have more, you'll have to adapt things a bit, in particular with the carry, which can then be larger than 19, and the way the result string is allocated:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Two original strings of large integers
string str1 = "1234567890",
str2 = "2345678901234";
// Zero-padd str1 and str2 to the same length
size_t n = max(str1.size(), str2.size());
if (n > str1.size())
str1 = string(n-str1.size(), '0') + str1;
if (n > str2.size())
str2 = string(n-str2.size(), '0') + str2;
// Final product string, sum of two original strings.
// The sum of two integers has at most one digit more, for more inputs make
// below reverse_iterator a back_insert_iterator, then reverse the result
// and skip the removal of the padding.
string final(n+1, '0');
// The carry
char carry = 0;
// Iterators
string::const_reverse_iterator s1 = str1.rbegin(), e = str1.rend(),
s2 = str2.rbegin();
string::reverse_iterator f = final.rbegin();
// Conversion
for (; s1 != e; ++s1, ++s2, ++f)
{
// Bracketing to avoid overflow
char tmp = (*s1-'0')+(*s2-'0') + carry;
if (tmp > 9)
{
carry = 1;
tmp -= 10;
}
else
{
carry = 0;
}
*f = tmp + '0';
}
final[0] = carry + '0';
// Remove leading zeros from result
n = final.find_first_not_of("0");
if (n != string::npos)
{
final = final.substr(n);
}
cout << "str1 = " << str1 << endl
<< "str2 = " << str2 << endl
<< "final = " << final << endl;
}

Your problem is that you are carrying 10s instead of 1s. When you add 19 + 5, you get 4 in the units position and add an extra 1 in the 10s position. You wouldn't add an extra 10 in the 10s position.
You simply need to change this line: remainder += 10; to remainder += 1;.
Also, that while loop isn't necessary if you have more than two addends. As it is, when you are adding only two digits at a time, the largest addends you can have are 9 + 9, which carries only 1.

#include<iostream>
using namespace std;
main(){
int sum =0;
int a;
int reminder;
cout<<"Enter the Number :"<<endl;
cin>>a;
while(a>0){
reminder=a%10;
sum=r+sum;
a=a/10;`enter code here`
}
cout<<"Additon is :"<<sum<<endl;
}

Related

My code for computing large sums fails this very specific test case and I'm not sure why

The point of this exercise was to create code that can compute very large sums by using an algorithm close to how you would do it by hand. My code seems to work just fine, except for one specific test case, which is 9223372036854775808 + 486127654835486515383218192. I'm not sure what is special about this specific test case for it to fail, because the code is totally capable of carrying over, as well as adding numbers that have two different amounts of digits...Help would be greatly appreciated.
Edit: The output for this case is +'2+-0+*.4058858552237994000
// Basic mechanism:
//reverse both strings
//reversing the strings works because ex. 12+12 is the same as 21+21=42->reverse->24
//add digits one by one to the end of the smaller string
//dividing each sum by 10 and attaching the remainder to the end of the result-> gets us the carry over value
// reverse the result.
//ex. 45+45 ->reverse = 54+54 -> do the tens place -> 0->carry over -> 4+4+1 -> result= 09 -> reverse -> 90.
#include <iostream>
#include <cstring>
using namespace std;
string strA;
string strB;
string ResStr = ""; // empty result string for storing the result
int carry =0;
int sum; //intermediary sum
int n1; //length of string 1
int n2; // length of string 2
int rem; // remainder
int main()
{
cout << "enter" << endl;
cin >> strA;
cout << "enter" << endl; // I didn't know how to write this program to use argv[1] and argv[2] so this was my solution
cin >> strB;
// turning the length of each string into an integer
int n1 = strA.length(), n2 = strB.length();
if (n1<n2){
swap(strA,strB);
}//for this part I have no idea why this has to be the case but it only works if this statement is here
// Reversing both of the strings so that the ones, tens, etc. positions line up (the computer reads from left to right but we want it to read from right to left)
reverse(strA.begin(), strA.end());
reverse(strB.begin(), strB.end());
for (int i=0; i<n2; i++)//start at 0, perform this operation until the amount of times reaches the value of n2
{
//get the sum of current digits
int sum = ((strA[i]-'0')+(strB[i]-'0')+carry);
int quotient=(sum/10);
int rem=(sum-10*quotient);
ResStr+=(rem+'0'); //this gets the remainder and adds it to the next row
// Calculate carry for next step. Thus works because carry is an integer type, so it will truncate the quotient to an integer, which is what we want
carry = sum/10;
}
// Add the remaining digits of the larger number
for (int i=n2; i<n1; i++) //start at n1, perform this operation until the amount of times reaches the value of n1
{
int sum = ((strA[i]-'0')+carry);
int quotient=(sum/10);
int rem=(sum-10*quotient);
ResStr+=(rem+'0');
carry = sum/10;
}
// Add remaining carry over value
if (carry)
ResStr+=(carry+'0');
// reverse the resulting string back, because we reversed it at the beginning
reverse(ResStr.begin(), ResStr.end());
cout << "The result is " << ResStr << endl;
return 0;
}
After a lot of experimentation, what made the difference for me was replacing n1 and n2 entirely with strA.length() and strB.length() respectively in the for loop declarations. I'm not entirely sure why this happens, so if anyone has an explanation- please forward it.
Anyway, here's my version of the code:
//Basic mechanism: reverse both strings
//reversing the strings works because ex. 12+12 is the same as 21+21=42->reverse->24 (for single-digit sums smaller than 10)
//add digits one by one to the end of the smaller string
//dividing each sum by 10 and attaching the remainder to the end of the result-> gets us the carry over value reverse the result (mod 10 arithetic)
//ex. 45+45 ->reverse = 54+54 -> do the tens place -> 0->carry over -> 4+4+1 -> result= 09 -> reverse -> 90.
//ex. 90+90 ->reverse = 09+09 -> do the tens place -> 0->carry over ->0+ 9+9 ->carry over->1+ result= 081 -> reverse -> 180.
#include <iostream>
using std::cin; using std::cout;
#include <cstring>
using std::string;
#include <algorithm>
using std::reverse;
string strA, strB, ResStr = "";
int carry = 0, sum;
int main() {
//get user input
cout << "Enter first number: "; cin >> strA;
cout << "Enter second number: "; cin >> strB; cout << "\n";
if (length_strA < length_strB){ swap(strA,strB); } //force stringA to be larger (or equal) in size
//Reversing both of the strings so that the ones, tens, etc. positions line up (the computer reads from left to right but we want it to read from right to left)
reverse(strA.begin(), strA.end()); cout << strA << "\n";
reverse(strB.begin(), strB.end()); cout << strB << "\n";
for (int i = 0; i < strB.length(); i++) {
sum = int(strA[i])-48 + int(strB[i])-48 + carry/10;
ResStr += char(sum % 10)+48;
carry = sum - sum%10;
}
// Add the remaining digits of the larger number
//start at strB.length, perform this operation until the amount of times reaches the value of strA.length
for (int i = strB.length(); i < strA.length(); i++) {
sum = int(strA[i])-48 + carry/10;;
ResStr += char(sum % 10)+48;
carry = sum - sum%10;
}
// Add remaining carry over value
if (carry != 0) { ResStr += char(carry)+48; }
// reverse the resulting string back, because we reversed it at the beginning
reverse(ResStr.begin(), ResStr.end());
//return user result
cout << "The result is: " << ResStr << "\n";
return 0; }
To answer why, it's because even once strB ended, it kept iterating through making a new sum in the first loop until strA ended. This meant it was reading null values for strB[i] and adding that to strA[i]+carry- which effectively shifted all the characters into the noisy-looking mess it was.

Adding to very large numbers using stack

i am a novice to C++ , I was trying to write this program for adding two very large numbers using strings but the program is not working correctly and I can't get what's wrong with it , please help me with this.
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main() {
stack <char> a1;
stack<char> a2;
stack<int> result;
stack<int> temp;
int carry = 0;
string num1;
string num2;
cout << "Enter first number (both numbers should have equal digits)" << endl;
getline(cin, num1);
cout << "Enter second number" << endl;
getline(cin, num2);
for (int i = num1.size()-1; i >= 0; i--) {
a1.push(num1[i]);
a2.push(num2[i]);
}
while (!a1.empty() && !a2.empty()) {
int element = (int)a1.top() + (int)a2.top() + carry;
cout << element;
if (element > 10) {
element %= 10;
carry = 1;
}
result.push(element);
cout << result.top() << endl;
a1.pop();
a2.pop();
}
string abc;
while (!result.empty()) {
temp.push(result.top());
result.pop();
abc += temp.top();
}
cout << abc;
}
I know i have definitely made a logical mistake , but i can't get it , can anyone please guide me?
the following is the output am getting
I was thinking, why stacks should be used. My guess is that you did this, because the numbers must be processed from right to left.
Additionally, you have obiously a challenge with strings with a different length.
But both problems can be solved easily. Let us start with the different length strings.
If 2 strings have a different length, we can pad (fill in) the shorter string with leading `0's. How many leading '0s' do we need to add? Right, the delta of the lengths.
And for inserting characters in a string at a certain position, we have the function insert.
So, the code for that will look like this:
if (numberAsString1.length() < numberAsString2.length())
numberAsString1.insert(0, numberAsString2.length() - numberAsString2.length(), '0');
else
numberAsString2.insert(0, numberAsString1.length() - numberAsString2.length(), '0');
This is rather straightforward.
The result will always be 2 strings with equal length. With entering "1234" and "9", we will get: "1234" and "0009".
This makes the next task easier.
Now that we have 2 equal length strings, we can "add", like we learned in school.
We go from right to left, by starting with the highest possible index of a character in the string. This is always length-1.
For calculating the sum, we need first to subtract the ASCII code for '0' from the characters in the string, because the string contains not integer numbers, but characters. For example "123" consists of '1', '2', '3' and not of 1,2,3.
Suming up is then easy: digit + digit + carry.
The resulting digit is always the sum % 10. And the next carry is always sum / 10. Example 1: 3+5=8 8%10=8 8/10=0. Example 2: 9+8=17 17%10=7 17/10=1.
So, also this is rather simple.
After we worked on all digits of the strings, there maybe still a set carry. This we will then add to the string.
Adding digits will be done in any case using the instert function. Because we want to insert digits on the left side of the resulting string.
So, with working from right to left, using correct indices and the insert function, we do not have the need for a stack.
With a lot of input checking, the whole function would look like this:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
// Give instruction to user
std::cout << "\nPlease enter 2 positive interger numbers:\n";
// Here we will store the user input
std::string numberAsString1{}, numberAsString2{};
// Get strings from user and check, if that worked
if (std::cin >> numberAsString1 >> numberAsString2) {
// Check if all characters in string 1 are digits
if (std::all_of(numberAsString1.begin(), numberAsString1.end(), std::isdigit)) {
// Check if all characters in string 2 are digits
if (std::all_of(numberAsString2.begin(), numberAsString2.end(), std::isdigit)) {
// ---------------------------------------------------------------------------------
// Here we will store the calculated result
std::string result{};
// Temporary helpers
unsigned int carry{};
// ---------------------------------------------------------------------------------
// Make strings equal length. Pad with leading '0' s
if (numberAsString1.length() < numberAsString2.length())
numberAsString1.insert(0, numberAsString2.length() - numberAsString2.length(), '0');
else
numberAsString2.insert(0, numberAsString1.length() - numberAsString2.length(), '0');
// ---------------------------------------------------------------------------------
// Iterate over all digits from right to left
for (int i = numberAsString1.length()-1; i >= 0; --i) {
// Calculate the sum
const int sum = numberAsString1[i]-'0' + numberAsString2[i] - '0' + carry;
// Get the carry bit in case of overflow
carry = sum / 10;
// Save the resulting digit
result.insert(0, 1, sum % 10 + '0');
}
// handle last carry bit
if (carry) result.insert(0, 1, '1');
// ---------------------------------------------------------------------------------
// Show result
std::cout << "\n\nSum: " << result << '\n';
}
else std::cerr << "\n\nError: number 1 contains illegal characters\n";
}
else std::cerr << "\n\nError: number 2 contains illegal characters\n";
}
else std::cerr << "\n\nError: Problem with input\n";
return 0;
}

Output not as expected from the array

I am writing a code where I take user user text input, convert it to binary, store each binary character in an element in an array and then print A or T for 0 and G or C for 1 at random. But the ATGC seem to not follow this rule and they come at random for every digit; 0 and 1. So If the binary is 0010101 I need output as ATGACTG. Also when I store the binary in an int variable, the zero in front of it vanishes. Is there a way to keep it?
#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <ctime>
int main()
{
using namespace std;
int p, i=0, a[100000];
int s;
string myString;
int binary;
cout << "Type your text: ";
std::getline (std::cin,myString);
for (std::size_t k=0; k < myString.size(); ++k)
{
std::bitset<8> y(myString[k]);
std::string dna = y.to_string();
binary = atoi(dna.c_str());
cout << binary;
while (binary != 0)
{
a[i] = binary % 10;
binary = binary / 10;
i++;
}
}
std::cout << std::endl;
srand(time(0));
for (int j = (i-1); j>-1; j--)
{
if (a[j] == 0)
{
p = rand() %2;
if (p==0)
cout<< "A";
else
cout<< "T";
}
if (a[j] == 1)
{
s = rand() %2;
if (s == 0)
cout<< "G";
else
cout<< "C";
}
else
{
cout << "";
}
}
}
I don't know why exactly you wrote so much wrong code, but I've managed to extract (and change) the code that actually does the job.
#include <iostream>
#include <string>
#include <bitset>
#include <ctime>
int main()
{
int i = 0, a[8];
std::string myString;
std::cout << "Type your text: " << std::endl;
std::getline(std::cin, myString);
for(auto x : std::bitset<8>(myString).to_string())
a[i++] = x == '1';
std::cout << std::endl;
srand(time(0));
for(int j = 0; j < i; ++j)
if(a[j] == 0)
std::cout << (rand() % 2 ? "T" : "A");
else if(a[j] == 1)
std::cout << (rand() % 2 ? "C" : "G");
std::cout << std::endl;
}
And here's neater version of main:
int main()
{
std::vector<int> a; // using std::vector
std::bitset<8> bs;
std::cout << "Type your text: " << std::endl;
std::cin >> bs; // std::bitset can be read from stream via operator>>
for(auto x : bs.to_string())
a.push_back(x == '1');
std::cout << std::endl;
srand(time(0));
for(auto x : a)
if(x == 0)
std::cout << (rand() % 2 ? "T" : "A");
else if(x == 1)
std::cout << (rand() % 2 ? "C" : "G");
std::cout << std::endl;
}
Just ask if you want an explanation on some specific part.
I told you not to convert the string to an integer. You didn't listen. This is why leading 0 vanishes.
Your output seams to be completely random because you reverse the order of characters in the sequence when reading the information from a.
Here is how I'd solve your problem: run online
#include <iostream>
#include <string>
#include <bitset>
#include <ctime>
#include <cstdlib>
int main()
{
std::cout << "Type your text: " << std::endl;
std::string in_str;
std::getline(std::cin, in_str);
std::string binary_str;
for(int i = 0; i < in_str.size(); ++i)
{
char c = in_str.at(i);
binary_str.append(std::bitset<8>(c).to_string());
}
std::cout << binary_str << std::endl;
srand(time(0));
for(int i = 0; i < binary_str.size(); ++i)
{
char c = binary_str.at(i);
if(c == '0')
std::cout << (rand() % 2 ? "T" : "A");
else
std::cout << (rand() % 2 ? "C" : "G");
}
std::cout << std::endl;
}
If you have any questions, ask me in the comments.
Edit: the OP asked me to explain all mistakes in his program.
Where did all those zeros gone?
To answer this question I'll have to explain all things your program does line-by-line.
Here you convert a symbol to a bitset:
std::bitset<8> y(myString[k])
For example: if k is 'a', then the y would be 01100001.
Here you convert the bitset to a string:
std::string dna = y.to_string();
In our example the dna would be "01100001".
Here you convert the string to an integer:
binary = atoi(dna.c_str());
A very simplified version of what atoi does:
binary = 0;
for(int i = 0; i < dna.size(); ++i)
binary = binary * 10 + (dna.at(i) - '0')
In our example the binary would be 1100001.
Note: that's NOT where you loose zeros. At this point you are still able to extract them because you know that you need to extract 8 digits. So you can append leading zeros to up it's length to 8.
The next line is where you actually loose zeros the first time because cout doesn't know that you want to print 8 digits.
cout << binary;
In our example it would print 1100001.
And here you loose zeros again because you stop extracting digits as soon as binary == 0 even if you extracted less than 8 digits. Also note that you are actually reversing what the function atoi just did with the only difference that you don't get your leading zeros back and the reverse order of bits (see the next paragraph):
while (binary != 0)
{
a[i] = binary % 10;
binary = binary / 10;
i++;
}
Why the output is "random"?
Here you are iterating through myString in the standard order
for (std::size_t k=0; k < myString.size(); ++k)
e.g. if myString is "abc" than
in the first iteration myString[k] would be 'a'
in the second iteration myString[k] would be 'b'
in the third iteration myString[k] would be 'c':
But in this loop you extract digits in reverse order:
while (binary != 0)
{
a[i] = binary % 10;
binary = binary / 10;
i++;
}
eg if binary is 1100001
in the 1st iteration you extract 1 and binary becomes 110000
in the 2nd iteration you extract 0 and binary becomes 11000
in the 3rd iteration you extract 0 and binary becomes 1100
in the 4th iteration you extract 0 and binary becomes 110
in the 5th iteration you extract 0 and binary becomes 11
in the 6th iteration you extract 1 and binary becomes 1
in the 7th iteration you extract 1 and binary becomes 0
Now you end up with an array where bits inside a character code are reversed, but different characters are stored in the array in the normal order.
e.g. If the input string was "abc", then a would become:
1,0,0,0,0,1,1, 0,1,0,0,0,1,1, 1,1,0,0,0,1,1
reversed 'a' reversed 'b' reversed 'c'
If you iterate through a in normal order, the order of bits inside character codes would be reversed. If you iterate through a in reverse order, you get the reversed order of characters.
As a rule of thumb: don't program by guessing, program by thinking.
Further reading
The Zen of Python. Most of this aphorisms are applicable to every programming language with the exception of Brainfuck
Raw C arrays are evil

C++ Long Division

Whilst working on a personal project of mine, I came across a need to divide two very large arbitrary numbers (each number having roughly 100 digits).
So i wrote out the very basic code for division (i.e., answer = a/b, where a and b are imputed by the user)and quickly discovered that it only has a precision of 16 digits! It may be obvious at this point that Im not a coder!
So i searched the internet and found a code that, as far as i can tell, uses the traditional method of long division by making a string(but too be honest im not sure as im quite confused by it). But upon running the code it gives out some incorrect answers and wont work at all if a>b.
Im not even sure if there's a better way to solve this problem than the method in the code below!? Maybe there's a simpler code??
So basically i need help to write a code, in C++, to divide two very large numbers.
Any help or suggestions are greatly appreciated!
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std; //avoids having to use std:: with cout/cin
int main (int argc, char **argv)
{
string dividend, divisor, difference, a, b, s, tempstring = ""; // a and b used to store dividend and divisor.
int quotient, inta, intb, diff, tempint = 0;
char d;
quotient = 0;
cout << "Enter the dividend? "; //larger number (on top)
cin >> a;
cout << "Enter the divisor? "; //smaller number (on bottom)
cin >> b;
//making the strings the same length by adding 0's to the beggining of string.
while (a.length() < b.length()) a = '0'+a; // a has less digits than b add 0's
while (b.length() < a.length()) b = '0'+b; // b has less digits than a add 0's
inta = a[0]-'0'; // getting first digit in both strings
intb = b[0]-'0';
//if a<b print remainder out (a) and return 0
if (inta < intb)
{
cout << "Quotient: 0 " << endl << "Remainder: " << a << endl;
}
else
{
a = '0'+a;
b = '0'+b;
diff = intb;
//s = b;
// while ( s >= b )
do
{
for (int i = a.length()-1; i>=0; i--) // do subtraction until end of string
{
inta = a[i]-'0'; // converting ascii to int, used for munipulation
intb = b[i]-'0';
if (inta < intb) // borrow if needed
{
a[i-1]--; //borrow from next digit
a[i] += 10;
}
diff = a[i] - b[i];
char d = diff+'0';
s = d + s; //this + is appending two strings, not performing addition.
}
quotient++;
a = s;
// strcpy (a, s);
}
while (s >= b); // fails after dividing 3 x's
cout << "s string: " << s << endl;
cout << "a string: " << a << endl;
cout << "Quotient: " << quotient << endl;
//cout << "Remainder: " << s << endl;
}
system ("pause");
return 0;
cin.get(); // allows the user to enter variable without instantly ending the program
cin.get(); // allows the user to enter variable without instantly ending the program
}
There are much better methods than that. This subtractive method is arbitrarily slow for large dividends and small divisors. The canonical method is given as Algorithm D in Knuth, D.E., The Art of Computer Programming, volume 2, but I'm sure you will find it online. I'd be astonished if it wasn't in Wikipedia somewhere.

Brute Force Character Generation in C++

So I'm trying to make a brute force string generator to match and compare strings in CUDA. Before I start trying to mess around with a language I don't know I wanted to get one working in C++. I currently have this code.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int sLength = 0;
int count = 0;
int charReset = 0;
int stop = 0;
int maxValue = 0;
string inString = "";
static const char charSet[] = //define character set to draw from
"0123456789"
"!##$%^&*"
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int stringLength = sizeof(charSet) - 1;
char genChars()
{
return charSet[count]; //Get character and send to genChars()
}
int main()
{
cout << "Length of string to match?" << endl;
cin >> sLength;
cout << "What string do you want to match?" << endl;
cin >> inString;
string sMatch(sLength, ' ');
while(true)
{
for (int y = 0; y < sLength; y++)
{
sMatch[y] = genChars(); //get the characters
cout << sMatch[y];
if (count == 74)
{
charReset + 1;
count = 0;
}
if (count == 2147000000)
{
count == 0;
maxValue++;
}
}
count++;
if (sMatch == inString) //check for string match
{
cout << endl;
cout << "It took " << count + (charReset * 74) + (maxValue*2147000000) << " randomly generated characters to match the strings." << endl;
cin >> stop;
}
cout << endl;
}
}
Now this code runs and compiles but it doesn't exactly do what I want it to. It will do 4 of the same character, EX. aaaa or 1111 and then go onto the next without incrementing like aaab or 1112. I've tried messing around with things like this
for (int x = 0; x < sLength; x++)
{
return charSet[count-sLength+x];
}
Which in my mind should work but to no avail.
You basically just need to increment a counter, than convert the count number to base (size of char array)
Here's an example which does normal numbers up to base 16.
http://www.daniweb.com/code/snippet217243.html
You should be able to replace
char NUMS[] = "0123456789ABCDEF";
with your set of characters and figure it out from there. This might not generate a large enough string using a uint, but you should be able to break it up into chunks from there.
Imagine your character array was "BAR", so you would want to convert to a base 3 number using your own symbols instead of 0 1 and 2.
What this does is perform a modulus to determine the character, then divide by the base until the number becomes zero. What you would do instead is repeat 'B' until your string length was reached instead of stopping when you hit zero.
Eg: A four character string generated from the number 13:
14%3 = 2, so it would push charSet[2] to the beginning of the empty string, "R";
Then it would divide by 3, which using integer math would = 4. 4%3 is again 1, so "A".
It would divide by 3 again, (1) 1%3 is 1, so "A".
It would divide by 3 again, (0) -- The example would stop here, but since we're generating a string we continue pushing 0 "B" until we reach 4 our 4 characters.
Final output: BAAR
For an approach which could generate much larger strings, you could use an array of ints the size of your string, (call it positions), initialize all the ints to zero and do something like this on each iteration:
i = 0;
positions[i]++;
while (positions[i] == base)
{
positions[i] = 0;
positions[++i]++;
}
Then you would go through the whole array, and build the string up using charSet[positions[i]] to determine what each character is.