Interview Question: The Swap

Went to an interview at Verix today. It went rather well, I think. I’m over the interview cliches and I make that known so I also try to be honest because if they don’t want me as me, they would definitely wouldn’t want me pretending to be someone else and failing in a month. So I look for a character (or as my tech interviewer said, interests) compatibility. But, as usual, there is the usual interview tech question. This one, one I’ve seen before, is actually rather earnest and seemed to me to test actual knowledge. This one, tests knowledge of variable passing.

The idea is that we want a function that receives two variable references (strings in my case) and we need to swap them around. The problem that is needed to be understood here is that swapping the references, which will happen if you go with your first thought, doesn’t help.

temp = var1;

var1 = var2;

var2 = temp;

// doesn’t do anything once you exit the function

Because what ever you do, if you do it that way, you will switch around references in your hand and do nothing to the original pointers and data. What needs to be done is to access the underlying data and modify that.

for (int i; i < var1.length; i++)

{

tempPart = var1[0];

var1[0] = var2[0];

var2[0] = tempPart;

}

// this should get things done but be careful of access violations which are not protected against here.

That is, if all you get is the object you need to modify. If you could get the objects in a container or if you could output the swapped variables, that would be better. C also has realloc to avoid dangers in swapping strings of different lengths but introduces other dangers too.


Posted in No Category, Programming, Thinking Out Loud by with 2 comments.

Comments

  • Nihau says:

    It is interesting to see how people lose their ability to communicate with people outside their particular field as they progress in it and get so used to jargon.

    at the beginning of your degree I could follow you most of the time, with a few bits here and there where natural confusion happened. now its the opposite- I get a few bits here and there and most of the time I have no clue what you are talking about.

    • Eran says:

      I don’t think it’s like that. I can communicate about computers and programming at whatever level is convenient for the listener.

      When I address everyone then I make it simple. This one is meant to be a short description of a general idea solution to a problem that is relevant only to those interviewing for a new programming job. So it’s chock full of jargon and condensed anyway.

      I could explain it in a less jargon intensive method if you really care about this. :) I just assume anyone not into programming doesn’t.