473,796 Members | 2,603 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

replace values

I'm using 2 integer numbers X and Y.
I would like to replace there values(Y=X, X=Y) but without using any other
variables or functions.

Hrcko
Oct 3 '07
19 1449
"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************@m snews.microsoft .com...
marss <ma******@gmail .comwrote:
On 3 , 19:27, Göran Andersson <gu...@guffa.co mwrote:
You don't have to play around with bits. It works just fine with
addition and subtraction:

var1 -= var2
var2 += var1
var1 = var2 - var1

Not so reliable as Graeme's solution. What about stack overflow? :)
I can't see how the stack would overflow. You might get *numeric*
overflow, but that would just wrap round - shouldn't be a problem.

--
Jon Skeet - <sk***@pobox.co m>

I thought it was obvious marss ment numeric overflow.
But you are right, syntax is not semantics, and correction
is needed in this forum.

But I still think that marss has the best solution,
as it is totally OO and does it with one understandable line of code.

I bet it also has better performance, as while we have no idea,
the call to .Exchange() could be optimized by the jitter
understanding there is no need for interlocking anything,
and then just shift two registers...by using a third register...
Oh, wait a minute! That's a temp-register, no?!

That would be cheating! =)

- Michael Starberg
Oct 3 '07 #11
Jon Skeet [C# MVP] wrote:
I can't see how the stack would overflow. You might get *numeric*
overflow, but that would just wrap round - shouldn't be a problem.
I guess it depends on the implementation. You could easily imagine a
type that does some range-checking on arithmetic and either throws an
exception or pins the value or some such thing. The original question
did not actually assume or demand a C# int-specific implementation.
Just that the values are integers.

Of course, if that type doesn't implement a bit-wise XOR or similar
alternative, you're kind of out-of-luck anyway. But still.

And of course, the real-world bottom line here is that there's really no
reason to try to swap the variables without a temp anyway. :)

Pete
Oct 3 '07 #12
On 3 , 22:33, Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
>>I can't see how the stack would overflow. You might get
*numeric* overflow,
Of course, shame on me :)
>>but that would just wrap round - shouldn't be a problem.
I am surprised but you are right - that is not a problem?!!! I made a
test example (VS 2005):

int var1 = 2000000000;
int var2 = -2000000001;

var1 -= var2; //-294967295 = result is truncated
var2 += var1; //2000000000
var1 = var2 - var1; //-2000000001

Why this happens?

Regards,
Mykola
http://marss.co.ua

Oct 4 '07 #13
On 4 , 08:27, marss <marss...@gmail .comwrote:
Why this happens?
I mean, why it returns a correct result even though one of the values
is truncated? Can anyone explain?

Mykola

Oct 4 '07 #14
marss wrote:
[...]
int var1 = 2000000000;
int var2 = -2000000001;

var1 -= var2; //-294967295 = result is truncated
var2 += var1; //2000000000
var1 = var2 - var1; //-2000000001

Why this happens?
Well, first, the result isn't "truncated" . It overflowed.

As for why it works okay, it's because the overflow isn't actually a
problem unless you care about the intermediate value. And in this case
you don't. All that you lose in the overflow is the bit that would have
been carried; all of the other bits are just as they should be. And the
carry bit isn't required for the subsequent operations that restore the
original value to wind up correct (you get more overflow, and again the
carry bit is irrelevant).

Another way of looking at it is that you've got a bit circular number
line, where the circle connects at the minimum and maximum values for
the type. The addition and subtraction operations shift your position
around on the number line and may in fact cross that place on the number
line where the min and max meet, but wrapping around doesn't hurt, as it
simply gets offset in the subsequent operation back into the correct
range of values.
As long as you're dealing with a type that allows this overflow to occur
undetected and uncorrected, there's no problem.

Pete
Oct 4 '07 #15
marss <ma******@gmail .comwrote:
On 3 , 22:33, Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
>I can't see how the stack would overflow. You might get
*numeric* overflow,

Of course, shame on me :)
>but that would just wrap round - shouldn't be a problem.

I am surprised but you are right - that is not a problem?!!! I made a
test example (VS 2005):

int var1 = 2000000000;
int var2 = -2000000001;

var1 -= var2; //-294967295 = result is truncated
var2 += var1; //2000000000
var1 = var2 - var1; //-2000000001

Why this happens?
The result isn't truncated - it just wrapped round.
Int.MaxValue+1= Int.MinValue. You lose the information that you *have*
wrapped round, but nothing else. As your code then reverses the
operation, you end up with the right answer.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Oct 4 '07 #16
"Peter Duniho" <Np*********@Nn OwSlPiAnMk.comw rote in message
news:13******** *****@corp.supe rnews.com...
>
Another way of looking at it is that you've got a bit circular number
line, where the circle connects at the minimum and maximum values for the
type. The addition and subtraction operations shift your position around
on the number line and may in fact cross that place on the number line
where the min and max meet, but wrapping around doesn't hurt, as it simply
gets offset in the subsequent operation back into the correct range of
values.
Nice analogy. I remember that one.

