Method vector::clear doesn't clear a two dimensional vector - vector

Thank you very much for the answer.
The reason that makes me think about checking the content of the vector is that even after I overwrite it, the same (strange) values remain. My purpose is to generate iteratively some random variables and put them in the two dimensional vector. I give you my code, maybe I am doing something wrong:
while (nbre_TTI_tempo != 0 )
{
srand(time(NULL)) ;
while (nbre_UE_tempo != 0 )
{
vect.clear() ;
nbre_PRB_tempo = nbre_PRB ;
while (nbre_PRB_tempo != 0)
{
value = rand() % 15 + 1 ; // generating random variables between 1 and 15
vect.push_back(value) ;
nbre_PRB_tempo -- ;
}
All_CQI.push_back(vect) ;
nbre_UE_tempo -- ;
}
// Do business
All_CQI.clear();
} .// end while
At the first round, everything goes well, but at the second one, this is what I find in the vector after the use of the method "clear":
158429184
14
15
158429264
10
9
158429440
5
1
And when I try to overwrite it, I find:
158429184
14
15
158429264
10
9
158429440
5
1
Which are the same values as before using the method "push_back".
Do you think I'm doing something wrong in my code?
Thank you very much in advance for your help.

For your purpose, if empty() returns true, you should trust that it is empty and SHOULD NOT check for individual elements. It is illegal to access the contents of an empty vector thus and can cause memory access errors.
The reason you find values is because the actual memory locations are not overwritten immediately- they are only marked as invalid. Until some other object is allocated the same memory, the data may remain as it is - but there is no way to be sure - the implementation is left to the compiler.
Looks like you are using the array operator[] to access the elements. To be safer, use the iterator or the .at() method to access the elements. Both these methods perform bounds checking and will not let you go beyond the last valid element

Related

Julia: Append to an array

Someone please help me understand this. I have the following code below. I am trying to append index[i]-1 to an empty array. However I am getting this error: "BoundsError: attempt to access 0-element Array{Any,1} at index [1]" :
sample_size_array = [9,5,6,9,2,6,9]
n_minus_1 = []
array_length = length(sample_size_array)
for i in 1:array_length
n_minus_1[i].append(sample_size_array[i] -1)
end
println(n_minus_1)
If Julia does not understand array[0] then why is i starting at 0 and not at 1?
Your code has two problems:
in the first iteration you are trying to access n_minus_1 array at index 1 while this array is still empty (has 0 length) - this throws you an error;
in Julia you do not invoke methods using a . (this symbol is used for different purposes - in this case it is parsed as field access and also would throw an error later)
To solve both those problems use push! function which appends an element at the end of an array. The code could look like this:
sample_size_array = [9,5,6,9,2,6,9]
n_minus_1 = []
array_length = length(sample_size_array)
for i in 1:array_length
push!(n_minus_1, sample_size_array[i]-1)
end
println(n_minus_1)
However in this case the whole operation can be written even simpler as:
n_minus_1 = sample_size_array .- 1
and you do not need any loop (and here you see another use of . in Julia - in this case we use it to signal that we want to subtract 1 from every element of sample_size_array).

How do I represent sparse arrays in Pari/GP?

