How do you swap two integer variables without using any if conditions, casting, or additional variables? [closed] - swap

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
There are two integer variables. Can you swap those integer variables without using any if conditions, without casting, and without using additional variables? For example:
int a = 10;
int b = 5;
a > b always. The answer should be a == 5 and b == 10

If you think you are being clever by not using 3rd variable then do some performance tests and you see that the much faster way is to use 3rd int to store the variable temporarily.
Anyways, i solved the problem with XOR bitwise operator:
a ^= b;
b ^= a;
a ^= b;

a=a+b;
b=a-b;
a=a-b;

It's a little trick.
int a = 5;
int b= 10;
a = a+b;
b = a-b; /* Really (a+b) - b i.e. a */
a = a-b; /* Really (a+b) - a i.e. b */

simple try this
a=a+b;
b=a-b;
a=a-b;
and that's it

yes you can do it By using plus/minus operation.
Example:
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;

a=a+b
b=a-b
a=a-b
That's it!

Related

How to find out if first x bits are set in a binary representation of an integer effectively?

In a recent interview, I was asked this question. I gave the solution by running a loop and checking every one of the x bits by right-shifting 1 every time.
Then he asked if I can do this without running a loop. I tried various approaches but could not find a solution. Can here any bit-fiddling expert help me out?
Example - if num = 15 and x = 2 then result should be true because 1st 2 bits are set in 15(01111).
Thanks
I think following (Java implementation) should work:
/** Returns true if the least significant x bits in n are set */
public static boolean areLSBSet(int n, int x) {
// validate x, n
int y = (1<<x) - 1;
return (n & y) == y;
}
The idea is to quickly find out the number that is 2^x - 1 (this number has all the x least significant bits set) and then taking the bitwise-and with given number n which will give the same number only if exactly that many bits in n are set.

Fibonacci sequence in solving an equation

