Using multiple assignment to do what array.insert does? - arrays

I'm going through the code on a sample solution to my first Ruby Quiz (The Solitaire Cipher), and ran across this little nugget:
def move_down( index )
if index == #deck.length - 1
#deck[1..1] = #deck[index], #deck[1]
#deck.pop
else
...
end
end
The person who wrote this solution apparently used the multiple assignment in the second line to insert #deck[index] into the position before #deck[1]. Why not just use this?
#deck.insert(1, #deck[index])
Is there a difference?

OK, now I see what you mean. Sure, they will give the same result. I guess it just would be matter of choosing which style is more clear for you, or how you think your code would be easier to understand and in consequence more maintainable.
If your question is about which method is more "performant" I don't know that answer and I don't think it evens matters, as ruby is not meant to be performant but to be expressive.

Related

How do you represent a function call as an if condition statement in Sequence Diagram?

I've been drawing a sequence diagram of a module recently, while reverse engineering.
I encountered a control statement, and it is like,
if (func_A() == True)
{
DoSomeThing();
}
else
{
DoSomeThingElse();
}
The problem is how to draw the condition?
As I mentioned, It is reverse engineering. The code cannot be modified now.
I drew two diagrams, and I don't know which way is right,
The first one is this, I think it's wrong because it doesn't show the function call as a message from A to B.
This is the second, It shows a message func_A.
What do you think about to do this right?
To complete the other answer there is anyway a problem in the second proposal because we do not know if in [func_A() == True] you reuse the value return by the previous call or you do a second call, to avoid that add the explicit return in your diagram :
Out of that do you know the activities ? A sequence diagram is "just" an interaction while an activity is a behavior and can be more adapted :
It depends. If func_A is an operation defined in Object2 the second representation would be correct. The first does not tell where the operation is defined. Most likely (!) one would interpret func_A as an operation local to ObjectA which your code seems to say. (Btw. you have two completely different object sets AB vs. 12 in your examples.) But that is uncertain. So the 2nd variant is more explicit (and correct).
In any case I advise to not overdo SDs with fragments as "graphical programming" doesn't make things easier to read (my practical experience). It's excellent to show message flows in various collaborations. But when it comes to conditions it's getting messy very soon. A better way is to create different sub-diagrams or even use pseudo code if there are too nested if conditions. In many cases such if clauses are a good fit for state machines.

Dynamic vector creation

I am trying to create a vector dynamically in dependence of n (for example 1 or 4). If my n is bigger I need to have more values in my vector.
for i=1:(N-n)
yvecT(i)=y(n+i); % Achtung, Zeilenvektor
for k=n:-1:1
F(i-1+n,:)=[-y(i) -y(i-k) u(i) u(i-k)];
end
end
%n=1 F(i,:)=[-y(i) u(i)];
%n=2 F(i,:)=[-y(i) -y(i-1) u(i) u(i-1)];
%n=4 F(i,:)=[-y(i) -y(i-1) -y(i-2) -y(i-3) u(i) u(i-1) u(i-2) u(i-3)];
it is a function used to identify a System....
You should have posted the for-loop (with the if-statements) from the link in the question and stated that you wanted it to work for an arbitary n. That would have made everyone understand your problem. I think the easiest way to do what you do is to use subreferencing. So in case n==2 we do not have
F(i-1,:)=[-y(i) -y(i-1) u(i) u(i-1)];
but rather,
F(i-(n-1),:)=[-y(i:-1:(n-1)) u(i:-1:(n-1))];
This looks messier, but it works for any arbitary n. Some other comments about the code. The variable i is also a function returning the imaginary unit. By naming a variable i you overload this function. The recommended way is to use 1i as an imaginary unit, so it is not critical, but in case you do not necessarily need i as a variable you should consider another name. Also it is easier for us to understand in case you write in english. So in general, prefer comments in english when posting here.

How to search three or more arrays row by row for an optimum value in matlab

