Difference between arr and &arr if arr is an array of ints - c++11

I am just starting out with C++ and I have a question. If arr is an array or 10 ints, then arr is a pointer to the first element in the array. But what is meant by &arr? SO what is the difference bwteen a pointer to an array and a reference to an array?

then arr is a pointer to the first element in the array
No!
Arrays and pointers are two different types in C++ that have enough similarities between them to create confusion if they are not understood properly. The fact that pointers are one of the most difficult concepts for beginners to grasp doesn't help either.
So I fell a quick crash course is needed.
Crash course
Arrays, easy
int a[3] = {2, 3, 4};
This creates an array named a that contains 3 elements.
Arrays have defined the array subscript operator:
a[i]
evaluates to the i'th element of the array.
Pointers, easy
int val = 24;
int* p = &val;
p is a pointer pointing to the address of the object val.
Pointers have the indirection (dereference) operator defined:
*p
evaluates to the value of the object pointed by p.
Pointers, acting like arrays
Pointers give you the address of an object in memory. It can be a "standalone object" like in the example above, or it can be an object that is part of an array. Neither the pointer type nor the pointer value can tell you which one it is. Just the programmer. That's why
Pointers also have the array subscript operator defined:
p[i]
evaluates to the ith element to the "right" of the object pointed by p. This assumes that the object pointer by p is part of an array (except in p[0] where it doesn't need to be part of an array).
Note that p[0] is equivalent to (the exact same as) *p.
Arrays, acting like pointers
In most contexts array names decay to a pointer to the first element in the array. That is why many beginners think that arrays and pointers are the same thing. In fact they are not. They are different types.
Back to your question
what is meant by &arr
As said above, arr is not a pointer. So &arr means pointer to array. This is different from pointer to the first element of the array (&arr[0]).
SO what is the difference between a pointer to an array and a reference to an array?
Well, first of all please read What are the differences between a pointer variable and a reference variable in C++?. Second of all... well that's pretty much it.
the bulk of this answer is copied from this other answer of mine

There are 3 different concepts that you need to think about:
Pointer : the pointer is a variable that is used for storing the address of another variable.
Array: An array is a collection of variables of a similar data type
Reference : A reference variable is an alias, that is, another name for an already existing variable.
Here is a summary of how you can connect these three variables together:
arr == &arr[0]
and
*arr == arr[0]

For example
int arr[5] = {0,1,2,3,4};
arr is a pointer to pointer to the first element of array. While &arr a pointer to whole array of 5 int.
The value of arr and &arr are the same, but arr + 1 and &arr + 1 is different.
#include <iostream>
using namespace std;
int main()
{
int array[5];
cout << "array = " << array << " : &array = " << &array << endl;
cout << "array + 1 = " << array + 1 << " : &array + 1 = " << &array + 1;
return 0;
}
Result
array = 0x7fffebce1b80 : &array = 0x7fffebce1b80
array + 1 = 0x7fffebce1b84 : &array + 1 = 0x7fffebce1b94

Related

What do these 2 lines of code actually do?

I don’t know Ruby but I need to understand how the input value is manipulated in the lines below.
I think that the input is converted to the sum of the values of its characters but the second line is confusing; does it take the final value of the sum and perform the bitwise operations or per iteration? Could you provide a simple explanation of the steps followed?
Thank you in advance!
input.to_s.each_char.inject(0) do |sum, ch|
(sum << 8) ^ (ch.ord) ^ (sum >> 4)
inject is the same as reduce, and is similar to reduce in many other languages.
There are a number of different ways to call it but the way shown in the question is this:
inject(initial) { |memo, obj| block } → obj
If you specify a block, then for each element in enum the block is
passed an accumulator value (memo) and the element. If you specify a
symbol instead, then each element in the collection will be passed to
the named method of memo. In either case, the result becomes the new
value for memo. At the end of the iteration, the final value of memo
is the return value for the method.
If you do not explicitly specify an initial value for memo, then the
first element of collection is used as the initial value of memo.
So in your case:
input.to_s.each_char.inject(0) do |sum, ch|
(sum << 8) ^ (ch.ord) ^ (sum >> 4)
end
The initial value of sum is 0, which is used for the first iteration, but for each subsequent iteration the result of the block is used for sum in the next iteration.
For example the following should produce the same value without using inject/reduce.
sum = 0
input.to_s.each_char do |ch|
sum = (sum << 8) ^ (ch.ord) ^ (sum >> 4)
end

Recursion and order of statements execution

This question deals with how the statements and those involving recursion are executed, and in what order Ruby will handle the,. Specifically, as I've been learning online, I have found that Ruby does not follow Last in first out convention in a stack form of memory-management, but rather has a garbage collector. I have numbered questions at the bottom after all the code. I hope I have made everything clear, but please let me know what parts of the question may need improvement. Thank you.
def append(array, n)
return array if n < 0 #base case, how we end this thing
array << n*2 #Line No. 1
append(array, n - 1) #Line No. 2
array << n*2 #Line No. 3
end
append( [], 3)
#output [6,4,2,0,0,2,4,6]
The two lines below give the output of [6,4,2,0]
array << n*2 #Line No. 1
append(array, n - 1) #Line No. 2
When the order of the two statements are reversed the output is [0,2,4,6]
append(array, n - 1) #Line No. 2
array << n*2 #Line No. 3
In the original append method (top section of code), why does ruby stop to compute at the first recursive call, continue on to line 3, and then do the second recursive call, then concatenate the output of both recursions?
If line 2 and line 3 were the only part of the recursion the output would be[0,2,4,6], in ascending order. What is the convention that Ruby uses in its execution? Why does this code not give the output [6,4,2,0], since the n-1 is being called before array << n*2?
Is there a proper definition or programming theory as to how these recursive calls are handled?
Ruby is doing nothing unusual here, any more than any other "typical" computer language.
In the original append method (top section of code), why does ruby stop to compute at the first recursive call, continue on to line 3, and then do the second recursive call, then concatenate the output of both recursions?
I don't see any evidence for this. The first half of the output 6,4,2,0 is from Line 1. The second half 0,2,4,6 is from Line 3. Note that the first time it falls through to Line 3 is when n==0. So the next value after 6,4,2,0 is 0, then 2, 4, and finally 6. It pops out of the call stack, LIFO, just like any other computer language.
If line 2 and line 3 were the only part of the recursion the output would be[0,2,4,6], in ascending order. What is the convention that Ruby uses in its execution? Why does this code not give the output [6,4,2,0], since the n-1 is being called before array << n*2?
Because it has to call append 4 times before it returns to fall through to Line 3. By this time, n=0 which is why 0 is still first in this case.
Is there a proper definition or programming theory as to how these recursive calls are handled?
It's just LIFO. Give it some more thought.
If you're still not convinced, here is C++ code that prints the exact same sequence:
#include <iostream>
#include <list>
using namespace std;
list<int>& append( list<int> &array, int n )
{
if( n < 0 ) return array;
array.push_back(n*2);
append( array, n-1 );
array.push_back(n*2);
return array;
}
int main()
{
list<int> array;
append( array, 3 );
for( int& x : array ) cout << x << ' ';
cout << endl;
}

Finding the indexes of specific strings in an array, using a differently ordered equivalent array, ruby

I have two arrays: fasta_ids & frags_by_density. Both contain the same set of ≈1300 strings.
fasta_ids is ordered numerically e.g. ['frag1', 'frag2', 'frag3'...]
frags_by_density contains the same strings ordered differently e.g. ['frag14', 'frag1000'...]
The way in which frag_by_density is ordered is irrelevant to the question (but for any bioinformaticians, the 'frags' are contigs ordered by snp density).
What I want to do is find the indexes in the frag_by_density array, that contain each of the strings in fasta_ids. I want to end up with a new array of those positions (indexes), which will be in the same order as the fasta_ids array.
For example, if the order of the 'frag' strings was identical in both the fasta_ids and frags_by_density arrays, the output array would be: [0, 1, 2, 3...].
In this example, the value at index 2 of the output array (2), corresponds to the value at index 2 of fasta_ids ('frag3') - so I can deduce from this that the 'frag3' string is at index 2 in frags_by_density.
Below is the code I have come up with, at the moment it gets stuck in what I think is an infinite loop. I have annotated what each part should do:
x = 0 #the value of x will represent the position (index) in the density array
position_each_frag_id_in_d = [] #want to get positions of the values in frag_ids in frags_by_density
iteration = []
fasta_ids.each do |i|
if frags_by_density[x] == i
position_each_frag_id_in_d << x #if the value at position x matches the value at i, add it to the new array
iteration << i
else
until frags_by_density[x] == i #otherwise increment x until they do match, and add the position
x +=1
end
position_each_frag_id_in_d << x
iteration << i
end
x = iteration.length # x should be incremented, however I cannot simply do: x += 1, as x may have been incremented by the until loop
end
puts position_each_frag_id_in_d
This was quite a complex question to put into words. Hopefully there is a much easier solution, or at least someone can modify what I have started.
Update: renamed the array fasta_ids, as it is in the code (sorry if any confusion)
fasta_id = frag_id
Non optimized version. array.index(x) returns index of x in array or nil if not found. compact then removes nil elements from the array.
position_of_frag_id_in_d = frag_ids.map{|x| frag_by_density.index(x)}.compact

Ruby Exercise: Count the numbers in an array between a given range

So working through the above exercise and found this solution on GitHub.
def count_between arr, lower, upper
return 0 if arr.length == 0 || lower > upper
return arr.length if lower == upper
range = (lower..upper).to_a
arr.select { |value| range.include?(value) }.length
end
I understand what the first three lines mean and why they return the values they do. What I'd like to understand are the following lines of code.
Line 4 (below) is defining "range" as a variable and uses the lower...upper as the range variables (just discovered you don't need to put an integer value in a range. What does '.to_a' mean, can't seem to find it in the ruby docs, and what does it do?
range = (lower..upper).to_a
Line 5 (below) is using an Array#select method and its saying select this value if the value is included in this range and then give me the Array#length of all selected values, but I don't quite understand A. what |value| is doing and what it means. B. range.include?(value) means is this value included in this range I am assuming.
arr.select { |value| range.include?(value) }.length
Actually, I'd simplify to this:
def count_between arr, lower, upper
return 0 if lower > upper
arr.count{|v| (lower..upper).include?(v)}
end
to_a is documented here; it returns an Array containing each element in the Range. However, there's no reason to call to_a on the Range before calling include?.
There's also no reason to special-case the empty array.
Returning the length of the array when lower equals upper makes no sense.
value is the name given to the value the block is called with. I think a simple v is better for such a trivial case.
select calls the block for each value in arr and returns a new Array containing the elements for which the block returns true, so the length of that new Array is the number of matching values. However, count exists, and makes more sense to use, since the count is all we care about.
Update: As #steenslag points out in the comments, Comparable#between? can be used instead of creating a Range on which to call include?, and this eliminates the need to ensure that lower is less than or equal to upper:
def count_between arr, lower, upper
arr.count{|v| v.between?(lower, upper)}
end
to_a means convert to array
irb(main):001:0> (1..5).to_a
=> [1, 2, 3, 4, 5]
select method passes each element to the block and Returns a new array containing all elements of ary for which the given block returns a true value.. In your case it simply checks if the value is contained in the range array. range is an array not a range.
## if arr is [1,5] for eg:
irb(main):005:0> [1,5].select {|value| range.include?(value)}
=> [1, 5]
irb(main):006:0> [1,5].select {|value| range.include?(value)}.length
=> 2
so the elements of arr are contained in the |value| variable inside the block.
It's a block.
As the documentation says: select "Returns a new array containing all elements of ary for which the given block returns a true value."
So for each object in arr it is passed to the block in which you provide whatever code you want to that returns true or false, and the select statement uses this result to add the value to the the array that it returns. And after that, length is called on the array.
So you have an array, you filter the array to contain only the numbers that are in the range, and then you take the length - effectively counting the number of elements.

extracting from 2 dimensional array and creating a hash with array values

I have a 2 dimensional array
v = [ ["ab","12"], ["ab","31"], ["gh","54"] ]
The first element of the subarray of v will have repeating elements, such as "ab". I want to create a hash that puts the key as the first element of the subarray, and values as an array of corresponding second elements from v.
please advice.
Further, I want this, h={"ab"=>["12","31"],"gh"=>["54"]} and then I want to return h.values, such that the array [["12","31"],["54"]] is returned
v.inject(Hash.new{|h,k|h[k]=[]}) { |h, (k, v)| h[k] << v ; h}
What it does:
inject (also called reduce) is a fold. Wikipedia defines folds like this: "a family of higher-order functions that analyze a recursive data structure and recombine through use of a given combining operation the results of recursively processing its constituent parts, building up a return value".
The block form of Hash.new takes two arguments, the hash itself and the key. If your default argument is a mutable object, you have to set the default this way, otherwise all keys will point to the same array instance.
In inject's block, we get two arguments, the hash and the current value of the iteration. Since this is a two element array, (k, v) is used to destructure the latter into two variables.
Finally we add each value to the array for its key and return the entire hash for the next iteration.
v.inject({­}) do |res,­ ar|
res[ar.fir­st] ||= []
res[ar.fir­st] << ar.la­st
res
end
v = [ ["ab","12"], ["ab","31"], ["gh","54"] ]
This gets you a hash, where the keys are the
unique first elements from the sub arrays.
h = v.inject({}) { |c,i| (c[i.first] ||= []) << i.last; c }
This turns that hash back into an array, just in case you need the array of arrays format.
arr = h.collect { |k,v| [k,v] }

Resources