What is the output of this array pseudocode and why? - arrays

I am a new student in a programming fundamentals course. I have absolutely no previous experience with programming. I am trying to understand a question that was posed on a recent quiz about arrays. This is it: What will be the output of the pseudocode below?
nums = [30, 10, 20, 50, 40]
val = 0
For i = 0 to 5
val = nums[i] + val
Display val
Thanks for any thoughts on this. I don't understand it at all. I originally thought 40 was the answer but sadly, that was wrong lol. Can someone tell me what the answer is and explain why that's so? Our textbook doesn't have any examples like this.

Well, as Wayne already said, the for loops is running on to many times, which would result in an exception. Assuming that is a mistake and that the loop only runs 5 times. Then your result would be 30 + 10 + 20 + 50 + 40, as it just adds all values of the array up and saves it in val. So it would probably display 150, unless I am completely wrong and I also misunderstood it.

As posed, the correct answer is "This code generates an error/exception." The reason is that the loop is iterating over six array elements, but the array contains only five. Here are just some of the things that various real languages might do in this case:
Generate an incorrect result.
Abort the program with a memory error (accessing memory out of bounds).
Generate an exception due to an invalid array index.
Generate an exception due to adding nil/null to an integer.
But the one thing you can be sure of is that the program is incorrect.

Related

Loop through table without checking if end of table has been reached

I really don't like asking a question regarding homework, but this question has me stumped. It seems like the answer should be so simple, yet the answer escapes me!
The question comes from "Data Structures and Algorithms" by Harry Lewis and Larry Denenberg, question 1 of chapter 1. We have a simple for loop for sequential search.
function SequentialSearch(table T[0...n-1], key K): integer
{Return position of K in table T, if it is present, otherwise -1}
for i from 0 to n - 1 do
if T[i] = K then return i
return -1
Simple enough, right? Okay, for every iteration through this loop, there are two checks: (1) check if T[i] = K, and (2) check if i > n - 1. The runtime for each loop iteration is a constant 2. The question is this: how can the runtime be reduced to 1? How can I get rid of having to check if i > n - 1 (i.e., if the end of the table has been reached)?
The hint given to us is that a sentinel value can be used. Well, that's simple enough, except for one problem, which is this: How does checking against a sentinel value improve the runtime from checking against the table's length? Wouldn't the runtime still be 2 for each iteration regardless of whether I check against the table's length or against a sentinel value?
I'm not expecting to be given an answer here. (The answer will be written in pseudocode.) I'm just stumped at how to implement this to reduce the runtime. To me, it seems like it's reduced to as little as possible, but what do I know?
Thanks!
How about a hint: The sentinel value, which you put into T[n], doesn't have to be the same for every run of the algorithm. It can depend K, the value you're searching for. Does this help?

Cannot match exact number within an array in R

This must be a trivial one but after many, many trials and errors I need to ask this.
I would like to find a whole number within a numerical array, e.g. 14 in c(1,14,144).
The code I tried reads
dayNo <- 14
which(grepl(dayNo, c(1,14,144))==TRUE)
I get 2 & 3. The results I am looking for is 2.
Another one is
dayNo <- 14
which(grepl("\\bdayNo\\b", c(1,14,144))==TRUE)
but I get as result integer(0).
Any ideas would be very appreciated.
In this case this simple solution works just fine
which(dayNo==c(1,14,144))and gives as expected 2

Updating values in an array with logical indexing with a non-constant value

A common problem I encounter when I want to write concise/readable code:
I want to update all the values of a vector matching a logical expression with a value that depends on the previous value.
For example, double all even entries:
weights = [10 7 4 8 3];
weights(mod(weights,2)==0) = weights(mod(weights,2)==0) * 2;
% weights = [20 7 8 16 3]
Is it possible to write the second line in a more concise fashion (i.e. avoiding the double use of the logical expression, something like i+=3 for i=i+3 in other languages). If I often use this kind of vector operation in different contexts/variables, and I have long conditionals, I feel that my code is less concise and readable than it could be.
Thanks!
How about
ind = mod(weights,2)==0;
weights(ind) = weights(ind)*2;
This way you avoid calculating the indices twice and it's easy to read.
Starting your other comment to Wauzl, such powerful operation capabilities is the Fortran side. This is purely matlab's design that is quickly getting obsolete. Let's use this horribleness further:
for i=1:length(weights),if (mod(weights(i),2)==0)weights(i)=weights(i)*2;end,end
It is even slightly faster than your two liner because you are doing the conditional indexing twice on both sides. In general, consider switching to Python3.
Well, I after more searching around, I found this link that deals with this issue (I used search before posting, I swear!), and there is interesting further discussion regarding this topic in the links in that thread. So apparently there are issues with ambiguity when introducing such an operator.
Looks like that is the price we have to pay in terms of syntactic limitations for having such powerful matrix operation capabilities.
Thanks a lot anyway, Wauzl!

Creating binary indexed tree

I read various tutorials on BIT.. topcoder etc ones, all operations are well explained in those, but m not getting the way BIT is created i.e.
Given an array, 1-D, how e have to kake the corresponding BIT for that? ex. if the array is 10 8 5 9 1 what will the BIT for this?
I am a beginner, so apologies if my question sounds stupid but i am not understanding this. So, please help.
You simply start with an empty structure (allo 0s) and insert each element. Complexity is O(NLogN) but likely the rest of your algotihm is also NLogN so it will not matter.