I have a few variables and here they are, three variables "R1, R2 and R3" each have a size of [40 x 1].
I have a fourth variable U of the same dimension. For every U(i) I need to search for an optimum value within R1(i), R2(i) and R3(i) which would return a single value solution. I intend to plot the optimum value against U9i).I have been trying to wrap my head around the knnsearch function but no luck.
Any one out there who could please help??
Thanks
Well when I can't wrap my head around something, I don't come here first.
A lot of people forget this one because we are online, but read a book on the topic. Have your code open so when you see something in the book, test it out.
Draw out any type of diagram. I call these "Napkin Diagrams", because I write it on anything, even a napkin.
I play with code until my keyboard has no letters left on it, then I keep plugging away until the keys fall off
Explore the language API's
Check for public repositories that you can play with
Google, is okay for a quick reference, but google will not teach you anything other than how to google
I talk my code over with myself all the time, people think I'm nuts, but so do I . . It actually works sometimes.
Then if I still can't get it, I come here with a list of things that I have tried, sample code that has not worked, etc.
I used to hate when people told me this, but that was the best thing anyone could have done for me so I tend to do the same now" Thinking about coding is a big part, but u have to get done wht u can. Then we all know what level u are at. Plus it being the end of semester a lot of these types of questions are homework...
Thinking is good, now turn those thoughts into a conceptual design . It's okay to be wrong in this stage, its all just conceptual
If I understood correctly, this might be what you need:
RR = [R1(:) R2(:) R3(:)];
d = bsxfun(#minus,RR, U(:));
[m mi] = min(abs(d),[],2);
answer = RR(:,mi);
first - put the three vectors into a single matrix:
RR = [R1(:) R2(:) R3(:)];
next, take the difference with U: bsxfun is ideal for this kind of thing
d = bsxfun(#minus,RR, U(:));
Now find the minimum absolute difference for each row:
[m mi] = min(abs(d),[],2);
The corresponding indices should allow you to find the "best fit"
answer = RR(:,mi);
I had to do some mind reading to get to this 'answer', so feel free to correct my misunderstanding of your problem!
update if you just need the highest of the three values, then
val = max([R1(:) R2(:) R3(:)]');
plot(U, val);
should be all you need...

ANTLR and arrays

I have question relating to implementation of arrays with Java+ANTLR combo. (I'm mainly talking about java/c style arrays).
So basically I'm asking how do you implement such feature, if there is such example already available or if someone could point me to anything that may point to solve it.
On other hand, I've searched a bit how would possible solution be. Main problem that I see
is that user may create arrays of various dimensions, even go crazy if he or she wants (like creating 5 dimension arrays or worse).
While grammar for something like this is fairly simple, like
new ID (INT (',' INT)* )
back end really gets involved a bit. As I said, user may input any number of dimensions, so array dimensions should be dynamically created. (at least as I see it, maybe I'm over complicating things?)
After searching I did found something that pretty much solves this problem perfectly, here is link to the question:
Is it possible to dynamically build a multi-dimensional array in Java?
Of course, my question is, is this viable example, it is a bit (to say at least), complicated? Is there more elegant solution to it?
Having that in mind, I was thinking maybe answer might be in the grounds of somehow transforming multidimensions
into more linear structure ? Could something like that be useful ? Simple search on stackoverflow pointed many solutions
to this, like:
Algorithm to convert a multi-dimensional array to a one-dimensional array
Would it be worth to search in that direction ?
Now, at the end, having in mind that arrays are really common feature in many languages, I must find it surprising that after searching ANTLR mailing list there is no similar question, which as I previously said leads me to believe that I'm maybe over complicating things ? (Unless I really suck at search?) I would really appreciate feedback.
Your syntax, if I'm not mistaken, corresponds to something like
new char 4,5,6,7
which is kind of strange. I expect that you really meant
new char[4,5,6,7]
However from a purely syntactic point of view, there's no reason not to just store the indices in an array and let the semantic analysis pass worry about it.

MD5 code kata and BDD

I was thinking to implement MD5 as a code kata and wanted to use BDD to drive the design (I am a BDD newb).
However, the only test I can think of starting with is to pass in an empty string, and the simplest thing that will work is embedding the hash in my program and returning that.
The logical extension of this is that I end up embedding the hash in my solution for every test and switching on the input to decide what to return. Which of course will not result in a working MD5 program.
One of my difficulties is that there should only be one public function:
public static string MD5(input byte[])
And I don't see how to test the internals.
Is my approach completely flawed or is MD5 unsuitable for BDD?
I believe you chose a pretty hard exercise for a BDD code-kata. The thing about code-kata, or what I've understood about it so far, is that you somehow have to see the problem in small incremental steps, so that you can perform these steps in red, green, refactor iterations.
For example, an exercise of finding an element position inside an array, might be like this:
If array is empty, then position is 0, no matter the needle element
Write test. Implementation. Refactor
If array is not empty, and element does not exist, position is -1
Write test. Implementation. Refactor
If array is not empty, and element is the first in list, position is 1
Write test. Implementation. Refactor
I don't really see how to break the MD5 algorithm in that kind of steps. But that may be because I'm not really an algorithm guy. If you better understand the steps involved in the MD5 algorithm, then you may have better chances.
It depends on what you mean with unsuitable... :-) It is suitable if you want to document a few examples that describes your implementation. It should also be possible to have the algorithm emerge from your specifciation if you add one more character for each test.
By just adding a switch statement you're just trying to "cheat the system". Using BDD/TDD does not mean you have to implement stupid things. Also the fact that you have hardcoded hash values as well as a switch statement in your code are clear code smells and should be refactored and removed. That is how your algorithm should emerge because when you see the hard coded values you first remove them (by calculating the value) and then you see that they are all the same so you remove the switch statement.
Also if your question is about finding good katas I would recommend lokking in the Kata catalogue.

Resources