I am looking for any advice on how to turn a function into a class. I will enter a program below. It is long. I feel i should place the whole thing in for context. I need to rewrite it so that i will use classes in place of the three functions.
#include <iostream>
#include <string>
using namespace std;
// Do not change these function prototypes:
void readBig(int[]);
void printBig(int[]);
void addBig(int[], int[], int[]);
// This constant should be 100 when the program is finished.
const int MAX_DIGITS = 100;
int main()
{
// Declare the three numbers, the first, second and the sum:
int number1[MAX_DIGITS], number2[MAX_DIGITS], sum[MAX_DIGITS];
bool finished = false;
char response;
while (! finished)
{
cout << "Please enter a number up to " << MAX_DIGITS << " digits: ";
readBig(number1);
cout << "Please enter a number up to " << MAX_DIGITS << " digits: ";
readBig(number2);
addBig(number1, number2, sum);
printBig(number1);
cout << "\n+\n";
printBig(number2);
cout << "\n=\n";
printBig(sum);
cout << "\n";
cout << "test again?";
cin>>response;
cin.ignore(900,'\n');
finished = toupper(response)!= 'Y';
}
return 0;
}
//ReadBig will read a number as a string,
//It then converts each element of the string to an integer and stores it in an integer array.
//Finally, it reverses the elements of the array so that the ones digit is in element zero,
//the tens digit is in element 1, the hundreds digit is in element 2, etc.
//AddBig adds the corresponding digits of the first two arrays and stores the answer in the third.
//In a second loop, it performs the carry operation.
//PrintBig uses a while loop to skip leading zeros and then uses a for loop to print the number.
//FUNCTIONS GO BELOW
void readBig(int number[MAX_DIGITS])
{
string read="";
cin>>read;
int len,i, save=0;
len= read.length();
while(i<MAX_DIGITS){
number[i]=0;
i++;
}
for (i=0; i <= len-1; i++){
number[i] = int (read.at(i)-'0');
}
for (i=0;i<=len/2-1;i++){
save=number[i];
number[i]=number[len-1-i];
number[len-1-i]=save;
}
}
void printBig(int number[MAX_DIGITS])
{
int digit=MAX_DIGITS-1;
while(number[digit]==0){
digit--;
}
for (int i=digit; i>=0; i--)
{cout<<number[i];
}
}
void addBig(int number1[MAX_DIGITS], int number2[MAX_DIGITS], int sum[MAX_DIGITS])
{
// The code below sums the arrays.
for (int i = MAX_DIGITS - 1; i >= 0; i--)
{
sum[i] = number1[i] + number2[i];
if (sum[i] > 9 && i < MAX_DIGITS - 1)
{
sum[i + 1] += 1;
sum[i] -= 10;
}
}
}
I'm trying to learn pointers in C++, but seems that it get more complicated...
In the main loop
int i;
for (i = 0; i < 5; ++i){
if (fun == arrfun[i]) break;
}
How is that fun==arrfun[i] at fun2 if both fun and arrfun start looping form 0? Hence they should equal at log(x) instead. How could I loop to sin or cos, etc?
#include <iostream>
#include <cmath>
using namespace std;
typedef double(*FUNDtoD)(double);
typedef FUNDtoD ARRFUN[];
FUNDtoD funmax(ARRFUN, double);
double fun0(double x) { return log(x); }
double fun1(double x) { return x*x; }
double fun2(double x) { return exp(x); }
double fun3(double x) { return sin(x); }
double fun4(double x) { return cos(x); }
int main() {
ARRFUN arrfun = { fun0, fun1, fun2, fun3, fun4 };
FUNDtoD fun = funmax(arrfun, 1);
int i;
for (i = 0; i < 5; ++i){
if (fun == arrfun[i]) break;
}
cout.precision(14);
cout << "Largest value at x=1 assumed by function # "
<< i << ".\nThe value is " << fun(2) << endl;
return 0;
}
FUNDtoD funmax(ARRFUN f, double x){
double m = f[0](x), z;
int k = 0;
for (int i = 1; i < 5; i++){
if ((z = f[i](x)) > m) {
m = z;
k = i;
}
}
return f[k];
}
I don't understand how function FUNDtoD funmax is working at the bottom, could somebody clarify it please, many thanks.
How is that fun==arrfun[i] at fun2 if both fun and arrfun start looping form 0? > Hence they should equal at log(x) instead. How could I loop to sin or cos, etc?
fun is not being looped, the same pointer is checked against each function pointer stored in the array (arrfun). It is simply trying to find the index of the returned function pointer. If sin(x) gave the highest value then that loop would finish with a 4 in i.
don't understand how function FUNDtoD funmax is working at the bottom, could
somebody clarify it please, many thanks.
It breaks down as follows:
Firstly it performs m = f0;
f[0] -> fun0 so the result is m = log( x );
Next it steps through the other 4 functions and tests whether the operation on x results in a higher valuer than the previous. It then stores the index of the function that returned the highest value.
Finally it returns that function pointer.
I am building a windows phone app and i added a windows phone runtime component with this function in order to decode a string which i provide. The same function seems to be working correctly in a console application if i provide an std::string and return the same type. I think my problem is that i am converting from one type to another in the wrong way, but i can't see what i am doing wrong!
String^ Base64Encoding::base64_decode(String^ someString) {
std::wstring ws1(someString->Data());
std::string encoded_string(ws1.begin(), ws1.end());
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i == 4) {
for (i = 0; i <4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
std::wstring widestr = std::wstring(ret.begin(), ret.end());
const wchar_t* wcstring2 = widestr.c_str();
return ref new String(wcstring2);
}
So what am i doing wrong here?
Normally, the output of a Base64 decode isn't a string, it's a byte array. Base64 can encode arbitrary binary data, and depending on the string's encoding, not all byte arrays are valid strings.
To do a Base64 decode, use Convert::FromBase64String. If you want to interpret that byte array as a string, I suggest you use one of the Encoding classes, such as Encoding.Unicode, to do that conversion.
I'm trying to convert hex into bin. If i call bits(0x101) it prints 00011, which is obviously wrong. Im pretty sure its in the for loop. Any ideas??
int hextobin (int n){
char buffer[33];
if(n==0) {
putchar('0');
return 0;
}
char *cp = buffer + 32;
*cp = 0;
for(int i =0;i <=sizeof(n); i++){
--cp;
if(n & 1) *cp = '1';
else *cp = '0';
n >>= i;
}
printf(cp);
return 0;
}
Once you shift the last 1 bit out of n, it becomes a zero, and your loop aborts, even if there's bits left to deal with.
And do yourself a favor... indent your code properly. It's oh-so-much easier to read/debug when it's formatted properly.
I am looking for an optimal algorithm to find out remaining all possible permutation
of a give binary number.
For ex:
Binary number is : ........1. algorithm should return the remaining 2^7 remaining binary numbers, like 00000001,00000011, etc.
Thanks,
sathish
The example given is not a permutation!
A permutation is a reordering of the input.
So if the input is 00000001, 00100000 and 00000010 are permutations, but 00000011 is not.
If this is only for small numbers (probably up to 16 bits), then just iterate over all of them and ignore the mismatches:
int fixed = 0x01; // this is the fixed part
int mask = 0x01; // these are the bits of the fixed part which matter
for (int i=0; i<256; i++) {
if (i & mask == fixed) {
print i;
}
}
to find all you aren't going to do better than looping over all numbers e.g. if you want to loop over all 8 bit numbers
for (int i =0; i < (1<<8) ; ++i)
{
//do stuff with i
}
if you need to output in binary then look at the string formatting options you have in what ever language you are using.
e.g.
printf("%b",i); //not standard in C/C++
for calculation the base should be irrelavent in most languages.
I read your question as: "given some binary number with some bits always set, create the remaining possible binary numbers".
For example, given 1xx1: you want: 1001, 1011, 1101, 1111.
An O(N) algorithm is as follows.
Suppose the bits are defined in mask m. You also have a hash h.
To generate the numbers < n-1, in pseudocode:
counter = 0
for x in 0..n-1:
x' = x | ~m
if h[x'] is not set:
h[x'] = counter
counter += 1
The idea in the code is to walk through all numbers from 0 to n-1, and set the pre-defined bits to 1. Then memoize the resulting number (iff not already memoized) by mapping the resulting number to the value of a running counter.
The keys of h will be the permutations. As a bonus the h[p] will contain a unique index number for the permutation p, although you did not need it in your original question, it can be useful.
Why are you making it complicated !
It is as simple as the following:
// permutation of i on a length K
// Example : decimal i=10 is permuted over length k= 7
// [10]0001010-> [5] 0000101-> [66] 1000010 and 33, 80, 40, 20 etc.
main(){
int i=10,j,k=7; j=i;
do printf("%d \n", i= ( (i&1)<< k + i >>1); while (i!=j);
}
There are many permutation generating algorithms you can use, such as this one:
#include <stdio.h>
void print(const int *v, const int size)
{
if (v != 0) {
for (int i = 0; i < size; i++) {
printf("%4d", v[i] );
}
printf("\n");
}
} // print
void visit(int *Value, int N, int k)
{
static level = -1;
level = level+1; Value[k] = level;
if (level == N)
print(Value, N);
else
for (int i = 0; i < N; i++)
if (Value[i] == 0)
visit(Value, N, i);
level = level-1; Value[k] = 0;
}
main()
{
const int N = 4;
int Value[N];
for (int i = 0; i < N; i++) {
Value[i] = 0;
}
visit(Value, N, 0);
}
source: http://www.bearcave.com/random_hacks/permute.html
Make sure you adapt the relevant constants to your needs (binary number, 7 bits, etc...)
If you are really looking for permutations then the following code should do.
To find all possible permutations of a given binary string(pattern) for example.
The permutations of 1000 are 1000, 0100, 0010, 0001:
void permutation(int no_ones, int no_zeroes, string accum){
if(no_ones == 0){
for(int i=0;i<no_zeroes;i++){
accum += "0";
}
cout << accum << endl;
return;
}
else if(no_zeroes == 0){
for(int j=0;j<no_ones;j++){
accum += "1";
}
cout << accum << endl;
return;
}
permutation (no_ones - 1, no_zeroes, accum + "1");
permutation (no_ones , no_zeroes - 1, accum + "0");
}
int main(){
string append = "";
//finding permutation of 11000
permutation(2, 6, append); //the permutations are
//11000
//10100
//10010
//10001
//01100
//01010
cin.get();
}
If you intend to generate all the string combinations for n bits , then the problem can be solved using backtracking.
Here you go :
//Generating all string of n bits assuming A[0..n-1] is array of size n
public class Backtracking {
int[] A;
void Binary(int n){
if(n<1){
for(int i : A)
System.out.print(i);
System.out.println();
}else{
A[n-1] = 0;
Binary(n-1);
A[n-1] = 1;
Binary(n-1);
}
}
public static void main(String[] args) {
// n is number of bits
int n = 8;
Backtracking backtracking = new Backtracking();
backtracking.A = new int[n];
backtracking.Binary(n);
}
}