DEC to BIN using for and - c++

I have a problem with made a function in c++ that will give me back binary number.
function(unsigned short int user_input, int tab[16]) {
for(ii = 0; ??; ii++)
tab[ii] = i % 2;
i = i / 2;
}
User insert DEC number and get back BIN.
Should i just type ii < 16 ? It's working, but is it correct?

That'll work but is a bit wasteful (if you enter 1, you divide 0 by 2 15 times). Also division by 2 can be "sped up" by shifting. Here's an alternative:
function(unsigned short int user_input, int tab[16]) {
int idx = 0;
while(user_input > 0)
{
tab[idx] = user_input & 1;
user_input = user_input >> 1;
idx++;
}
for(; idx < 16; idx++)
{
tab[idx] = 0;
}
}

A somewhat more compact version:
void function(uint16_t x, int b[16]) {
for (int i = 0; i != 16; ++i, x >>= 1)
b[i] = x & 1;
}
Note that this puts the least significant bit in b[0].
To answer your question: Yes, ii < 16 is correct. This causes the loop to iterate 16 times, with ii going from 0 to 15 on each execution of the loop body, during which you check the last bit then shift.

Related

Converting an integer into it's binary equivalent

I have an assignment to make a program that should convert a number from it's integer value to a binary value. For some reason my array is always filled with zeroes and won't add "1"'s from my if statements. I know there are probably solutions to this assignment on internet but I would like to understand what is problem with my code. Any help is appreciated.
Here is what I tried:
#include <iostream>
/*Write a code that will enable input of one real number in order to write out it's binary equivalent.*/
int main() {
int number;
int binaryNumber[32] = { 0 };
std::cout << "Enter your number: ";
std::cin >> number;
while (number > 0) {
int i = 0;
if ((number / 10) % 2 == 0) {
binaryNumber[i] = 0;
}
if ((number / 10) % 2 != 0) {
binaryNumber[i] = 1;
}
number = number / 10;
i++;
}
for (int i = 31; i >= 0; i--) {
std::cout << binaryNumber[i];
}
return 0;
}
You need to remove number/10 in both the if statements. Instead, just use number. you need the last digit every time to get the ith bit.
Moreover, you need to just half the number in every iteration rather than doing it /10.
// Updated Code
int main() {
int number;
int binaryNumber[32] = { 0 };
std::cout << "Enter your number: ";
std::cin >> number;
int i = 0;
while (number > 0) {
if (number % 2 == 0) {
binaryNumber[i] = 0;
}
if (number % 2 != 0) {
binaryNumber[i] = 1;
}
number = number / 2;
i++;
}
for (int i = 31; i >= 0; i--) {
std::cout << binaryNumber[i];
}
return 0;
}
The first thing is the variable 'i' in the while loop. Consider it more precisely: every time you iterate over it, 'i' is recreated again and assigned the value of zero. It's the basics of the language itself.
The most relevant mistake is logic of your program. Each iteration we must take the remainder of division by 2, and then divide our number by 2.
The correct code is:
#include <iostream>
int main()
{
int x = 8;
bool repr[32]{};
int p = 0;
while(x)
{
repr[p] = x % 2;
++p;
x /= 2;
}
for(int i = 31; i >= 0; --i)
std::cout << repr[i];
return 0;
}
... is always filled with zeroes ... I would like to understand what is problem with my code
int i = 0; must be before the while, having it inside you only set the index 0 of the array in your loop because i always values 0.
But there are several other problems in your code :
using int binaryNumber[32] you suppose your int are on 32bits. Do not use 32 but sizeof(int)*CHAR_BIT, and the same for your last loop in case you want to also write 0 on the left of the first 1
you look at the value of (number / 10) % 2, you must look at the value of number % 2
it is useless to do the test then its reverse, just use else, or better remove the two ifs and just do binaryNumber[i] = number & 1;
number = number / 10; is the right way when you want to produce the value in decimal, in binary you have to divide by 2
in for (int i = 31; i >= 0; i--) { except for numbers needing 32 bits you will write useless 0 on the left, why not using the value of i from the while ?
There are some logical errors in your code.
You have taken (number/10) % 2, instead, you have to take (number %2 ) as you want the remainder.
Instead of taking i = 31, you should use this logic so you can print the following binary in reverse order:
for (int j = i - 1; j >= 0; j--)
{
cout << BinaryNumb[j];
}
Here is the code to convert an integer to its binary equivalent:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// function to convert integer to binary
void DecBinary(int n)
{
// Array to store binary number
int BinaryNumb[32];
int i = 0;
while (n > 0)
{
// Storing remainder in array
BinaryNumb[i] = n % 2;
n = n / 2;
i++;
}
// Printing array in reverse order
for (int j = i - 1; j >= 0; j--)
{
cout << BinaryNumb[j];
}
}
// Main Program
int main()
{
int testcase;
//Loop is optional
for(int i = 0; i < testcase; i++)
{
cin >> n;
DecToBinary(n);
}
return 0;
}

Why The Elements of 2 Identical arrays Equal each other

I should mention the purpose of this code is to tackle a leading zero scenario when finding date palindromes in dates in format MMDDYYY.
Here is the code.
#include <iostream>
using namespace std;
unsigned numDigits (unsigned num)//this works
{
if (num < 10) return 1;
return 1+ numDigits(num/10);
}
int main ()
{
unsigned date = 1111110;//01/11/1110(jan 11th of 1110 is palindrome)
cout<<numDigits(date)<<"num of dig"<<endl;
if (numDigits(date) == 7)
{
unsigned array[8];
unsigned number = date;
unsigned revArr[8];
for (int h = 7; h >= 0; h--) //this pops array withdate
{
array[h] = number % 10;
number /= 10;
cout<<array[h]<<endl;
}
cout<<"vs"<<endl;
for (int i = 0; i < 8; i++) //this pops revarray withdate
{
revArr[i] = number % 10;
number /= 10;
cout<<array[i]<<endl;
}
for (int j = 0; j < 8; j++)
{
if (array[j] == revArr[j])
{
cout<<j<<"th digit are" <<" equal"<<endl;
}
}
}
return 0;
}
In this case both of the arrays are identical, I don't underdtdanwd why array[0] == revArr[0] but array[1] != revArr[1] and so on but array[7] == revArr[7] again... its boggling my mind.
The loops traverse all elements of the array. Even when the expression number /= 10 is equal to 0. In this case the zero is stored in the array elements because 0 / 10 gives again 0.
Before the second loop write
number = date;

Find Maximum Strength given number of elements to be skipped on left and right.Please Tell me why my code gives wrong output for certain test cases?

Given an array "s" of "n" items, you have for each item an left value "L[i]" and right value "R[i]" and its strength "S[i]",if you pick an element you can not pick L[i] elements on immediate left of it and R[i] on immediate right of it, find the maximum strength possible.
Example input:
5 //n
1 3 7 3 7 //strength
0 0 2 2 2 //Left Value
3 0 1 0 0 //Right Value
Output:
10
Code:
#include < bits / stdc++.h >
using namespace std;
unsigned long int getMax(int n, int * s, int * l, int * r) {
unsigned long int dyn[n + 1] = {};
dyn[1] = s[1];
for (int i = 2; i <= n; i++) {
dyn[i] = dyn[i - 1];
unsigned long int onInc = s[i];
int left = i - l[i] - 1;
if (left >= 1) {
unsigned int k = left;
while ((k > 0) && ((r[k] + k) >= i)) {
k--;
}
if (k != 0) {
if ((dyn[k] + s[i]) > dyn[i]) {
onInc = dyn[k] + s[i];
}
}
}
dyn[i] = (dyn[i] > onInc) ? dyn[i] : onInc;
}
return dyn[n];
}
int main() {
int n;
cin >> n;
int s[n + 1] = {}, l[n + 1] = {}, r[n + 1] = {};
for (int i = 1; i <= n; i++) {
cin >> s[i];
}
for (int i = 1; i <= n; i++) {
cin >> l[i];
}
for (int i = 1; i <= n; i++) {
cin >> r[i];
}
cout << getMax(n, s, l, r) << endl;
return 0;
}
Problem in your approach:
In your DP table, the information you are storing is about maximum possible so far. The information regarding whether the ith index has been considered is lost. You can consider taking strength at current index to extend previous indices only if any of the previously seen indices is either not in range or it is in range and has not been considered.
Solution:
Reconfigure your DP recurrence. Let DP[i] denote the maximum answer if ith index was considered. Now you will only need to extend those that satisfy range condition. The answer would be maximum value of all DP indices.
Code:
vector<long> DP(n,0);
DP[0]=strength[0]; // base condition
for(int i = 1; i < n ; i++){
DP[i] = strength[i];
for(int j = 0; j < i ; j++){
if(j >= (i-l[i]) || i <= (j+r[j])){ // can't extend
}
else{
DP[i]=max(DP[i],strength[i]+DP[j]); // extend to maximize result
}
}
}
long ans=*max_element(DP.begin(),DP.end());
Time Complexity: O(n^2)
Possible Optimizations:
There are better ways to calculate maximum values which you might want to look into. You can start by looking into Segment tree and Binary Indexed Trees.

all possible combinations bits

I am working on a program in C++ to demonstrate the workings of coding theory (in the sense of error correction using linear codes). I am adding parity bits to a string of bits ('words'). This is so I can still see what the message used to be if some bits have changed during transmission (Error detection and correction). One important thing to know is the minimum distance between two words. To calculate this I need to compile a list of all possible words and compare them to each other. If my error correction code consists of words of length n=6, there would be 2^6 = 64 possible combinations. My question is about how I can generate all these possible words and store them in an array.
These are two instances of what these words would look like:
0 0 0 0 0 0
1 0 0 0 0 0
1 1 0 1 0 1
I know I can generate combinations of two numbers with an algorithm like this:
for (int i = 1; i <= 5; i++)
for (int j = 2; j <= 5; j++)
if (i != j)
cout << i << "," << j << "," << endl;
However, this code only generates combinations of two numbers and also uses numbers other than 1 or 0.
EDIT
I have created a few for loops that do the job. It is not especially elegant:
int bits[64][6] = { 0 };
for (int x = 0; x < 32; x++)
bits[x][0] = 1;
for (int x = 0; x < 64; x += 2)
bits[x][1] = 1;
for (int x = 0; x < 64; x += 4)
{
bits[x][2] = 1;
bits[x + 1][2] = 1;
}
for (int x = 0; x < 64; x += 8)
{
bits[x][3] = 1;
bits[x + 1][3] = 1;
bits[x + 2][3] = 1;
bits[x + 3][3] = 1;
}
for (int x = 0; x < 64; x += 16)
{
for (int i = 0; i < 8; i++)
bits[x + i][4] = 1;
}
for (int x = 0; x < 64; x += 32)
{
for (int i = 0; i < 16; i++)
bits[x + i][5] = 1;
}
You may use the following: http://ideone.com/C8O8Qe
template <std::size_t N>
bool increase(std::bitset<N>& bs)
{
for (std::size_t i = 0; i != bs.size(); ++i) {
if (bs.flip(i).test(i) == true) {
return true;
}
}
return false; // overflow
}
And then to iterate on all values :
std::bitset<5> bs;
do {
std::cout << bs << std::endl;
} while (increase(bs));
If size is not a compile time value, you may use similar code with std::vector<bool>
I'd use iota or similar:
vector<int> foo(64); // Create a vector to hold 64 entries
iota(foo.begin(), foo.end(), 0); // Inserts the range of numbers in foo [0,foo.size())
for(auto& i : foo){
cout << bitset<6>(i) << endl;
}
I should probably also point out that an int is a sizeof(int) collection of bits, so hopefully you can work with that using bit-wise operators.
If you must use a more literal collection of bits, I would second Jarod42's answer, but still use iota:
vector<bitset<6>> bar(64);
iota(bar.begin(), bar.end(), 0);
for(auto& i : bar){
cout << i << endl;
}
Use a double loop from 0 to 62 and from the first loop index to 63.
Inside the loops convert the two indexes to binary. (A simple way is to convert to hexadecimal and expand the hex digits into four bits.)

How to efficiently manuplate very long vector?

I have a very long vector as below in Eigen:
MatrixXi iIndex(1000000);
which is initialized into zeros, with only a short continuous part(less than 100) filled with 1 's, the position of which is randomized.
I need to do the following things in a long loop:
int count;
int position;
for(int i=0;i<99999;i++){
//... randomly fill iIndex will short `1` s
// e.g. index = (someVectorXi.array() == i).cast<int>();
count = iIndex.sum(); // count all the nonzero elements
//position the first nonzero element index:
for (int j=0; j<1000000;j++){
if(iIndex(j))
position = j;
}
}
But it is really very slow.
Is there any way to expedite?
my 2 cents: group the bits in e.g. uint32_t, so you can check whether an i32 differs from 0. When it is different, then you may take longer to find out which bits are 1.
Assuming the number of bits is a multitude of 32 (making it easier):
for (int i = 0; i < max / sizeof(uint32_t); ++i)
{
if (wordGrp[i] != 0)
{
uint32_t grp = wordGrp[i];
for (j = 0; j < BITS_PER_UINT32; j++)
{
if ((grp & 1) == 1) std::cout << "idx " << (i*32 + j) << " is 1\n";
grp >>= 1;
}
}
}