How to find specific numbers of repeating consecutive digits? - c++

I am having trouble making this function evaluate if a a six digit integer has either a set of two repeated consecutive digits or four. All other sets of repeated consecutive digits should evaluate to false.
Examples of good input: 122345, 133335
Bad input: 123335, 666478
Here is my code:
bool hasDuplicate(int number){
int rem, num, dig;
do {
rem = number % 10;
num = number / 10;
dig = num % 10;
if (rem == dig) {
return true;
}
else {
return hasDuplicate(num);
}
} while (number > 0);
return false;
}

Consider converting the number to string and then just scanning the characters in the string from left to right.
bool hasDuplicate(int number) {
std::string s = std::to_string(number);
bool good = false;
bool bad = false;
int consecutive = 1;
// deliberately starting at s[1]
for (size_t i = 1; i < s.size(); i++) {
bool dupe = (s[i - 1] == s[i]);
if (dupe) {
consecutive++;
}
// last iteration or this char is not a duplicate of the previous one
if ((i + 1 == s.size()) || (!dupe)) {
bool good_sequence = (consecutive == 2) || (consecutive == 4);
good = good || good_sequence;
bool bad_sequence = (consecutive == 3) || (consecutive > 4);
bad = bad || bad_sequence;
}
if (!dupe) {
consecutive = 1;
}
}
return good && !bad;
}

Related

run-length encoding is not working with big numbers

I have a assingment were I need to code and decode txt files, for example: hello how are you? has to be coded as hel2o how are you? and aaaaaaaaaajkle as a10jkle.
while ( ! invoer.eof ( ) ) {
if (kar >= '0' && kar <= '9') {
counter = kar-48;
while (counter > 1){
uitvoer.put(vorigeKar);
counter--;
}
}else if (kar == '/'){
kar = invoer.get();
uitvoer.put(kar);
}else{
uitvoer.put(kar);
}
vorigeKar = kar;
kar = invoer.get ( );
}
but the problem I have is if need to decode a12bhr, the answer is aaaaaaaaaaaabhr but I can't seem to get the 12 as number without problems, I also can't use any strings.
try to put a repeated character when next is not numeric or end of string.
For prepare this, it needs to make number by parsing string.
about this, I recommend you to find how to convert string to integer in real time at C++.
bool isNumeric(char ch) {
return '0' <= ch && ch <= '9';
}
string decode(const string& s) {
int counter = 0;
string result;
char prevCh;
for (int i = 0; i < s.length(); i++) {
if (isNumeric(s[i])) { // update counter
counter = counter * 10 + (s[i] - '0');
if (isNumeric(s[i + 1]) == false || i + 1 == s.length()) {
// now, put previous character stacked
while (counter-- > 1) {
result.push_back(prevCh);
}
counter = 0;
}
}
else {
result.push_back(s[i]);
prevCh = s[i];
}
}
return result;
}
now, decode("a12bhr3") returns aaaaaaaaaaaabhrrr. it works well.

Is there a way to store INT and strings in the same array?

I'm not sure how parsing works, nor have I been able to do it in C++.
I've created an algorithm that converts decimals to hexadecimals. The algorithm right now still outputs values bigger than 9, like 10 instead of A. The following function was supposed to deal with the issue but when I run it through, I can't store the normal 1-9 values with the As and Bs in the same array, which means I can't output them. I've been stuck on this for 2 days.
string hexValues(int remainder)
{
string A = "A";
string B = "B";
string C = "C";
string D = "D";
string E = "E";
string F = "F";
if (remainder == 10)
{
return A;
}
else if (remainder == 11)
{
return B;
}
else if (remainder == 12)
{
return C;
}
else if (remainder == 13)
{
return D;
}
else if (remainder == 14)
{
return E;
}
else if (remainder == 15)
{
return F;
}
}
hexMod = userDecNumber4Hex % 16;
if (hexMod > 9)
{
hexadecimalAnswer[y] = hexValues(hexMod);
}
else
{
hexadecimalAnswer[y] = hexMod;
}
while (userDecNumber4Hex != 0)
{
if (userDecNumber4Hex % 16 != 0)
{
hexMod = userDecNumber4Hex % 16;
if (hexMod > 9)
{
hexadecimalAnswer[y] = hexValues(hexMod);
}
else
{
hexadecimalAnswer[y] = hexMod;
}
userDecNumber4Hex = (userDecNumber4Hex-hexMod)/ 16;
y += 1;
}
else if (userDecNumber4Hex % 16 == 0)
{
userDecNumber4Hex = userDecNumber4Hex / 16;
if (userDecNumber4Hex > 9)
{
hexadecimalAnswer[y] = userDecNumber4Hex;
}
}
}
the code is long so i wasn't really sure what to post but there are multiple arrays- but its just one of them that i need to have store the values getting from the hexValues function, while it already has int values
Since the integers in your hexadecimal number are only going to range between 0 and 9, you can store them as characters. At the same time, you can store A-F as characters as well.
Therefore, instead return characters as the face values.
char hexValues (int remainder)
{
if (remainder < 10)
return '0' + remainder;
else
return 'A' + (remainder - 10);
}
For full conversion, here's a good excuse to use Recursion:
string decToHex (int n)
{
if (n < 16)
{
string s (1, decToHex (n));
return s;
}
else
return decToHex (n / 16) + hexValues (n % 16);
}

