C++ Arrays & pointers [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
can anyone help me with the following inequalities for arrays:
#include <stdio.h>
#define PRD(a) printf("%d", (a))
#define NL printf("\n")
int a[] = {0,1,2,3,4};
int main ()
{
int i;
int*p;
for (i=0; i<=4; i++)
PRD(a[i]);
NL;
for (p=&a[0]; p<=&a[4]; p++)
PRD(*p);
NL;
for (p=&a[0]; i=0; p+i<=a+4; i++)
PRD(p[i]);
NL;
for (p=a, i=0; p+i<=a+4; p++, i++)
PRD(*(p+i));
NL;
Basically I dont understand the 4 loops, please kindly help to explain to me!

A detail here, the "inequalities" you're asking about are about pointers, not arrays. Think of comparing memory locations, and the following will be easier to follow.
First one should be pretty straightforward: print each element of the array in order (a[0], a[1], etc.)
In number 2, p is the address of element 0 of a. p++ increases that address to be address of the next element in the array.The termination condition can be read as "p is less or equal the address of element number 4 of the array". To put some values and make this concrete: imagine &a[0] is 200, as a consequence &a[4] is 216, as p is incremented it becomes 204, 208, 212, 216, and finally 220.
When it becomes 220 the condition becomes false, and the loop ends.
Number 3's left side is similar but instead of increasing p it adds i to p. Note that thanks to the magic of pointer arithmetic p + 1 is actually p + i*(sizeof(*p)). The sequence is exactly the same as in case 2. BTW, initialization should be p = &a[0], i=0; (note the comma before the i). For the right side (a+4), the plain a means the address of the first element of a (this is the C equivalency between pointers and arrays, a topic full of subtleties and pain). a + 4 is thus equivalent to &a[4].
Number 4 is there to mess with your head. The information above should be enough to translate the initialization and condition; but having both i++ and p++ means you will be advancing 2 elements each iteration.
The use of the preprocessor here is likely obscuring what gets called, try expanding manually to follow up more easily. and PRD should be adding a space after each number for easier reading.

Related

How to find the power of the array elements? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I need to check if A[0] ^ A[1] ^ A[2] ... ^ A[N] is even or odd.
Is this code right??
#include <bits/stdc++.h>
#include <cmath>
using namespace std;
int main(){
long long n;
cin >> n;
int a[n];
long int mp;
for(int i = 0; i < n; i++){
cin >> a[i];
mp = pow(a[i], a[i+1]);
}
if (mp % 2 == 0){
cout << "YES";
}
else cout<<"NO";
}
Do the maths first.
Consider that
odd * odd * odd * odd .... * odd == odd
You can multiply any odd factors and the result is always odd. Whether a number is odd or even is equivalent to: It has a prime factor 2. Some integer raised to some other integer cannot remove a prime factor, it can also not add a prime factor when it wasn't present before. You start with some x and then
x * x * x * x * x .... * x = y
has the same prime factors as x, just with different powers. The only exceptions is to get an odd number from an even one when you raise a number to power 0, because x^0 = 1.
Ergo, you are on the wrong track. Instead of brute force raising numbers to some power you merely need to consider ...
is A[0] odd or even
is any of the other elements 0 (remember that (a^b)^c) is just a^(b*c))
Thats it.
I will not write the code for you to not spoil the exercise. But I should tell you whats wrong with your code: pow is not made to be used with integers. There are many Q&As here about pow returning a "wrong" result, which is most often just due to wrong expectations. Here is one of them: Why does pow(n,2) return 24 when n=5, with my compiler and OS?. Moreover, you are accessing the array out of bounds in the last iteration of the loop. Hence all your code has undefined behavior. Output could be "maybe" or something else entirely. Also, your code merely calculates a[i] ^ a[i+1] and after the loop you only consider the very last result. Thats not what the task you describe asks for. Last but not least, Why aren't variable-length arrays part of the C++ standard?. Use std::vector for dynamically sized arrays.

How to check if two n-sized vectors are linearly dependant on C++? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
A program should be made which finds if the two vectors a = (a0, a1, ..., an-1) and b = (b0, b1, ..., bn-1) (1 ≤ n ≤ 20) are linearly dependant. The input should be n, and the coordinates of the two vectors and the output should be 1 if the vectors are linearly dependant, else - 0.
I've been struggling for hours over this now and I've got absolutely nothing. I know only basic C++ stuff and my geometry sucks way too much. I'd be really thankful if someone would write me a solution or at least give me some hint. Thanks in advance !
#include <iostream>
using namespace std;
int main()
{
int n;
double a[20], b[20];
cin >> n;
int counter = n;
bool flag = false;
for (int i = 0; i < n; i++)
{
cin >> a[i];
cin >> b[i];
}
double k;
for (int i = 0; i < n; i++)
{
for (k = 0; k < 1000; k = k + 0.01)
{
if (a[i] == b[i])
{
counter--;
}
}
}
if (counter == 0 && k != 0)
flag = true;
cout << flag;
return 0;
}
Apparently that was all I could possibly come up with. The "for" cycle is wrong on so many levels but I don't know how to fix it. I'm open to suggestions.
There are 4 parts to the problem:
1. Math and algorithms
Vectors a and b are linearly depndent if ∃k. a = k b. That is expanded to ∃k. ∑i=1..n ai = k ai and that is a set of equations any of which can be solved for k.
So you calculate k as b0 / a0 and check that the same k works for the other dimensions.
Don't forget to handle a0 = 0 (or small, see below). I'd probably swap the vectors so the larger absolute value is denominator.
2. Limited precision numeric calculations
Since the precision is limited, calculations involve rounding error. You need to check for approximate equality, not exact, because most likely you won't get exact results even when you expect them.
Approximate equality comes in two forms, absolute (|x - y| < ε) and relative (1 - ε < |x / y| < 1 + ε). Obviously the relative makes more sense here (you want to ignore the last significant digit only), but again you have to handle the case where the values are too small.
3. C++
Don't use plain arrays, use std::vector. That way you won't have arbitrary limits.
Iterate with iterator, not indices. Iterators work for all container types, indices only work for the few with continuous integral indices and random access. Which is basically just vector and plain array. And note that iterators are designed so that pointer is iterator, so you can iterate with iterator over plain arrays too.
4. Plain old bugs
You have the loop over k, but you don't use the value inside the loop.
The logic with counter does not seem to make any sense. I don't even see what you wanted to achieve with that.
You're right, that code bears no reationship to the problem at all.
It's easier than you think (at least conceptually). Divide each element in the vector by the corressponding element in the other vector. If all those division result in the same number then the vectors are linearly dependendent. So { 1, 2, 4 } and { 3, 6, 12 } are linear because 1/3 == 2/6 == 4/12.
However there are two technical problems. First you have to consider what happens when your elements are zero, you don't want to divide by zero.
Secondly because you are dealing with floating point numbers it's not sufficient to test if two numbers are equal. Because of rounding errors they often won't be. So you have to come up with some test to see if two numbers are nearly equal.
I'll leave you to think about both those problems.

Can someone explain this line of c++? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
cout << results[rand()%(sizeof(results)/sizeof(results[0]))] << endl;
results is an array of integers: 1,2,3,4,5.
Can somebody Explain?
This will print the value of your arrayentry in a random order.
It creates a random value and limits it to the index of the arraysize by using the modulo operator %.
rand() create a random integer value in the range of 0 to RAND_MAX
sizeof(results)/sizeof(results[0]) is the size of your array as you defined it earlier in your code i.e. int results[5]
The modulo operator % combines those tww values and makes sure that the result is not bigger then the size of your array (0-4).
Looks like my previous answer was a bit terse...
cout << results[rand()%(sizeof(results)/sizeof(results[0]))] << endl;
could be broken down to
int num_elems = sizeof(results)/sizeof(results[0]);
int randomIndex = rand() % num_elems;
int randomValue = results[randomIndex];
cout << randomValue << endl;
In slightly more detail:
sizeof(results)/sizeof(results[0]) calculates the number of elements in the array results. (Note that this only works when you have access to the array definition - you can't use this with a pointer to an array.)
rand() % num_elems calculates a random number in the range [0..num_elems-1]; this is the range of the results array.
results[randomIndex] returns a single, randomly selected, element from results
rand() returns a random number.
You want a random number from the array that is of size 5. So you use the modulo operator to be sure that you're not exceeding 4 (0,1,2,3 or 4).
sizeof(results) returns the total size in bytes of the array. sizeof(results[0]) is the size of an element in that array. For example, if sizeof(results[0]) is 8, then sizeof(results) is 40, so the result will be 40/8 which is 5, which is the array's size.

Backtrack in any programming language [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I was given a task of writing a program for string permutation. I understand the logic, but not the exact meaning of the Backtrack in this program. Please explain the for-loop functionality, when swap will be called, when permutate() will be called, and the exact meaning of backtrack.
# include <stdio.h>
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else
{
for (j = i; j <= n; j++)
{
swap((a+i), (a+j));
permute(a, i+1, n);
swap((a+i), (a+j)); //backtrack
}
}
}
int main()
{
char a[] = "ABC";
permute(a, 0, 2);
getchar();
return 0;
}
Sketching the call stack can help you understanding how the algorithm works. The example string "ABC" is a good starting point. Basically, this is what will happen with ABC:
permute(ABC, 0, 2)
i = 0
j = 0
permute(ABC, 1, 2)
i = 1
j = 1
permute(ABC, 2, 2)
print "ABC"
j = 2
string = ACB
permute(ACB, 2, 2)
print "ACB"
string = ABC
j = 1
string = BAC
permute(BAC, 1, 2)
.... (everything starts over)
As usual, in the example above, indentation defines what happens inside each of the recursive calls.
The reasoning behind the for loop is that every permutation of string ABC is given by ABC, BAC and CBA, plus every permutation of the substrings BC, AC and BA (remove the first letter from each of the previous ones). For any string S, the possible permutations are obtained by swapping every position with the first one, plus all of the permutations of each of these strings. Think of it like this: any permuted string must start with one of the letters in the original string, so you place every possible letter in the first position, and recursively apply the same method to the rest of the string (without the first letter).
That's what the loop is doing: we scan the string from the current starting point (which is i) up to the end, and at each step we swap that position with the starting point, recursively call permute() to print every permutation of this new string, and after that we restore the string back to its previous state, so that we have the original string to repeat the same process with the next position.
Personally, I don't like that comment saying "backtrack". A better term would be "winding back", because at that point the recursion winds back and you prepare your string for the next recursive call. Backtrack is normally used for a situation in which you explored a subtree and you didn't find a solution, so you go back up (backtrack) and try a different branch. Taken from wikipedia:
Backtracking is a general algorithm for finding all (or some)
solutions to some computational problem, that incrementally builds
candidates to the solutions, and abandons each partial candidate c
("backtracks") as soon as it determines that c cannot possibly be
completed to a valid solution.
Note that this algorithm does not generate the set of permutations, because it can print the same string more than once when there are repeated letters. An extreme case is when you apply it to the string "aaaaa", or any other string with one unique letter.
"Backtracking" means, you are gong back one step in your solution space (think of it as a decision tree and you are going up one level). It is usually used if you can rule out certain sub-trees in the decision space, and gives significant performance boost compared to full exploration of the decision tree if and only if it is very likely that you can rule out larger parts of the solution space.
You can find an exhaustive expalnation of a similar algorithm here: Using recursion and backtracking to generate all possible combinations

Finding the middle of an array without knowing the length

Find the middle of the string or array with an unknown length. You may
not traverse the list to find the length. You may not use anything to
help you find the length - as it is "unknown." (ie. no sizeof (C) or count(C#) etc...)
I had this question as an interview question. I'm just wondering what the answer is. I did ask if i could use sizeof, he said "no, the size of the string or array is unknown - you just need to get to the middle."
BTW, i'm not sure if this is actually possible to solve with no traversing. I almost felt as though he may have wanted to see how confident i am in my answer :S not sure...
His English was bad - also not sure if this contributed to misunderstandings. He directly told me that i do not need to traverse the list to get to the middle :S :S I'm assuming he meant no traversing at all..... :S
Have two counters, c1 and c2. Begin traversing the list, incrementing c1 every time and c2 every other time. By the time c1 gets to the end, c2 will be in the middle.
You haven't "traversed the list to find the length" and then divided it by two, you've just gone through once.
The only other way I can think of would be to keep taking off the first and last item of the list until you are left with the one(s) in the middle.
You (or your interviewer) are very vague in what the data is (you mentioned "string" and "array"); there's no assumption that can be made, so it can be anything.
You mentioned that the length of the string is unknown, but from your wording it might seem like you (or the interviewer) actually meant to say unknowable.
a) If it's just unknown, then the question is, how can it can be determined? In the case of strings, for example, you can consider the end to be '\0'. You can then apply some algorithms like the ones suggested by the other answers.
b) If it's unknowable, the riddle has no solution. The concept of middle has no meaning without a beginning and an end.
Bottom line, you cannot talk about a middle without a beginning and an end, or a length. Either this question was intentionally unanswerable, or you did not understand it properly. You must know more than just the beginning of the memory segment and maybe its type.
The following code will find the middle of an array WITHOUT traversing the list
int thearray[80];
int start = (int)&thearray;
int end = (int)(&thearray+1);
int half = ((end-start) / 4)/ 2;
std::cout << half << std::endl;
EDITS:
This code assumes you are dealing with an actual array and not a pointer to the first element of one, thus code like:
int *pointer_to_first_element = (int *)malloc(someamount);
will not work, likewise with any other notation that degrades the array reference into a pointer to the first element. Basically any notation using the *.
You would just use the difference between the addresses of the first and last elements.
I think this problem is aimed to also test your skills in problem analysis and requirements gathering. As others have stated before, we will need at least another piece of data to solve this issue.
My approach is to let clear to the interviewer that we can solve the problem with one constraint in the function call: the caller must provide 2 pointer, one to the beginning and another to the end of the array. Given those 2 pointers, and using basic pointer arithmetic, I reach this solution; please let me know what you think about it.
int *findMiddleArray( int const *first, int const *last )
{
if( first == NULL || last == NULL || first > last )
{
return NULL;
}
if( first == last )
{
return (int *)first;
}
size_t dataSize= ( size_t )( first + 1 ) - ( size_t )first,
addFirst= ( size_t )first,
addLast= ( size_t )last,
arrayLen= ( addLast - addFirst) / dataSize + 1,
arrayMiddle= arrayLen % 2 > 0 ? arrayLen / 2 + 1 : arrayLen / 2;
return ( int * )( ( arrayMiddle - 1 ) * dataSize + addFirst );
}
one way you can find midpoint of array is (for odd length array)
just use two loops ,1st loop start traverse from 0 index and the other (nested) loop will traverse from last index of array. Now just compare elements when it comes same ...that will be the mid point of array. i.e if(arr[i]== arr[j]) . Hope you got the point !
For Even length array ..you can do if(arr[i] == arr[j-1]) Or if(arr[i] == arr[j+1]) as they will never be same .try it by dry run!