- Michael Starberg
Oct 4 '07 #17
Thanks for answers.
This is one more candidate for "aha!" interview questions, is not
it? :)

Mykola
http://marss.co.ua

Oct 4 '07 #18
"marss" <ma******@gmail .comwrote in message
news:11******** **************@ o80g2000hse.goo glegroups.com.. .
Thanks for answers.
This is one more candidate for "aha!" interview questions, is not
it? :)
Nah, Mykola.
You created echos at my work and in other forums.
This is one snippet of text that from someone not impressed.

<q>
Of course, anyone can write a function to swap two values.

And x86 assembler has had XCHG for a long time already, and that is
locked as well. Nothing new. Next!
<q/>

But I am impressed.
I hope Hrvoja Voda sends your solution to his future employer.
Also, I feel sorry for the employer if they hire the cheater.
>
Mykola
http://marss.co.ua
My I ask: Did you come up with it yourself, or read it somewhere?

- Michael Starberg
Oct 4 '07 #19
On 5 , 01:24, "Michael Starberg" <n...@no.comwro te:
But I am impressed.
I hope Hrvoja Voda sends your solution to his future employer.
Also, I feel sorry for the employer if they hire the cheater.
Thanks for kind words.
I do not think that you should feel sorry for the employer who based
his decision on solving puzzles only, he cheats with questions, Hrvoja
Voda cheats with answers - fair play :)
My I ask: Did you come up with it yourself, or read it somewhere?
I read it in CLR via C# by Jeffrey Richter.

Regards,
Mykola
http://marss.co.ua
Oct 5 '07 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2255
by: andrea.gavana | last post by:
Hello NG, probably this is a basic question, but I'm going crazy... I am unable to find an answer. Suppose that I have a file (that I called "Errors.txt") which contains these lines: MULTIPLY 'PERMX' @PERMX1 1 34 1 20 1 6 / 'PERMX' @PERMX2 1 34 21 41 1 6 / 'PERMX' @PERMX3 1 34 1 20 7 14 /
3
1688
by: Roy Adams | last post by:
Hi group I'm having trouble using the replace command Here's my code below <%@LANGUAGE="JAVASCRIPT" CODEPAGE="1252"%> <!--#include file="../../Connections/conn.asp" --> <% if( String(Request.Form("ProductName")) != "undefined" ){//formfield
1
1888
by: Will | last post by:
I have the following code: var rx = /{{(.+?)}}/i; var expr = 'each {{word}} wrapped in {{curly}} {{braces}} in this {{string}} needs to be {{replaced}} with a different {{value}}.'; var values = ; values = "foo"; values = "bar"; values = "bundy";
3
2428
by: RickN | last post by:
What is the best way to open a file and perform a search and replace for multiple char values. Thanks, RickN
3
5453
by: Andy Sutorius | last post by:
Hi, I read the thread (2/16/05) regarding a replace function in C# however it didn't answer my question. I have a string which is building an insert sql statement and I would like to replace apostrophes of the form fields. I was trying to do something like this: string sqlInsertEmails = "insert into tblContent (content, subject) values ('" + Replace(txtBody.Text,"'","''") + "', '" + Replace(txtSubject.Text,"'","''") + "')";
12
7325
by: Michael | last post by:
In PHP there is a function called str_replace (http://php.net/str_replace). Basically you can freed in two strings and a "subject" string. Then it goes through the subject string searching for occurences of the "search" string and replaces them with the "replace" string. Is there something simular in JavaScript, or can someone give me a solution. I am an experienced PHP user and XHTML writer, and I have learnt Javascript to a reasonable...
2
1577
by: john | last post by:
In a table I have text field A. I would like to replace all the null values in field A to a real value, let's say 'Test'. When I use Find & Replace and I search for 'is null' and I press replace or replace all, no null value is found, so I can't replace anything. However, when I press Find Next in that same dialog then the null values are found. Anyone and idea what is happening here? Thanks, john
1
1505
by: nasse | last post by:
Need some one to help me in doing a find and replace task for all the files in my application. I have a list of pairs of old values in one file (findFile.php) and wanted to replace them with different values that are store in second file (replaceFile.php): findFile.php: , "abdomen", "Abdomen"; , "afternoon", "Afternoon"; , "almost always", "Almost Always"; , "almost never", "Almost Never"; , "always", "Always"; , "bursitis",...
2
1575
by: wolverine2512 | last post by:
Hi all! I want to replace the values of QID in my datalist1 bound with the following data: Dim sqlStmnt As String = "Select QID, QUESTION from ENVIRONMENTAL_EXAM order by newid() " Dim myda As SqlDataAdapter = New SqlDataAdapter(sqlStmnt, scon) Dim ds As New DataSet
2
11685
by: X l e c t r i c | last post by:
Here: http://bigbangfodder.fileave.com/res/sandr.html I'm trying to use string.replace() for a basic search and replace form using textarea values as the regexp and replacement values for string.replace(). When I tried to use the textarea variable name for regexp it didn't work as I thought it would. For example:
0
9535
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10465
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10242
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10021
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6800
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5453
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4127
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3744
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.