Im trying to figure out an equation. This is f(n)=f(n-1) + 3n^2 - n. I also have the values to use as f(1), f(2), f(3). How would i go about solving this??
You would usually use recursion but, whether you do that or an iterative solution, you're missing (or simply haven't shown us) a vital bit of information, the terminating condition such as f(1) = 1 (for example).
With that extra piece of information, you could code up a recursive solution relatively easily, such as the following pseudo-code:
define f(n):
if n == 1:
return 1
return f(n-1) + (3 * n * n) - n
As an aside, that's not actually Fibonacci, which is the specific 1, 1, 2, 3, 5, 8, 13, ... sequence.
It can be said to be Fibonacci-like but it's actually more efficient to do this one recursively since it only involves one self-referential call per level whereas Fibonacci needs two:
define f(n):
if n <= 2:
return 1
return f(n-2) + f(n-1)
And if you're one of those paranoid types who doesn't like recursion (and I'll admit freely it can have its problems in the real world of limited stack depths), you could opt for the iterative version.
define f(n):
if n == 1:
return 1
parent = 1
for num = 2 to n inclusive:
result = parent + (3 * num * num) - num
parent = result
return result
If you ask this question on a programming site such as Stack Overflow, you can expect to get code as an answer.
On the other hand, if you are looking for a closed formula for f(n), then you should direct your question to a specialised StackExchange site such as Computer Science.
Note: what you are looking for is called the repertoire method. It can be used to solve your problem (the closed formula is very simple).

Approximation of sum/average of last n terms in a series

Assume I have a series t_1, t_2,..., t_n,..., and the number is always coming in. I want to calculate the approximate of sum/average of last t numbers, but without storing those t numbers. The only thing stored is the previous sum/average. What is the appropriate function?
E.g.
s_1 = t_1
s_2 = f(t_2, s_1)
s_3 = f(t_3, s_2)
The possible function may be like s_2 = t_2 + s_1 * (e ^ -1), but what is the optimal solution?
Note: The window size is fixed. So there is no exact solution, but an approximation, since the number out of the window is not known.
Note 2: Thanks for all the discussion. I know the answer now. It is really trivial, my fault not thinking it well. I will delete this question later. But any way, the answer is, I should assume that the number out of the window is the average. Under this assumption, the new sum is
(old average)*(t-1) + new number
and the new average is
((old average)*(t-1)+(new number))/t
First of all, this realistically is probably a question for Mathematics Stack Exchange
but anyway, since you dont mention a programming language, Ill go with C# (with an array). lets call your series 'mySeries':
double average=0;
for (int i = 0; i < mySeries.Length; i++)
average+=mySeries[i]/(i+1);
MessageBox.Show("Here is your average dawg:" + average.ToString());

Most significant decimal digit (or 0.3 - 0.1 = 0.1 ) [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
This operation should return 2, but it returns 1 instead because of the floating point representation:
a <- .3
b <- .1
floor((a-b)*10)
I basically want the first digit after the point, of the actual base-10 result, not the floating-point computer's result. In this case a and b only have one decimal digit, but in most situations there will be more. Examples:
0.3-0.1=0.2 so I want the 2
0.5-0.001=0.499 so I want the 4
0.925-0.113=0.812 so I want the 8
0.57-0.11=0.46 so I want the 4
0.12-0.11=0.01 so I want the 0
that is, not rounding but truncating. I thought of using this:
floor(floor((a-b)*100)/10)
but I'm not sure if that is the best I can do.
update: indeed, it doesn't work (see comments below):
floor(floor((.9-.8)*100)/10) # gives 0 instead of 1
floor(round((.5-.001)*100)/10) # gives 5 instead of 1
update 2: think this does work (at least in all cases listed so far):
substring(as.character(a-b),first=3,last=3)
Suggestions?
This is not possible, because the information is no longer there:
doubles cannot exactly represent decimal numbers.
If you are fine with an approximate solution,
you can add a small number, and truncate the result.
For instance, if you know that your numbers have at most 14 digits,
the following would work:
first_digit <- function(x, epsilon=5e-15)
floor( (x+epsilon) * 10 )
first_digit( .3 - .1 ) # 2
first_digit( .5 - .001 ) # 4
first_digit( .925 - .113 ) # 8
first_digit( .57 - .11 ) # 4
first_digit( .12 - .11 ) # 0
If you wanted the first significant digit (that means "first non-zero digit"),
you could use:
first_significant_digit <- function(x, epsilon=5e-14)
floor( (x+epsilon) * 10^-floor(log10(x+epsilon)) )
first_significant_digit(0.12-0.11) # 1

Filter out columns in R [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Referring to Post# Filtering out columns in R , the columns with all 1's and 0's were successfully eliminated from the training_data. However, the classification algorithm still complaint about the columns where MOST of the values are 0's except 1 or 2 (All the values in the column are 0 except 1 or 2 values).
I am using penalizedSVM R package to perform feature selection. Looking more closely at the data set, the function svm.fs complains about the columns where most of the values are 0 except a one or two.
How one can modify (or add something to) the following code to achieve the result.
lambda1.scad<-c(seq(0.01, 0.05, .01), seq(0.1, 0.5, 0.2), 1)
lambda1.scad<-lambda1.scad[2:3]
seed <- 123
f0 <- function(x) any(x!=1) & any(x!=0) & is.numeric(x)
trainingdata <- lapply(trainingdata, function(data) cbind(label=data$label,
colwise(identity, f0)(data)))
datax <- trainingdata[[1]]
levels(datax$label) <- c(-1, 1)
train_x<-datax[, -1]
train_x<-data.matrix(train_x)
trainy<-datax[, 1]
idx <- is.na(train_x) | is.infinite(train_x)
train_x[idx] <- 0
tryCatch(scad.fix<-svm.fs(train_x, y=trainy, fs.method="scad",
cross.outer=0, grid.search="discrete",
lambda1.set=lambda1.scad, parms.coding="none",
show="none", maxIter=1000, inner.val.method="cv",
cross.inner=5, seed=seed, verbose=FALSE), error=function(e) e)
Or one may propose an entirely different solution.
Use the fact that boolean values can be summed and define some tolerance of zeros:
sum(x == 0) / length(x) >= tolerance
Where this becomes your condition for dropping. However, often zeros are not only valid data, but are critical to the phenomenon being studied. You should think carefully about your algorithm choice and the decision to drop columns before going forward wit this approach.

Resources