converting a string of numbers to binary - c++

If the string is "8123", I first converted the string number into its integer form 8123 and then sent this number to a function that converts it to binary. I got numbers as big as unsigned long long to work but once its passed that, the outputs are wrong. Is there a way to convert to binary by looking at each digit.
i.e looking a the 3, 2, 1, and 8 to convert to binary.
So rather than taking the string "999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999" and turning it into a number, is there a way to look at each character in this string and turn it into binary?
Any suggestions is much appreciated

Pseudocode:
string binary_string = ""
#an example
number = 81
while (number != 0)
#append the string casted value of the remainder of (number / 2)
#to the front of binary_string
binary_string = str(number % 2) + binary_string
number = number / 2
e.g. 81:
binary_string = str(81 % 2) + binary_string = str(1) + "" = "1"
number = 81 / 2 = 40
binary_string = str(40 % 2) + binary_string = str(0) + "1" = "01"
number = 40 / 2 = 20
binary_string = str(20 % 2) + binary_string = str(0) + "01" = "001"
number = 20 / 2 = 10
binary_string = str(10 % 2) + binary_string = str(0) + "001" = "0001"
number = 10 / 2 = 5
binary_string = str(5 % 2) + binary_string = str(1) + "0001" = "10001"
number = 5 / 2 = 2
binary_string = str(2 % 2) + binary_string = str(0) + "10001" = "010001"
number = 2 / 2 = 1
binary_string = str(1 % 2) + binary_string = str(1) + "010001" = "1010001"
81 -> "1010001"

string dec2bin(string in) {
for(size_t i = 0; i < in.length(); i++)
in[i] -= '0';
string out;
while(in.length()) {
out.insert(0, 1, '0' + (in[in.length()-1]&1));
char overflow = 0;
if(in[0]<=1) {
overflow = 10;
in.erase(0);
}
for(size_t i = 0; i<in.length(); i++) {
in[i] += overflow;
overflow = 10 * (in[i]&1);
in[i] /= 2;
}
}
return out;
}

Related

Result not matching up to Set Variable

I am scratching my brain off trying to figure this one out.
Why are running backs getting 60+ carries a game with this code? I just don't get it.
The team is an array, this for loop is only supposed to run 25 times AT MOST. I've even tried setting the for loop to (int g = 1; g < 20; g++) and yet still it is coming up with 60+ carries a game for no reason. Any help?
hold3 = rand() % (10 - 15 + 1) + 15;
for(int g = 1; g < hold3; g++){
hold = rand() % (15 - team[u].elusivness[2] + 1) + team[u].elusivness[2];
if(hold == 13 || hold == 14){
team[u].carries[2]++;
hold = rand() % (17 - team[u].strength[2] + 1) + team[u].strength[2];
if(hold == 13){
team[u].rushingtouchdowns[2]++;
hold = rand() % 25 + 5;
team[u].rushingyards[2] += hold;
}else{
hold = rand() % (12 - team[u].speed[2] + 1) + team[u].speed[2];
if(hold == 12){
hold = rand() % 15 + 5;
team[u].rushingyards[2] += hold;
}else{
hold = rand() % 5 + 1;
team[u].rushingyards[2] += hold;
}
}
}
}
you are trying getting mod from deviser below 0. hold3 = rand() % (10 - 15 + 1) + 15;

Function that reverse one part(half) of integer

