indexOf and substring skipping 1 result - c

I'm trying to separate / explode an String to do something with it later on.
The input string is this:
1_2_3_2_2
The function I'm calling with the above value as parameter:
void parseXString(String value){
int amountX = (value.length() / 2) + 1;
int seperatorIndex = value.indexOf('_');
int secondSeperator = 0;
for(int i = 0; i < amountX; i++){
String xPoint = "";
if(i == 0){
xPoint = value.substring(0, seperatorIndex);
}else{
xPoint = value.substring(seperatorIndex + 1, secondSeperator);
}
sendMessage((String)i + " X = " + xPoint + " || SEP: " + (String)seperatorIndex + " / " + (String)secondSeperator );
seperatorIndex = value.indexOf("_", seperatorIndex + 1);
secondSeperator = value.indexOf("_", seperatorIndex + 1);
}
sendMessage("Last X = " + value.substring(seperatorIndex + 1));
}
The sendMessage function will shout the value back to the operating Java application. The output I get is this:
0 X = 1 || SEP: 1 / 0
1 X = 3 || SEP: 3 / 5
2 X = 2 || SEP: 5 / 7
3 X = 2 || SEP: 7 / -1
4 X = 1 || SEP: -1 / 1
Last X = 2_3_2_2
As you can notice, on the second iteration there should be an return of the value 2 instead of an 3.
I think there's something wrong with the seperatorIndexes, but I'm out of the blank right now (working on this way to long).
So my question is very simple. Why doesn't I get the right value back / how can I fix that?

Your error is that you increase seperatorIndex in the first iteration. Therefore, seperatorIndex is 3 in your second iteration.
You should put the part where you increment seperatorIndex into the else part of your if(i == 0) condition. When doing this, you also have to increment secondSeperator in the if part of your condition.

Related

Wanted to check if a credit card number is valid or not