Conver BCD Strings to Decimal

I am looking for better ways to optimize this function for better performance, speed its targeted towards embedded device. i welcome any pointers, suggestion thanks
function converts string BCD to Decimal
int ConvertBCDToDecimal(const std::string& str, int splitLength)
{
int NumSubstrings = str.length() / splitLength;
std::vector<std::string> ret;
int newvalue;
for (auto i = 0; i < NumSubstrings; i++)
{
ret.push_back(str.substr(i * splitLength, splitLength));
}
// If there are leftover characters, create a shorter item at the end.
if (str.length() % splitLength != 0)
{
ret.push_back(str.substr(splitLength * NumSubstrings));
}
string temp;
for (int i=0; i<(int)ret.size(); i++)
{
temp +=ReverseBCDFormat(ret[i]);
}
return newvalue =std::stoi(temp);
}
string ReverseBCDFormat(string num)
{
if( num == "0000")
{
return "0";
}
else if( num == "0001")
{
return "1";
}
else if( num == "0010")
{
return "2";
}
else if( num == "0011")
{
return "3";
}
else if( num == "0100")
{
return "4";
}
else if( num == "0101")
{
return "5";
}
else if( num == "0110")
{
return "6";
}
else if( num == "0111")
{
return "7";
}
else if( num == "1000")
{
return "8";
}
else if( num == "1001")
{
return "9";
}
else
{
return "0";
}
}
Update
this is what i plan to get, for a BCD Value::0010000000000000 Decimal Result 2000
BCD is a method of encoding decimal numbers, two to a byte.
For instance 0x12345678 is the BCD representation of the decimal number 12345678. But, that doesn't seem to be what you're processing. So, I'm not sure you mean BCD when you say BCD.
As for the code, you could speed it up quite a bit by iterating over each substring and directly calculating the value. At a minimum, change ReverseBCDFormat to return an integer instead of a string and calculate the string on the fly:
temp = temp * 10 + ReverseBCDFormat(...)
Something like that.
What you call BCD is not actually BCD.
With that out of the way, you can do this:
int ConvertBCDToDecimal(const std::string& str, int splitLength)
{
int ret = 0;
for (unsigned i = 0, n = unsigned(str.size()); i < n; )
{
int v = 0;
for (unsigned j = 0; j < splitLength && i < n; ++j, ++i)
v = 2*v + ('1' == str[i] ? 1 : 0); // or 2*v + (str[i]-'0')
ret = 10*ret + v;
}
return ret;
}
Get rid of all the useless vector making and string copying. You don't need any of those.
Also, I think your code has a bug when processing strings with lengths that aren't a multiple of splitLength. I think your code always considers them to be zero. In fact, now that I think about it, your code won't work with any splitLength other than 4.
BTW, if you provide some sample inputs along with their expected outputs, I would be able to actually verify my code against yours (given that your definition of BCD differs from that of most people, what your code does is not exactly clear.)
as soon as you're optimizing function, here is different variant:
int ConvertBCDToDecimal(const std::string& str) {
unsigned int result = 0;
const std::string::size_type l = str.length();
for (std::string::size_type i = 0; i < l; i += 4)
result = result * 10 + ((str[i] - '0') << 3) + ((str[i + 1] - '0') << 2) + ((str[i + 2] - '0') << 1) + (str[i + 3] - '0');
return result;
}
note: you don't need splitLength argument, as you know that every digit is 4 symbols

Modify an array in spiral way