matlab error, attempt to reference field of non structure array

All the references to this error I could find searching online were completely inapplicable to my situation, they were dealing with some kind of variables involving dots, like a.b (structures in other words), whereas I am strictly using arrays. Nothing involves a dot, nor does my code ask about it.
Ok, I have this GINORMOUS array called tier2comparatorconnectionpoints. It is a 4-D array of size 400×10×20×10. Consider tier2comparatorconnectionpoints(counter,counter2,counter3,counter4).
counter is a number 1 to 400,
counter2 is a number 1 to numchromosomes(counter), and numchromosomes(counter1) is bound to 10,
counter3 is a number 1 to tier2numcomparators(counter,counter2), which is in turn bounded to 20.
counter4 is a number 1 to tier2inputspercomparator(counter,counter2,counter3), which is bounded to 10.
Now, so that I don't run out of RAM, I have tier2comparatorconnectionpoints as type int8, and UNFORTUNATELY at some point in my horrendous amount of code, I forgot to cast it to a double when I'm doing math with it, and a rounding error involved with multiplying it with a rand ends up with tier2comparatorconnectionpoints for some values of its 4 inputs exceeding what it's allowed to be.
The values it's allowed to have are 1 through tier1numcomparators(counter,counter2), which is bounded to 40, 41 through 40+tier2numcomparators(counter,counter2), with tier2numcomparators(counter,counter2) being bounded to 20, and 61 through 60+tier2numcomparators(counter,counter2), thus it's not allowed to be more than 80 since tier2numcomparators(counter,counter2) is bounded to 20 and it's not allowed to be more than 60+tier2numcomparators(counter,counter2), but it's also not allowed to be less than 40 but more than tier1numcomparators(counter,counter2) and it's not allowed to be less than 60 but more than 40+tier2numcomparators(counter,counter2). I became aware of the problem because it was being set to 81 somewhere.
This is an evolutionary simulation by the way, it's natural selection on simulated organisms. I need to hunt down the part of the code that is allowing the values of tier2comparatorconnectionpoints to exceed what it's allowed to be. But that is a separate problem.
A temporary fix of my data, just so that it at least is made to conform to its allowed values, is to set anything that is greater than tier1numcomparators(counter,counter2) but less than 40 to tier1numcomparators(counter,counter2), to set anything that is greater than 40+tier2numcomparators(counter,counter2) but less than 60 to 40+tier2numcomparators(counter,counter2), and to set anything that is greater than 60+tier2numcomparators(counter,counter2) to 60+tier2numcomparators(counter,counter2). I first found this problem because it was being set to 81, so it didn't just exceed 60+tier2numcomparators(counter,counter2), it exceeded 60+20, with tier2numcomparators being bounded to 20.
I hope this isn't all too-much-information, but I felt it might be necessary to get you to understand just what sort of variables these are.
So in my attempts to at least turn the data into valid data, I did the following:
for counter=1:size(tier2comparatorconnectionpoints,1)
for counter2=1:size(tier2comparatorconnectionpoints,2)
for counter3=1:size(tier2comparatorconnectionpoints,3)
for counter4=1:size(tier2comparatorconnectionpoints,4)
if tier2comparatorconnectionpoints(counter,counter2,counter3,counter4)>60+tier2numcomparators(counter,counter2)
tier2comparatorconnectionpoints(counter,counter2,counter3,counter4)=60+tier2numcomparators(counter,counter2);
end
end
end
end
end
And that worked just fine. And then:
for counter=1:size(tier2comparatorconnectionpoints,1)
for counter2=1:size(tier2comparatorconnectionpoints,2)
for counter3=1:size(tier2comparatorconnectionpoints,3)
for counter4=1:size(tier2comparatorconnectionpoints,4)
if tier2comparatorconnectionpoints(counter,counter2,counter3,counter4)>40+tier2numcomparators(counter,counter2)
if tier2comparatorconnectionpoints(counter,counter2,counter3,counter4)<60
tier2comparatorconnectionpoints(counter,counter2,counter3,counter4)=40+tier2numcomparators(counter,counter2);
end
end
end
end
end
end
And that's where it said "Attempt to reference field of non-structure array".
TBH it sounds like maybe you've made a typo and put a . in somewhere? Otherwise please post the entire error as maybe it's happening in a different function or something.
Either way you don't need all those for loops, it's simpler and usually quicker to do this (and should bypass your error):
First replicate your tier2numcomparators matrix so that it has the same dimension sizes as tier2comparatorconnectionpoints
T = repmat(tier2numcomparators + 40, 1, 1, size(tier2comparatorconnectionpoints, 3), size(tier2comparatorconnectionpoints, 4));
Now in one shot you can create a logical matrix of which elements meet your criteria:
ind = tier2comparatorconnectionpoints > T | tier2comparatorconnectionpoints < 60;
Finally employ logical indexing to set your desired elements:
tier2comparatorconnectionpoints(ind) = T(ind);
You can play around with bsxfun instead of repmat if this is slow or takes too much memory

Resources