I want to write a function to reverse one of two parts of number :
Input is: num = 1234567; part = 2
and output is: 1234765
So here is part that can be only 1 or 2
Now I know how to get part 1
int firstPartOfInt(int num) {
int ret = num;
digits = 1, halfDig = 10;
while (num > 9) {
ret = ret / 10;
digits++;
}
halfDigits = digits / 2;
for (int i = 1; i < halfDigits; i++) {
halfDigits *= 10;
}
ret = num;
while (num > halfDigits) {
ret = ret / 10;
}
return ret;
}
But I don't know how to get part 2 and reverse the number. If you post code here please do not use vector<> and other C++ feature not compatible with C
One way is to calculate the total number of digits in the number and then calculate a new number extracting digits from the original number in a certain order, complexity O(number-of-digits):
#include <stdio.h>
#include <stdlib.h>
unsigned reverse_decimal_half(unsigned n, unsigned half) {
unsigned char digits[sizeof(n) * 3];
unsigned digits10 = 0;
do digits[digits10++] = n % 10;
while(n /= 10);
unsigned result = 0;
switch(half) {
case 1:
for(unsigned digit = digits10 / 2; digit < digits10; ++digit)
result = result * 10 + digits[digit];
for(unsigned digit = digits10 / 2; digit--;)
result = result * 10 + digits[digit];
break;
case 2:
for(unsigned digit = digits10; digit-- > digits10 / 2;)
result = result * 10 + digits[digit];
for(unsigned digit = 0; digit < digits10 / 2; ++digit)
result = result * 10 + digits[digit];
break;
default:
abort();
}
return result;
}
int main() {
printf("%u %u %u\n", 0, 1, reverse_decimal_half(0, 1));
printf("%u %u %u\n", 12345678, 1, reverse_decimal_half(12345678, 1));
printf("%u %u %u\n", 12345678, 2, reverse_decimal_half(12345678, 2));
printf("%u %u %u\n", 123456789, 1, reverse_decimal_half(123456789, 1));
printf("%u %u %u\n", 123456789, 2, reverse_decimal_half(123456789, 2));
}
Outputs:
0 1 0
12345678 1 43215678
12345678 2 12348765
123456789 1 543216789
123456789 2 123459876
if understand this question well you need to reverse half of the decimal number. If the number has odd number of digits I assume that the first part is longer (for example 12345 - the first part is 123 the second 45). Because reverse is artihmetic the reverse the part 1 of 52001234 is 521234.
https://godbolt.org/z/frXvCM
(some numbers when reversed may wrap around - it is not checked)
int getndigits(unsigned number)
{
int ndigits = 0;
while(number)
{
ndigits++;
number /= 10;
}
return ndigits;
}
unsigned reverse(unsigned val, int ndigits)
{
unsigned left = 1, right = 1, result = 0;
while(--ndigits) left *= 10;
while(left)
{
result += (val / left) * right;
right *= 10;
val = val % left;
left /= 10;
}
return result;
}
unsigned reversehalf(unsigned val, int part)
{
int ndigits = getndigits(val);
unsigned parts[2], digits[2], left = 1;
if(ndigits < 3 || (ndigits == 3 && part == 2))
{
return val;
}
digits[0] = digits[1] = ndigits / 2;
if(digits[0] + digits[1] < ndigits) digits[0]++;
for(int dig = 0; dig < digits[1]; dig++) left *= 10;
parts[0] = val / left;
parts[1] = val % left;
parts[part - 1] = reverse(parts[part - 1], digits[part - 1]);
val = parts[0] * left + parts[1];
return val;
}
int main()
{
for(int number = 0; number < 40; number++)
{
unsigned num = rand();
printf("%u \tpart:%d\trev:%u\n", num,(number & 1) + 1,reversehalf(num, (number & 1) + 1));
}
}
My five cents.:)
#include <iostream>
int reverse_part_of_integer( int value, bool first_part = false )
{
const int Base = 10;
size_t n = 0;
int tmp = value;
do
{
++n;
} while ( tmp /= Base );
if ( first_part && n - n / 2 > 1 || !first_part && n / 2 > 1 )
{
n = n / 2;
int divider = 1;
while ( n-- ) divider *= Base;
int first_half = value / divider;
int second_half = value % divider;
int tmp = first_part ? first_half : second_half;
value = 0;
do
{
value = Base * value + tmp % Base;
} while ( tmp /= Base );
value = first_part ? value * divider + second_half
: first_half * divider +value;
}
return value;
}
int main()
{
int value = -123456789;
std::cout << "initial value: "
<< value << '\n';
std::cout << "First part reversed: "
<< reverse_part_of_integer( value, true ) << '\n';
std::cout << "Second part reversed: "
<< reverse_part_of_integer( value ) << '\n';
}
The program output is
initial value: -123456789
First part reversed: -543216789
Second part reversed: -123459876
Just for fun, a solution that counts only half the number of digits before reversing:
constexpr int base{10};
constexpr int partial_reverse(int number, int part)
{
// Split the number finding its "halfway"
int multiplier = base;
int abs_number = number < 0 ? -number : number;
int parts[2] = {0, abs_number};
while (parts[1] >= multiplier)
{
multiplier *= base;
parts[1] /= base;
}
multiplier /= base;
parts[0] = abs_number % multiplier;
// Now reverse only one of the two parts
int tmp = parts[part];
parts[part] = 0;
while (tmp)
{
parts[part] = parts[part] * base + tmp % base;
tmp /= base;
}
// Then rebuild the number
int reversed = parts[0] + multiplier * parts[1];
return number < 0 ? -reversed : reversed;
}
int main()
{
static_assert(partial_reverse(123, 0) == 123);
static_assert(partial_reverse(-123, 1) == -213);
static_assert(partial_reverse(1000, 0) == 1000);
static_assert(partial_reverse(1009, 1) == 109);
static_assert(partial_reverse(123456, 0) == 123654);
static_assert(partial_reverse(1234567, 0) == 1234765);
static_assert(partial_reverse(-1234567, 1) == -4321567);
}

Skipping values in a sequence of positive integers

I want to print the following number sequence:
1 2 3 6 7 8 11 12 13 16 17 18...
It prints three positive integers then skips two following values and then repeats the process.
Here's a simple way just using a for loop statement:
for (int i = 1; i < 100; i += ((i%5) == 3) ? 3 : 1)
{
// ...
}
As pointed out by Franck you can simply use the modulo operator.
The modulo operator gives you the rest of a division as a result.
0 / 10 = 0; 0 % 10 = 0;
10 / 10 = 1; 10 % 10 = 0;
11 / 10 = 1; 11 % 10 = 1;
12 / 10 = 1; 12 % 10 = 2;
20 / 10 = 2; 20 % 10 = 0;
21 / 10 = 2; 21 % 10 = 1;
27 / 10 = 2; 21 % 10 = 7;
0 % 3 = 0;
1 % 3 = 1;
2 % 3 = 2;
3 % 3 = 0;
4 % 3 = 1;
5 % 3 = 2;
6 % 3 = 0;
7 % 3 = 1;
8 % 3 = 2;
9 % 3 = 0;
...
From your example I assume that you want to skip values ending on 4 or 9.
You have 2 possibilities to archive this:
use % 10 and check the result for being either 4 or 9
use % 5 and check the result for being either 4
The result would look something like this:
for (int i=1; i<=100; i++)
{
if(i%5 == 4) continue; //Skip
std::cout << i << " ";
}

