function pointers returned by functions - function

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.

Related

What is wrong with my code? prime factors

int main ()
{
int num, i=num, isPrime;
printf("Enter an integer: ");
scanf("%d", &num);
while (i>=2)
{
if (num%i!=0)
i--;
if (num%i==0) //check if it is a factor
{
isPrime = 1;
for (int j=2; j<=i; j++)
{
if (i%j==0)
{
isPrime = 0;
break;
}
}
if (isPrime==1)
{
printf("%d ", i);
num = num/i;
}
}
}
return 0;
}
May I know why is my code not working?
I was trying to write a C code which print all prime factors of a given number from the biggest factor to the smallest and when I run it just show nothing after I input a number.
#include of required header stdio.h to use printf() and scanf() is missing.
num is assigned to i before a value is read to num. This is assigning an indeterminate value to i and using the value invokes undefined behavior.
Looping j until it becomes i is wrong because i%i will always become zero unless i is zero.
You should decrement i also when num%i==0 and i is not prime. Otherwise, the update of i will stop there and the loop may go infinitely.
The two if statements if (num%i!=0) and if (num%i==0) may see different values of i. This happens when num%i!=0 at the beginning of the iteration because i is updated when the condition is true. You should use else instead of the second if statement.
Fixed code:
#include <stdio.h>
int main (void)
{
int num, i, isPrime;
printf("Please enter an integer: ");
if (scanf("%d", &num) != 1)
{
fputs("read error\n", stderr);
return 1;
}
i=num;
while (i>=2)
{
if (num%i!=0) //check if it is a factor
{
i--;
}
else
{
isPrime = 1;
for (int j=2; j<i; j++)
{
if (i%j==0)
{
isPrime = 0;
break;
}
}
if (isPrime==1)
{
printf("%d ", i);
num = num/i;
}
else
{
i--;
}
}
}
return 0;
}
At least one bug here:
int num, i=num, isPrime;
It seems you are trying to make i equal to num. But here `num isn't even initialized yet. You have to do the assignment after reading user input:
int num, i, isPrime;
printf("Please enter an integer: ");
scanf("%d", &num);
i=num;
Also the check for primes is wrong:
for (int j=2; j<=i; j++)
{
if (i%j==0)
{
isPrime = 0;
break;
}
}
Since you use j<=i then j will eventually be equal to i and i%j==0 will be true so you don't find any primes. Try j<i instead.

using a function to compare integers and find the position where one value is even and the other is odd c++

/*
Description:
Write a function called digitsOpposite. The function has two integer parameters x and y that are
positive and have the same number of digits. It returns the number of positions where one number
has an even digit and the other has an odd one. For example, if the function was applied to 17345
and 97813 it would return 2 because the third digits are 3 and 8 and the fourth ones are 4 and 1.
(In both cases one of these is even and the other is odd.)
Problem: my code is not printing the desired output. HELP PLEASE!! I am a beginner. Thanks.
*/
#include <iostream>
using namespace std;
// declare function
int digitsOpposite(int x, int y){
int lastV1, lastV2, leftV1, leftV2;
leftV1 = 0,
leftV2 = 0;
lastV1 = 0;
lastV2 = 0;
for(int i = 5; i > 0; i--){
leftV1 += x; // 17345
leftV2 += y; // 97813
lastV1 += leftV1 % 2; //5
lastV2 += leftV2 % 2; //3
if((lastV1 == 0)&&( lastV2 != 0))
{
break;
return i;
}
else{
leftV1 += leftV1 / 10; // 1734
leftV2 += leftV2 / 10; // 9781
}
}
}
int main(){
cout <<"The position of the number is: " << digitsOpposite(17345, 97813);
return 0;
}

What is the best way to make these function into a class? Or multiple classes?

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;
}
}
}

Finding minimum distance between n points in cuda

I am trying to find the minimum distance between n points in cuda. I wrote the below code. This is working fine for number of points from 1 to 1024 i.e., 1 block. But if num_points is greater than 1024 i am getting wrong value for minimum distance. I am checking the gpu min value with the value I found in CPU using brute force algorithm.
The min value is stored in the temp1[0] at the end of kernel function.
I don't know what is wrong in this. Please help me out..
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/time.h>
#define MAX_POINTS 50000
__global__ void minimum_distance(float * X, float * Y, float * D, int n) {
__shared__ float temp[1024];
float temp1[1024];
int tid = threadIdx.x;
int bid = blockIdx.x;
int ref = tid+bid*blockDim.x;
temp[ref] = 1E+37F;
temp1[bid] = 1E+37F;
float dx,dy;
float Dij;
int i;
//each thread will take a point and find min dist to all
// points greater than its unique id(ref)
for (i = ref + 1; i < n; i++)
{
dx = X[ref]-X[i];
dy = Y[ref]-Y[i];
Dij = sqrtf(dx*dx+dy*dy);
if (temp[tid] > Dij)
{
temp[tid] = Dij;
}
}
__syncthreads();
//In each block the min value is stored in temp[0]
if(tid == 0)
{
if( bid == (n-1)/1024 ) {
int end = n - (bid) * 1024;
for (i = 1; i < end; i++ )
{
if (temp[i] < temp[tid])
temp[tid] = temp[i];
}
temp1[bid] = temp[tid];
}
else {
for (i = 1; i < 1024; i++ )
{
if (temp[i] < temp[tid])
temp[tid] = temp[i];
}
temp1[bid] = temp[tid];
}
}
__syncthreads();
//Here the min value is stored in temp1[0]
if (ref == 0)
{
for (i = 1; i <= (n-1)/1024; i++)
if( temp1[bid] > temp1[i])
temp1[bid] = temp1[i];
*D=temp1[bid];
}
}
//part of Main function
//kernel function invocation
// Invoking kernel of 1D grid and block sizes
// Vx and Vy are arrays of x-coordinates and y-coordinates respectively
int main(int argc, char* argv[]) {
.
.
blocks = (num_points-1)/1024 + 1;
minimum_distance<<<blocks,1024>>>(Vx,Vy,dmin_dist,num_points);
.
.
I'd say what's wrong is your choice of algorithm. You can certainly do better than O(n^2) - even if yours is pretty straightforward. Sure, on 5,000 points it might not seem terrible, but try 50,000 points and you'll feel the pain...
I'd think about parallelizing the construction of a Voronoi Diagram, or maybe some kind of BSP-like structure which might be easier to query with less code divergence.

Best algorithm to find all possible permutation of given binary bits

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);
}
}