I have a function that returns integer values to integer input. The output values are relatively sparse; the function only returns around 2^14 unique outputs for input values 1....2^16. I want to create a dataset that lets me quickly find the inputs that produce any given output.
At present, I'm storing my dataset in a Map of Lists, with each output value serving as the key for a List of input values. This seems slow and appears to use a whole of stack space. Is there a more efficient way to create/store/access my dataset?
Added:
It turns out the time taken by my sparesearray() function varies hugely on the ratio of output values (i.e., keys) to input values (values stored in the lists). Here's the time taken for a function that requires many lists, each with only a few values:
? sparsearray(2^16,x->x\7);
time = 126 ms.
Here's the time taken for a function that requires only a few lists, each with many values:
? sparsearray(2^12,x->x%7);
time = 218 ms.
? sparsearray(2^13,x->x%7);
time = 892 ms.
? sparsearray(2^14,x->x%7);
time = 3,609 ms.
As you can see, the time increases exponentially!
Here's my code:
\\ sparsearray takes two arguments, an integer "n" and a closure "myfun",
\\ and returns a Map() in which each key a number, and each key is associated
\\ with a List() of the input numbers for which the closure produces that output.
\\ E.g.:
\\ ? sparsearray(10,x->x%3)
\\ %1 = Map([0, List([3, 6, 9]); 1, List([1, 4, 7, 10]); 2, List([2, 5, 8])])
sparsearray(n,myfun=(x)->x)=
{
my(m=Map(),output,oldvalue=List());
for(loop=1,n,
output=myfun(loop);
if(!mapisdefined(m,output),
/* then */
oldvalue=List(),
/* else */
oldvalue=mapget(m,output));
listput(oldvalue,loop);
mapput(m,output,oldvalue));
m
}
To some extent, the behavior you are seeing is to be expected. PARI appears to pass lists and maps by value rather than reference except to the special inbuilt functions for manipulating them. This can be seen by creating a wrapper function like mylistput(list,item)=listput(list,item);. When you try to use this function you will discover that it doesn't work because it is operating on a copy of the list. Arguably, this is a bug in PARI, but perhaps they have their reasons. The upshot of this behavior is each time you add an element to one of the lists stored in the map, the entire list is being copied, possibly twice.
The following is a solution that avoids this issue.
sparsearray(n,myfun=(x)->x)=
{
my(vi=vector(n, i, i)); \\ input values
my(vo=vector(n, i, myfun(vi[i]))); \\ output values
my(perm=vecsort(vo,,1)); \\ obtain order of output values as a permutation
my(list=List(), bucket=List(), key);
for(loop=1, #perm,
if(loop==1||vo[perm[loop]]<>key,
if(#bucket, listput(list,[key,Vec(bucket)]);bucket=List()); key=vo[perm[loop]]);
listput(bucket,vi[perm[loop]])
);
if(#bucket, listput(list,[key,Vec(bucket)]));
Mat(Col(list))
}
The output is a matrix in the same format as a map - if you would rather a map then it can be converted with Map(...), but you probably want a matrix for processing since there is no built in function on a map to get the list of keys.
I did a little bit of reworking of the above to try and make something more akin to GroupBy in C#. (a function that could have utility for many things)
VecGroupBy(v, f)={
my(g=vector(#v, i, f(v[i]))); \\ groups
my(perm=vecsort(g,,1));
my(list=List(), bucket=List(), key);
for(loop=1, #perm,
if(loop==1||g[perm[loop]]<>key,
if(#bucket, listput(list,[key,Vec(bucket)]);bucket=List()); key=g[perm[loop]]);
listput(bucket, v[perm[loop]])
);
if(#bucket, listput(list,[key,Vec(bucket)]));
Mat(Col(list))
}
You would use this like VecGroupBy([1..300],i->i%7).
There is no good native GP solution because of the way garbage collection occurs because passing arguments by reference has to be restricted in GP's memory model (from version 2.13 on, it is supported for function arguments using the ~ modifier, but not for map components).
Here is a solution using the libpari function vec_equiv(), which returns the equivalence classes of identical objects in a vector.
install(vec_equiv,G);
sparsearray(n, f=x->x)=
{
my(v = vector(n, x, f(x)), e = vec_equiv(v));
[vector(#e, i, v[e[i][1]]), e];
}
? sparsearray(10, x->x%3)
%1 = [[0, 1, 2], [Vecsmall([3, 6, 9]), Vecsmall([1, 4, 7, 10]), Vecsmall([2, 5, 8])]]
(you have 3 values corresponding to the 3 given sets of indices)
The behaviour is linear as expected
? sparsearray(2^20,x->x%7);
time = 307 ms.
? sparsearray(2^21,x->x%7);
time = 670 ms.
? sparsearray(2^22,x->x%7);
time = 1,353 ms.
Use mapput, mapget and mapisdefined methods on a map created with Map(). If multiple dimensions are required, then use a polynomial or vector key.
I guess that is what you are already doing, and I'm not sure there is a better way. Do you have some code? From personal experience, 2^16 values with 2^14 keys should not be an issue with regards to speed or memory - there may be some unnecessary copying going on in your implementation.

Trying to understand how two same method call placed one after the other in recursive method

Below is an example of quicksort. I was wondering how two recursive method call inside quicksort method works i.e in what sequence it'll execute? So to check in what sequence I placed syso after each method (check output).My doubt why this sequence?Thus it depends on any conditions? if so, what condition? It would be helpful if explained the logic in detail.
Thank you in advance :)
void quicksort(int a[], int p, int r)
{
if(p < r)
{
int q;
q = partition(a, p, r);
System.out.println("q:"+q);
quicksort(a, p, q);
System.out.println("1");
quicksort(a, q+1, r);
System.out.println("2");
}
}
int partition(int a[], int p, int r)
{
System.out.println("p:"+p+" r:"+r);
int i, j, pivot, temp;
pivot = a[p];
i = p;
j = r;
while(1)
{
while(a[i] < pivot && a[i] != pivot)
i++;
while(a[j] > pivot && a[j] != pivot)
j--;
if(i < j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
else
{
return j;
}
}
}
Output
p:0 r:7
q:4
p:0 r:4
q:0
1
p:1 r:4
q:1
1
p:2 r:4
q:3
p:2 r:3
q:2
1
2
1
2
2
2
1
p:5 r:7
q:7
p:5 r:7
q:6
p:5 r:6
q:5
1
2
1
2
1
2
2
Would like to know why the gap between method calls?i.e how println(placed after method calls) statement getting executed w/o executing method call?
Yes, it depends on conditions: specifically, the values of p and r on each call. Each instance of the sort will do the two calls in order: none of the execution branches will get to the second call until the first call of that branch is completely done.
You will get a much nicer trace if you put a println at the top of the function that displays the parameter values. You might want to place one after you compute the value of q, as well. Try that, and see whether it tells you the rest of the story.
Okay, you've done the printing ... and you don't see the reason for that gap? When you get to the output line "q:2", you've made five calls to quicksort, and the only progress through that sequence is that you've made it past the "1" print for two of them (you're in the second call). Your current stack looks like this, in terms of p and r:
2, 3
2, 4
0, 4
0, 7
This is the right half of the left half (second quarter) of the array, four levels deep. You now have to finish off those calls, which will get you to the "1" print for the "right-half" ones, the "2" print for each of them.
Looking at it another way, you work to partition the array down to single elements. While you're doing this, you stack up calls for smaller partitions. Any call with at least two elements has to finish off both of its partitions before it returns to the next print.
Once you get to a single-element array, you return right away, and get to print the next "1" or "2". If the other partition is also fully atomized, then you get to the next "1" or "2" without any more partitioning calls.
Halfway through, you get to the point where you've fully atomized the left half of the array; that's when you clear out all the outstanding processing, back up the stack, and do all of that printing. Then you recur down the right half, and get a similar effect.
I think you might have an easier time understanding if you'd give yourself a full trace. Either follow this in your debugger, or modify and add print statements so that (1) you have a unique, easily-read output for every line, rather than 8 lines each of "1" and "2" that you can't tell apart; (2) you can also trace the return from each routine. The objective here is to be able to recognize where you are in the process at each output line.
Yes, it's another programming problem to be able to print out things such as
1.L.R.R
1.1.2
(0,4) L
...
... or whatever format you find readable.

Basics in for loop in actionscript 3 in flex

Good Morning stackoverflow...
I'm having a problem.... this is my sample code
var i:Number = new Number();
trace("showarray length" + showArray.length);
for(i=0;i<showArray.length;i++){
trace("equal daw" + showArray.getItemAt(i).id + "==" + num);
if(showArray.getItemAt(i).id == num){
showArray.removeItemAt(i);
}
}
trace('alerts');
myproblem here is...wherenever the if is satisfied it stops looping it immediately goes out of the loop
this is a sample output
given that the length of showArray is 2 and num = 0
showarray length2
equal daw0==0
alerts
please help me
If you want to remove items while iterating over array, iterate in reverse order. This way element removal does not affect cycle condition:
for (var i:int = showArray.length - 1; i >= 0; i--) {
if (someCondition) {
showArray.removeItemAt(i);
}
}
Another small bonus that this is slightly faster, as it doesn't call showArray.length on each step.
An even better way might be to use the filter method of the Array class.
array = array.filter(function (e:*, i:int, a:Array):Boolean {
return e.id != num;
});
When your if is satisfied for id == num (which is 0 so happening in the first loop) and the item is removed, your array length decreases to 1 so the loop won't run any more.
That's because you are removing items at the time you are iterating throught them.
array = [1, 2]
^ // pointer in first iteration
eliminate 1
array = [2]
^ // the pointer remains in the same location
//ups! out of the loop. all items were visited.
You can copy the array before you iterate through it and iterate the copy or mark the indices to remove and remove them later or iterate the array backwards.
PS: Sorry for my poor English.
After showArray.removeItemAt(i);, add i--;
Because you removed the item at index i from the array, the item that was at i + 1 got moved to i. By subtracting one, you ensure that the moved item doesn't get skipped.
alxx's answer is also a good solution.

What are block expressions actually good for?

I just solved the first problem from Project Euler in JavaFX for the fun of it and wondered what block expressions are actually good for? Why are they superior to functions? Is it the because of the narrowed scope? Less to write? Performance?
Here's the Euler example. I used a block here but I don't know if it actually makes sense
// sums up all number from low to high exclusive which are divisible by a or b
function sumDivisibleBy(a: Integer, b: Integer, high: Integer) {
def low = if (a <= b) a else b;
def sum = {
var result = 0;
for (i in [low .. <high] where i mod a == 0 or i mod b == 0) {
result += i
}
result
}
}
Does a block make sense here?
Well, no, not really, it looks like extra complexity with no real benefit. Try removing the sum variable and the block and you will see that the code still works the same.
In general block expressions can be useful when you want to create an anonymous scope rather than factoring the code into a function, most of the time you should rather create a function.

Resources