I wanted to check if a credit card number is valid or not but when i run the code, every number I give as input, the output comes as invalid.
The example given below is what I should i do.
Example with David’s Visa: 4003600000000014.
For the sake of discussion, let’s first underline every other digit, starting with the number’s second-to-last digit:
4003600000000014
Okay, let’s multiply each of the underlined digits by 2:
1•2 + 0•2 + 0•2 + 0•2 + 0•2 + 6•2 + 0•2 + 4•2
That gives us:
2 + 0 + 0 + 0 + 0 + 12 + 0 + 8
Now let’s add those products’ digits (i.e., not the products themselves) together:
2 + 0 + 0 + 0 + 0 + 1 + 2 + 0 + 8 = 13
Now let’s add that sum (13) to the sum of the digits that weren’t multiplied by 2 (starting from the end):
13 + 4 + 0 + 0 + 0 + 0 + 0 + 3 + 0 = 20
, the last digit in that sum (20) is a 0, so David’s card is legit!
#include <stdio.h>
int main()
{
int no;
printf("Visa number: ");`
scanf("%d", &no);
int d_1, d_2, d_3, d_4, d_5, d_6, d_7, d_8, d_9, d_10, d_11, d_12, d_13, d_14, d_15;
d_15 = no%10;
d_14 = ((no%100)/10)*2;
d_13 = (no%1000)/100;
d_12 = ((no%10000)/1000)*2;
d_11 = (no%100000)/10000;
d_10 = ((no%1000000)/100000)*2;
d_9 = (no%10000000)/1000000;
d_8 = ((no%100000000)/10000000)*2;
d_7 = (no%1000000000)/100000000;
d_6 = ((no%10000000000)/1000000000)*2;
d_5 = (no%100000000000)/10000000000;
d_4 = ((no%1000000000000)/100000000000)*2;
d_3 = (no%10000000000000)/1000000000000;
d_2 = ((no%100000000000000)/10000000000000)*2;
d_1 = (no%1000000000000000)/100000000000000;
int d[7] = {d_2, d_4, d_6, d_8, d_10, d_12, d_14};
int n,add;
for (n=1; n<=7; n++)
if(d[n]>10)
{
d[n] = (d[n]%10);
d[(15-n)+1] = ((d[n]%100)/10);
int sum=0;
for (int i=0; i<7; i++)
sum += d[i];
}
else
{
add = d_14 + d_12 + d_10 + d_8 + d_6 + d_4 + d_2;
}
int sum = add + d_15 + d_13 + d_11 + d_9 + d_7 + d_5 + d_3 + d_1;
if ((sum % 10) == 0)
{
printf("%s\n", "The card is valid");
}
else
{
printf("%s\n", "The card is invalid");
}
}
every number I give as input, the output comes as invalid.
Too big
OP's int is likely 32-bit.
Reading text input that would attempt to form an int outside the int range is undefined behavior. Rest of code is irrelevant.
int no;
scanf("%d", &no); // attempt to read "4003600000000014" leads to UB.
Consider reading user input into a string first and then process the characters. #Weather Vane
char buf[100];
if (fgets(buf, sizeof buf, stdin)) {
int i;
sum[2] = { 0, 0 }; // sums of even indexed digits and odd indexed digits.
// Note: only 1 sum really needed, but using 2 sums to mimic OP's approach
for (i = 0; isdigit((unsigned char) buf[i]); i++) {
digit = buf[i] - '0';
if (i%2 == 0) {
digit *= 2;
if (digit >= 10) {
digit = (digit/10 + digit%10);
}
}
sum[i%2] += digit;
}
// reject bad input: too long or missing expected end
if (i > 16 || (buf[i] != '\n' && buf[i] != '\0')) {
puts("Bad input");
} else {
// pseudo code to not give everything away.
// do math on sum[0], sum[1]
// if as expected --> success
}
}
#include <stdio.h>
#include <cs50.h>
long credit;
int getting_the_final_total_number (void);
void checking_which_kind (void);
int main(void)
{
credit = get_long("Number: ");
int i = 0;
long number_count = credit;
//finding how many numbers are there.
while(number_count > 0)
{
number_count /= 10;
i++;
}
//we use and because (using or make once true, the code block will work and always telling INVALID)
if(i != 13 && i != 15 && i != 16)
{
printf("INVALID\n");
return 0;
}
int total = getting_the_final_total_number(); //adding sum_1 and sum_2
if(total % 10 != 0)
{
printf("INVALID\n");
return 0;
}
checking_which_kind();
}
//assigning the credit to another variable for the loop
int getting_the_final_total_number (void)
{
long credit_one = credit;
int mod_1;
int mod_2;
int sum_1 = 0;
int m;
int d;
int sum_2 = 0;
do
{
//cutting the number into two pieces with all the last numbers and all the second-last-numbers
//cutting the last numbers.
mod_1 = credit_one % 10;
credit_one = credit_one / 10;
sum_1 += mod_1;
//cutting the second-last-numbers.
mod_2 = credit_one % 10;
credit_one = credit_one / 10;
//doubling the mod_2 (the second-last-numbers)
mod_2 = mod_2 * 2;
//making them into one number (if there is 16 or 18 in the product then make them 1 and 6 or 1 and 8. After that add them all together ).
m = mod_2 % 10; //This is for only one standing numer like 1 or 2 or 9 etc (but no 12 or 14 or 16)
d = mod_2 / 10; //This is for ten's digit to make sure to become ONE standing digit
sum_2 = sum_2 + m + d;
}
while(credit_one > 0);
return sum_1 + sum_2;
}
//checking the first two number of credit
void checking_which_kind (void)
{
long cc = credit;
do
{
cc = cc / 10;
}
while(cc > 100);
if(cc / 10 == 5 && (cc % 10 > 0 || cc % 10 < 6))
{
printf("MASTERCARD\n");
}
else if(cc / 10 == 3 && (cc % 10 == 4 || cc % 10 == 7))
{
printf("AMERICAN EXPRESS\n");
}
else if(cc / 10 == 4 && cc % 10 >= 0)
{
printf("VISA\n");
}
else
{
printf("ERROR");
}
}

Is this printf format possible (left-justify sign and no sign on zero)?

I'm trying to use printf to get the following programmatic output:
- 20
- 15
- 10
- 5
0
+ 5
+ 10
+ 15
+ 20
The key specifications are:
The field width is always 4
The sign is always left-justified
The number is always right-justified
The zero has no sign
So far I have not been able to come up with a printf statement that will give me the desired results. The closest I have is:
for(int i = -20; i <= 20; i+=5)
{
printf("%-+4d \n", i);
}
which produces:
-20
-15
-10
-5
+0
+5
+10
+15
+20
Is there a way to do this without having to do any cumbersome string manipulation?
printf("%c%3d\n", i>0 ? '+' : i<0 ? '-' : ' ', abs(i));
Note the above fails for INT_MIN, but that shouldn't be an issue since your values are only expected to be less than 1000 in magnitude.
A simple one-liner, not much different than others, yet with a nice look-up to a "- +" string.
printf("%c%3d\n", "- +"[i >= 0 + i > 0], abs(i));
To handle values outside the [-999 ... + 999] range and especially the pesky i = INT_MIN where the -i is undefined behavior, the code could use:
printf("%c%3u\n", "- +"[i >= 0 + i > 0], (i < 0) ? 0u - i: 0u + i);
// or
printf("%c%3lld\n", "- +"[i >= 0 + i > 0], llabs(i));
For a pedantic full range solution
// Buffer size = iceil(bit-width * log2(10)) + sign + null character
#define INT_BUF_SIZE (CHAR_BIT * sizeof(int)*31/100 + 3)
int print_int(int x) {
char buf[INT_BUF_SIZE*2];
sprintf(buf, "%+d", x);
int width = 4;
return printf("%c%*s\n", x ? buf[0] : ' ', width - 1, buf + 1);
}
Example output
- 20
0
+ 20
+2147483647
-2147483648
for(int i = -20; i <= 20; i+=5) {
if( i < 0 )
printf("-%3d \n", -i);
else if(i == 0)
printf(" 0 \n");
else
printf("+%3d \n", i);
}
for(int i = -20; i <= 20; i += 5){
if(i == 0){
printf("%4d\n", i);
}
else{
(i > 0) ? printf("+%3d\n", i) : printf("-%3d\n", -i);
}
}
It is ugly, but it works.

how to make 2 stage for loop statement from 1 stage for loop in c?

I'd like to make 2 stage for loop statment from 1 stage in the c.
//gray rgb
for (unsigned int i = 0; i < x * y; i++)
{
*(buff2 + i * 3 + 0) = data_[i];
*(buff2 + i * 3 + 1) = data_[i];
*(buff2 + i * 3 + 2) = data_[i];
}
But actually I can't get think how do I can make 2 stage.
Can you give a any hint?
Hope it would help you:-
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
*(buff2 + i*y + j) = data_[i*y+j]
}
}

Summing two numbers recursively digit by digit in C

I need to write to recursive functions, where in the first one, I need to sum two integers digit by digit. I have written some code, but it gives me the final result multiplied by 10. I see that the problem happens because when I sum first two digits I multiply them by 10.
The second function must count number of carries in the sum. Meaning if two digits were 3 and 8, then when we sum them we get 11, which is result 1, and carry 1. Simply, I just need to count how many carries occur.
Please note that I assume that both numbers have same number of digits.
#include <stdio.h>
int sum(int a, int b)
{
int temp = (a%10) + (b%10);
static int mul = 1;
if(a == 0 && b == 0)
return 0;
else
{
mul *= 10;
return (mul*temp) + sum(a/10, b/10);
}
}
int carry(int a, int b)
{
static int counter = 0;
if((a%10) + (b%10) > 9)
counter++;
if(a == 0 && b == 0)
return counter;
carry(a/10, b/10);
}
int main()
{
int a = 1941;
int b = 2282;
int result = sum(a, b);
printf("%d\n", result);
int car = carry(a, b);
printf("%d\n", car);
return 0;
}
return (mul*temp) + sum(a/10, b/10);
Should be:
return temp + 10*sum(a/10, b/10);
You don't need a static variable, Static variables are used to implement a global state whose lifetime extent the entire process. That's not something desirable and should only be used at last resort. Furthermore, that's definitely not what you need here, using static variables to implement your solution will leads to functions that only work the first time they are called.
You should use the recursive property of your algorithm to aggregate the result:
int sum(int a, int b)
{
if(a == 0 && b == 0) {
return 0;
}
else
{
return (a%10) + (b%10) + 10*sum(a/10, b/10);
}
}
sum(1941, 2282) will expand to :
sum(1941, 2282)
1 + 2 + 10*sum(194, 228)
1 + 2 + 10*(4 + 8 + 10*sum(19, 22))
1 + 2 + 10*(4 + 8 + 10*(9 + 2 + 10*sum(1, 2))
1 + 2 + 10*(4 + 8 + 10*(9 + 2 + 10*(1 + 2 + 10*sum(0, 0))
1 + 2 + 10*(4 + 8 + 10*(9 + 2 + 10*(1 + 2 + 10*0)
You should use the same approach for carry :
int carry(int a, int b)
{
if(a == 0 && b == 0) {
return 0;
}
else if((a%10) + (b%10) > 9) {
return 1 + carry(a/10, b/10);
}
else {
return carry(a/10, b/10);
}
}
carry(1941, 2282) will expand to :
carry(1941, 2282)
0 + carry(194, 228)
0 + 1 + carry(19, 22)
0 + 1 + 1 + carry(1, 2)
0 + 1 + 1 + 0 + carry(0, 0)
0 + 1 + 1 + 0 + 0

tricky interview question in C

In the following interview question :
Given a number n, give me the numbers
(among 3..5 and an even number of
numbers) whose adding would return the
original number. The resulting numbers
should be as balanced as possible,
meaning that instead of returning 3
and 5, for instance, return 4 and
4. Ex:
7 = 3 + 4
16 = 4 + 4 + 4 + 4 rather than 3 + 5 + 4 + 4
24 = 12 + 12 or 6 + 6 + 6 + 6
I thought of the following method:
splitnumber(int n)
{
//check if the number is even
if(n%2==0)
{
print(n/2,n/2);
//check if x=2^m multiple exists or
// not..like 4,8,16 etc
print (n/x...n/x);
}
else //else if the no is odd... this part is incomplete
{
if(n-3>0)
{
print (3);
}
n-=3;
if(n>0)
{
if (n>5)
{
print(3)
n-=3;
}
}
}
}
but still I am not able to complete all the cases... How should I check when the answer has unbalanced solution??
if (n < 4) print n;
else
switch (n % 4)
case 0: *print n/4 4's*
case 1: *print n/4 - 1 4's* print 5
case 2: *print n/4 - 1 4's* print 3 print 3
case 3: *print n/4 4's* print 3
Slightly inefficient implementation in C#
if (n < 4) Console.WriteLine(n);
else
switch (n % 4)
{
case 0:
Console.WriteLine(String.Join(" ", new string('4', n / 4).ToArray()));
break;
case 1:
Console.WriteLine(
(String.Join(" ", new string('4', n/4).ToArray().Skip(1)) +
" 5").TrimStart());
break;
case 2:
Console.WriteLine(
(String.Join(" ", new string('4', n/4).ToArray().Skip(1)) +
" 3 3").TrimStart());
break;
case 3:
Console.WriteLine(String.Join(" ", new string('4', n/4).ToArray() +
" 3"));
break;
}
Here is my solution where the result will be perfectly balanced and with detection of impossible cases:
vector<int> recursive_splitnumber(int n) {
if (n <= 5) {
return vector<int>(1,n);
}
int unbalancer = 0;
vector<int> result1, result2;
do {
int val1, val2;
if (n%2 == 0) {
val1 = n%2 + unbalancer;
val2 = n%2 - unbalancer;
}
else {
val1 = (n-1)%2 + 1 + unbalancer;
val2 = (n-1)%2 - unbalancer;
}
result1 = recursive_splitnumber(val1);
result2 = recursive_splitnumber(val2);
// Concatenate the result of the even and odd splits
result1.insert(result1.end(),result2.begin(),result2.end());
++unbalancer;
} while (result1.size()%2 != 0 && unbalancer <= 1);
return result1;
}
bool splitnumber(int n) {
vector<int> split = recursive_splitnumber(n);
if (split.size()%2 == 0) {
copy(split.begin(), split.end(), ostream_iterator<int>(cout, " "));
return true;
} else
return false;
}
That solution will also take into account cases like the number 22 where the balanced division gives 11+11 (11 being a number that cannot be represented using the given rules), the subdivision will be done as 10+12, then 5+5+6+6 and finally 5+5+3+3+3+3.

Resources