I am trying to make this go through the array in a spiral order. When it finds 2, it should replace it with 0 and the next number in the spiral order should become 2. So, if my array is
000
200
000
is should become
000
020
000
The variable ok tells me if I found that number 2 and simply modifies the next number to 2. Note that it doesn't loop through it. When It reaches the center of the array, it stops and doesn't go backwards or starts over.
Any ideas why it doesn't work? It simply doesn't modify my array at all.
#include<iostream>
using namespace std;
#define ROWS 3
#define COLS 3
int main()
{
int arr[ROWS][COLS] = {{2,0,0},
{0,0,0},
{0,0,0}};
// Four direction counters of current movement
// Horizontal right, vertical bottom, horizontal left and vertical top respectively
int hr, vb, hl, vt, ok=0;
// levl indicates current depth of our imaginary rectangle into array. Starting value is zero
// since we are looping on the boundaries and ending value is the inner most rectangle
int levl;
for (levl=0; levl < COLS - levl; levl++)
{
for(hr=levl; hr < COLS-levl; hr++) // go right
{
if (ok==1)
{
arr[levl][hr] == 2;
ok = 2;
}
if ( (arr[levl][hr] == 2) && (ok == 0) )
{
arr[levl][hr] == 0;
ok = 1;
}
}
for(vb=levl+1; vb < COLS-levl; vb++) // go down
{
if (ok == 1)
{
arr[vb][hr-1] == 2;
ok = 2;
}
if ( (arr[vb][hr-1] == 2) && (ok == 0) )
{
arr[vb][hr-1] == 0;
ok = 1;
}
}
for(hl=vb-1; hl-1 >= levl; hl--) // go left
{
if ( ok == 1)
{
arr[vb-1][hl-1] == 2;
ok = 2;
}
if ( (arr[vb-1][hl-1] == 2) && (ok == 0) )
{
arr[vb-1][hl-1] == 0;
ok = 1;
}
}
for(vt=vb-1; vt-1 > levl; vt--) // go up
{
if (ok == 1)
{
arr[vt-1][hl] == 2;
ok = 2;
}
if ( (arr[vt-1][hl] == 2) && (ok==0) )
{
arr[vt-1][hl] == 0;
ok = 1;
}
}
}
cout << endl;
for(int t = 0;t < 3;t++)
{
for(int u = 0;u < 3;u++)
cout<<arr[t][u]<<" ";
cout<<endl;
}
int a;
cin>>a;
return 0;
}
The reason that your array is not being modified is because you are using "==" instead of "=". So
if ((arr[levl][hr] == 2)&&(ok==0))
{
arr[levl][hr] == 0;
ok=1;
}
should be
if ((arr[levl][hr] == 2)&&(ok==0))
{
arr[levl][hr] = 0;
ok=1;
}
== Is a comparison operator and = assigns the value. Check your code very carefully and make it more readable for you could be able to find easy mistakes like that :).

How should I approach a credit card number validation algorithm?