Partition function based on Euler's formula

I am trying to find the partitions of a number using the Euler's formula for that:
It produces results like:
P(3) = P(2) + P(1) = 3
P(4) = P(3) + P(2) = 3+ 2 = 5
P(5) = P(4) + P(3) - P(0) = 5 + 3 - 1 = 7
P(6) = P(5) + P(4) - P(1) = 7 + 5 - 1 = 11 and so on..
* P(0) = 1
It produces two positive and then two negative values and so on.
I am using recursion for that but the code goes into an infinite loop without producing any result.
long result = 0;
long counter = 0;
class Euler
{
public:
long Partition(long n)
{
int exponent = 0;
if (n < 0)
{
return 0;
}
else
{
counter = counter + 1;
exponent = pow(-1, counter - 1) ;
if (n == 0)
{
n = 1;
}
return Partition((exponent * (n - ( (counter * ( (3 * counter) - 1)) / 2)))) +
Partition(((exponent * (n - ( (counter * ( (3 * counter) + 1)) / 2)) )));
}
}
};
int main(int argc, char** argv)
{
long result= 0;
long a = 3;
Euler * obj = new Euler();
long s = obj->Partition(a);
std::cout << s;
return 0;
}
Your global counter is modified by the first call to Partition, so the second one operates on a different one; in fact, the counter changes more or less unpredictably.
Do not use globals.

C++ Faulty Random Numbers [duplicate]

This question already has answers here:
How unique is rand() in C?
(4 answers)
Closed 8 years ago.
I'm creating a machine that generates a shotgun with random components that effect the overall quality of the gun. I'm having a problem generating the random parts that will comprise the shotgun. There are 4 parts that have to be generated. When I created each of these functions, I tested them individually and they all work but when I try to put them together with the createChromo() function, the numbers are individually random. I should be getting results like 2131 and 1332, but I keep getting 1111 or 1112 or 2221 or 2222....Here is the code:
int generateButt()
{
srand(unsigned(time(NULL)));
int buttType = rand() % 3 + 1;
if(buttType == 1)
{
accuracy = rand() % ((5 - 2) + 2) / 10.0;
fireRate = fireRate - 0.3;
}
if(buttType == 2)
{
accuracy = rand() % ((8 + 5) + 5)/ 10.0;
fireRate = fireRate - 0.2;
}
if(buttType == 3)
{
accuracy = rand() % ((11 + 8) + 8) / 10.0;
fireRate = fireRate - 0.1;
}
return buttType;
}
int generateBarrel()
{
srand(unsigned(time(NULL)));
int barrelType = rand() % 3 + 1;
if(barrelType == 1)
{
range = rand() % (16 - 5) + 5;
power = power + 3;
}
if(barrelType == 2)
{
range = rand() % (21 - 16) + 16;
power = power + 1;
}
if(barrelType == 3)
{
range = rand() % (26 + 21) + 21;
power = power - 1;
}
return barrelType;
}
int generateBullet()
{
srand(unsigned(time(NULL)));
int bulletType = rand() % 3 + 1;
if(bulletType == 1)
{
power = rand() % (16 - 10) + 10;
range = range + 5;
}
if(bulletType == 2)
{
power = rand() % (26 - 16) + 16;
range = range + 1;
}
if(bulletType == 3)
{
power = rand() % (35 - 26) + 26;
range = range - 2;
}
return bulletType;
}
int generateAction()
{
srand(unsigned(time(NULL)));
int actionType = rand() % 2 + 1;
if(actionType == 1)
{
fireRate = 1.5;
accuracy = accuracy + 0.2;
}
if(actionType == 2)
{
fireRate = 2.0;
accuracy = accuracy - 0.1;
}
return actionType;
}
void createChromo(int a, int b, int c, int d)
{
cout <<a<<b<<c<<d<<"\n";
}
int main()
{
for(int i = 0; i < popSize; i++)
createChromo(generateButt(), generateBarrel(), generateBullet(), generateAction());
system("pause");
return 0;
}
You're calling srand each time you call either function. What srand does is seed the generator for a new string of random numbers. You base that seed off of the current second, so if it's called in the same second, the seed will be the same as last time, and thus the sequence of random numbers obtained from rand() will be as well.
Call srand(time(NULL)); once at the beginning of your program to just have one sequence, and keep using the next number in that one sequence instead of starting the same sequence over.
If you have access to C++11, you might consider using the <random> header as well.
the concept of random does not exist in the entire computation world
the function srand() is used to set a seed for the rand() function
if you set 2 different seed your generator of pseudo-random numbers will behave in 2 different ways