I'm writing a program to validate credit card numbers and I have to use Luhn's Algorithm. Let me say beforehand, that I have just started to learn to program (we covered loops like last week), so there a lot of things I am unfamiliar with. I am having trouble with one of my functions that checks the arithmetic. Basically, it has to double every second digit from right to left and add everything together. But if you double a number, like 5, and you get 10, then you will have to add 1+0=1 to the total sum instead of 10. That's the part I'm stuck on. How can I put that in a program?
Sample code so far:
int
doubleEvenSum(string creditCardNumber) {
int evenSum;
int countPosition;
int doublePosition;
int length;
length = creditCardNumber.length ();
countPosition = creditCardNumber.at(length - 2);
evenSum = 0;
while(countPosition>0) {
if ((2 * countPosition) < 10) {
doublePosition = 2 * countPosition;
}
else if ((2 * countPosition) > 9) {
???
}
evenSum = evenSum + doublePosition;
}
#include <stdio.h>
#include <string.h>
#include <ctype.h>
/*
return the Luhn (MOD10) checksum for a sequence of digits.
-1 is returned on error (a non-digit was in the sequence
*/
int mod10( char const* s)
{
int len = strlen(s);
int sum = 0;
int dbl = 0;
while (len) {
char digit;
int val;
--len;
digit = s[len];
if (!isdigit( (unsigned char) digit)) return -1; // non digit in the sequence
val = digit - '0'; // convert character to numeric value
if (dbl) {
// double the value
val *= 2;
// if the result is double-digits, add the digits together
if (val > 9) {
val = val - 10;
val = val + 1;
}
}
dbl = !dbl; // only double value every other time
sum += val;
}
return sum % 10;
}
Here is a different algorithm. I cut/pasted from a C# example; the second link discusses a number of optimization for Luhn.
Please study this example, and please run it through the debugger to study how the code behaves as it's executing. Understanding how code actually runs (as opposed to how you think it will run when you write it) is an essential skill. IMHO....
/*
* Validate credit card with Luhn Algorithm
*
* REFERENCES:
* - http://jlcoady.net/c-sharp/credit-card-validation-in-c-sharp
* - http://orb-of-knowledge.blogspot.com/2009/08/extremely-fast-luhn-function-for-c.html
*/
#include <stdio.h> // printf(), scanf(), etc
#include <string.h> // strlen (), etc
#include <ctype.h> // isdigit(), etc
#if !defined(FALSE)
#define FALSE 0
#define TRUE ~FALSE
#endif
/*
* type definitions (should go in separate header)
*/
enum CardType {
MASTERCARD=1, BANKCARD=2, VISA=3, AMEX=4, DISCOVER=5, DINERS=6, JCB=7
};
/*
* function prototypes (should also go in header)
*/
int luhn (int number[], int len);
bool validate (CardType cardType, char *cardNumber);
/*
* program main
*/
int
main (int argc, char *argv[])
{
char cc_number[80];
int cc_type;
for ( ;; ) {
printf ("Enter a credit card number and type (1, 2, 3, 4, 5. 6 or 7):\n");
printf (" MASTERCARD=1, BANKCARD=2, VISA=3, AMEX=4, DISCOVER=5, DINERS=6, JCB=7\n");
int iret = scanf ("%s %d", cc_number, &cc_type);
if (iret == 2)
break;
else
printf ("Incorrect input: please enter a valid CC# and CC type\n");
}
if (validate ((CardType)cc_type, cc_number))
printf ("Valid\n");
else
printf ("Invalid card type/number\n");
return 0;
}
/*
* validate card#
*/
bool
validate (CardType cardType, char *cardNumber)
{
// 16 or fewer digits?
int len = strlen(cardNumber);
if (strlen (cardNumber) > 16)
return false;
// number to validate
int number[16];
for(int i = 0; i < (int)strlen (cardNumber); i++) {
if(!isdigit(cardNumber[i]))
return FALSE;
number[i] = cardNumber[i] - '0';
}
// Validate based on card type, first if tests length, second tests prefix
switch(cardType) {
case MASTERCARD:
if(len != 16)
return FALSE;
if(number[0] != 5 || number[1] == 0 || number[1] > 5)
return FALSE;
break;
case BANKCARD:
if(len != 16)
return FALSE;
if(number[0] != 5 || number[1] != 6 || number[2] > 1)
return FALSE;
break;
case VISA:
if(len != 16 && len != 13)
return FALSE;
if(number[0] != 4)
return FALSE;
break;
case AMEX:
if(len != 15)
return FALSE;
if(number[0] != 3 || (number[1] != 4 && number[1] != 7))
return FALSE;
break;
case DISCOVER:
if(len != 16)
return FALSE;
if(number[0] != 6 || number[1] != 0 || number[2] != 1 || number[3] != 1)
return FALSE;
break;
case DINERS:
if(len != 14)
return FALSE;
if(number[0] != 3 || (number[1] != 0 && number[1] != 6 && number[1] != 8) || number[1] == 0 && number[2] > 5)
return FALSE;
break;
case JCB:
if(len != 16 && len != 15)
return FALSE;
if(number[0] != 3 || number[1] != 5)
return FALSE;
break;
default:
return FALSE;
}
int sum = luhn (number, len);
return (sum % 10 == 0);
}
// Use Luhn Algorithm to validate
int luhn (int number[], int len)
{
int sum = 0;
for(int i = len - 1; i >= 0; i--)
{
if(i % 2 == len % 2)
{
int n = number[i] * 2;
sum += (n / 10) + (n % 10);
}
else
sum += number[i];
}
return sum;
}
int luhnCardValidator(char cardNumbers[]) {
int sum = 0, nxtDigit, i;
for (i = 0; cardNumbers[i] != NULL_TERMINATOR ; i++) {
nxtDigit = cardNumbers[i] - START_OF_ASCII_NUMERIC;
if (i % 2 == 0)
nxtDigit = (nxtDigit > 4) ? (nxtDigit * 2 - 10) + 1 : nxtDigit * 2;
sum += nxtDigit;
}
return (sum % 10);
}
This:
... (nxtDigit > 4) ? (nxtDigit * 2 - 10) + 1 : ...
is the clever bit. If the digit is greater than 4, then the doubling will be 10 or more. In that case, you take the doubled number and subtract 10 which will give you the ones-digit then you add 1 (the tens-digit).
Just subtract 9 from the double of the number then you will equivalent of the sum of the digits.
For ex.
7= 7*2 = 14 = 1+4 = 5 OR 14-9 = 5
This is more efficient than writing code for adding both digits.