Why is this integer not incrementing twice? [duplicate] - c#-4.0

This question already has answers here:
C# Increment operator (++) question:Why am i getting wrong output?
(5 answers)
Closed 8 years ago.
I am confused by the results of the code below. Why does 'b' retain a seemingly incorrect value when doing these operations?
int a = 0;
int b = 5;
a = b++;
b = b++;
Console.WriteLine("For b = b++; b=" + b.ToString()); // b should be 7 but it's 6
a = 0;
b = 5;
a = b--;
b = b--;
Console.WriteLine("For b = b--; b=" + b.ToString()); // b should be 3 but it's 4
a = 0;
b = 5;
a = b + 1;
b = b + 1;
Console.WriteLine("For b = b++; b=" + b.ToString());
Output
b=6
b=4
b=6
Can anyone explain this behavior in C# and how it's working?

That's indeed the behavior of postfix operators, as detailed here.
For instance, when you write:
b = b++;
The following happens:
The current value of b is saved,
b is incremented,
The saved value of b is produced by the postfix ++ operator,
The value produced by the operator is assigned to b.
Therefore, b will indeed be assigned its original value, and the incremented value is lost.

Because the ++ and -- operators when placed after the value will evaluate to the value itself, and then increment/decrement the value after the evaluation.
So:
int a = 0;
int b = a++;
After running this code, b will equal 0 and a will equal 1.
This is as opposed to using the operators as prefixes:
int a = 0;
int b = ++a;
After running this code, b will equal 1 and a will equal 1.
This is documented behavior and has been around for a long time.

The instruction a=b++ is stored on the stack but not evaluated because it was not used after that.
To get the correct result, make that instruction have a sense fro example change that line:
Console.WriteLine("For b = b++; b=" + b.ToString());
by that one:
Console.WriteLine("For a = b++; a=" + a.ToString());
Console.WriteLine("For b = b++; b=" + b.ToString()); //should give 7

When you use
int a = 0;
int b = 5;
a = b++;
b = b++;
You set a to be 6, and after that you set b to be 6.
When you write b to commandline, it presents 6 because a was never used when incrementing b.
If you want to use a as well, you'd have to make
int a = 1;
int b = 5;
b = b++;
b += a;
Console.WriteLine("For b = a + b++; b=" + b.ToString());
But overall I don't see any use in this kind of incrementation.

Related

Get If (condition), then (assign value), else (assign other value) statement in Linear Programming

I'm looking for a linear programming equation that satisfied the conditions;
Given that all variables here are binary variables
if A+B = 2; then C = 1; else C = 0
Also,
if A+B+D = 3; then E = 1; else E = 0
How would one phrase this and satisfy these conditions as well as linearity conditions?
I've tried
A + B - 2 <= M(1-y) and 1 - C <= My
for the first constraint but it doesn't seem to work
For the first equation, you can use:
C + 1 >= A + B
2C <= A + B
If there is a natural sense (max/min) for C in the problem, one of those is sufficient.
Similarly for the second:
E + 2 >= A + B + D
3E <= A + B + D

Problem with spec block in literate haskell file

I have this block of code on my literate haskell file
\end{code}
\paragraph{Valorização}
Codigo em C
\begin{spec}
double co(double x, int n){
double a = 1;
double b = -1 * x * x / 2;
double c = 12;
double d = 18;
for(; n > 0; n--){
a = a + b;
b = b * (-1 * x * x) / c;
c = c + d;
d = 8 + d;
}
return a;
}
\end{spec}
\subsection*{Problema 4}
What's happening is, when using lhs2tex and the pdflatex, what's inside the spec block is being completely ignored, and everything after it is forward, like it has a tab before it... Maybe this is something common? I'm not used to this... First time using it
By the way, if I remove the spec block everything else is formatted correctly
The following answer is based on speculation. If you would provide an MCVE—a short .lhs file that clearly demonstrates the issue—perhaps a better answer could emerge.
I think the issue is that lhs2TeX is not meant for C code. It gets confused by the spec block, thinks that it is Haskell code, and outputs problematic TeX commands. In fact, I can't even get your posted code past pdflatex—the .tex is that broken. You can use a different mechanism to output C code. The minted package should do.
\documentclass{article}
%include lhs2TeX.fmt
\usepackage{minted}
\setlength{\parindent}{0pt}
\begin{document}
Some C code:
\begin{minted}{c}
double co(double x, int n){
double a = 1;
double b = -1 * x * x / 2;
double c = 12;
double d = 18;
for(; n > 0; n--){
a = a + b;
b = b * (-1 * x * x) / c;
c = c + d;
d = 8 + d;
}
return a;
}
\end{minted}
It can be directly translated into Haskell:
\begin{code}
co :: Double -> Int -> Double
co x = worker 1 (-1 * x * x / 2) 12 18
where worker a _ _ _ 0 = a
worker a b c d n = worker (a + b) (b * (-1 * x * x) / c) (c + d) (8 + d) (n - 1)
\end{code}
As you can see, \textit{Haskell} code passes through just fine.
\end{document}
PS: The weird for-loop can be written while(n-- > 0) { ... }, no?

adding strings as numbers

I'm trying to add together two large numbers, stored as strings.
Here's what I have so far:
function addBigNums(a,b){
c = ""; // output
o = 0; // carryover
startLen = a.length-1;
for(i = startLen; i >= 0; i--) {
sum = parseInt(a[i], 10) + parseInt(b[i], 10) + o;
c = (sum % 10) + c;
o = sum >= 10;
}
if(o === true) c = "1" + c;
return c;
}
I'm running into two issues:
1 ) my carry is not always functioning properly, primarily when:
2 ) the numbers length differ.
Right now I think I would have to prepend 0's onto the shorter number in order to get this to function as expected.
Any better alternatives to this?
Simple, straightforward integer addition like you would do it manually:
a = "123456"; // input a
b = "123456"; // input b
c = ""; // target-string
o = 0; // overflow-bit
// traverse string from right to left
for(i = a.length - 1; i >= 0; i--) {
// do the calculation (with overflow bit)
sum = parseInt(a[i]) + parseInt(b[i]) + o;
// prepend resulting digit to target
c = (sum % 10) + c;
// set overflow bit for next round
o = sum >= 10;
}
// prepend another "1" if last overflow-bit is true
if(o == true) c = "1" + c;
If strings a and b are not equal length (but you stated that they are), you should prepend the shorter string with zeros before calculation.
Consider both numbers to be an array of digits. Add them up right-to-left handling overflow flag. Demo. Assuming your numbers are of the same length
function getNumber(len) {
return Array.apply(null, new Array(len)).map(function(){
return Math.floor(Math.random()*9);
}).join('');
}
var len = 600,
a = getNumber(len), //use your numbers here
b = getNumber(len),
flag = 0;
var c = [].reduceRight.call(a, function(acc, val, idx) {
val = +val + (+b.charAt(idx)) + flag;
flag = val / 10 | 0;
val %= 10;
return val + acc;
}, '');
c = (flag ? 1: '') + c;
console.log(a, b, c);

Generate all compositions of an integer into k parts

I can't figure out how to generate all compositions (http://en.wikipedia.org/wiki/Composition_%28number_theory%29) of an integer N into K parts, but only doing it one at a time. That is, I need a function that given the previous composition generated, returns the next one in the sequence. The reason is that memory is limited for my application. This would be much easier if I could use Python and its generator functionality, but I'm stuck with C++.
This is similar to Next Composition of n into k parts - does anyone have a working algorithm?
Any assistance would be greatly appreciated.
Preliminary remarks
First start from the observation that [1,1,...,1,n-k+1] is the first composition (in lexicographic order) of n over k parts, and [n-k+1,1,1,...,1] is the last one.
Now consider an exemple: the composition [2,4,3,1,1], here n = 11 and k=5. Which is the next one in lexicographic order? Obviously the rightmost part to be incremented is 4, because [3,1,1] is the last composition of 5 over 3 parts.
4 is at the left of 3, the rightmost part different from 1.
So turn 4 into 5, and replace [3,1,1] by [1,1,2], the first composition of the remainder (3+1+1)-1 , giving [2,5,1,1,2]
Generation program (in C)
The following C program shows how to compute such compositions on demand in lexicographic order
#include <stdio.h>
#include <stdbool.h>
bool get_first_composition(int n, int k, int composition[k])
{
if (n < k) {
return false;
}
for (int i = 0; i < k - 1; i++) {
composition[i] = 1;
}
composition[k - 1] = n - k + 1;
return true;
}
bool get_next_composition(int n, int k, int composition[k])
{
if (composition[0] == n - k + 1) {
return false;
}
// there'a an i with composition[i] > 1, and it is not 0.
// find the last one
int last = k - 1;
while (composition[last] == 1) {
last--;
}
// turn a b ... y z 1 1 ... 1
// ^ last
// into a b ... (y+1) 1 1 1 ... (z-1)
// be careful, there may be no 1's at the end
int z = composition[last];
composition[last - 1] += 1;
composition[last] = 1;
composition[k - 1] = z - 1;
return true;
}
void display_composition(int k, int composition[k])
{
char *separator = "[";
for (int i = 0; i < k; i++) {
printf("%s%d", separator, composition[i]);
separator = ",";
}
printf("]\n");
}
void display_all_compositions(int n, int k)
{
int composition[k]; // VLA. Please don't use silly values for k
for (bool exists = get_first_composition(n, k, composition);
exists;
exists = get_next_composition(n, k, composition)) {
display_composition(k, composition);
}
}
int main()
{
display_all_compositions(5, 3);
}
Results
[1,1,3]
[1,2,2]
[1,3,1]
[2,1,2]
[2,2,1]
[3,1,1]
Weak compositions
A similar algorithm works for weak compositions (where 0 is allowed).
bool get_first_weak_composition(int n, int k, int composition[k])
{
if (n < k) {
return false;
}
for (int i = 0; i < k - 1; i++) {
composition[i] = 0;
}
composition[k - 1] = n;
return true;
}
bool get_next_weak_composition(int n, int k, int composition[k])
{
if (composition[0] == n) {
return false;
}
// there'a an i with composition[i] > 0, and it is not 0.
// find the last one
int last = k - 1;
while (composition[last] == 0) {
last--;
}
// turn a b ... y z 0 0 ... 0
// ^ last
// into a b ... (y+1) 0 0 0 ... (z-1)
// be careful, there may be no 0's at the end
int z = composition[last];
composition[last - 1] += 1;
composition[last] = 0;
composition[k - 1] = z - 1;
return true;
}
Results for n=5 k=3
[0,0,5]
[0,1,4]
[0,2,3]
[0,3,2]
[0,4,1]
[0,5,0]
[1,0,4]
[1,1,3]
[1,2,2]
[1,3,1]
[1,4,0]
[2,0,3]
[2,1,2]
[2,2,1]
[2,3,0]
[3,0,2]
[3,1,1]
[3,2,0]
[4,0,1]
[4,1,0]
[5,0,0]
Similar algorithms can be written for compositions of n into k parts greater than some fixed value.
You could try something like this:
start with the array [1,1,...,1,N-k+1] of (K-1) ones and 1 entry with the remainder. The next composition can be created by incrementing the (K-1)th element and decreasing the last element. Do this trick as long as the last element is bigger than the second to last.
When the last element becomes smaller, increment the (K-2)th element, set the (K-1)th element to the same value and set the last element to the remainder again. Repeat the process and apply the same principle for the other elements when necessary.
You end up with a constantly sorted array that avoids duplicate compositions

AS2: How to iterate X times through a percentage calculation (containing a circular reference)?

Here is a question for the Excel / math-wizards.
I'm having trouble doing a calculation which is based on a formula with a circular reference. The calculation has been done in an Excel worksheet.
I've deducted the following equations from an Excel file:
a = 240000
b = 1400 + c + 850 + 2995
c = CEIL( ( a + b ) * 0.015, 100 )
After the iterations the total of A+B is supposed to be 249045 (where b = 9045).
In the Excel file this gives a circular reference, which is set to be allowed to iterate 4 times.
My problem: Recreate the calculation in AS2, going through 4 iterations.
I am not good enough at math to break this problem down.
Can anyone out there help me?
Edit: I've changed the formatting of the number in variable a. Sorry, I'm from DK and we use period as a thousand separator. I've removed it to avoid confusion :-)
2nd edit: The third equation, C uses Excels CEIL() function to round the number to nearest hundredth.
I don't know action script, but I think you want:
a = 240000
c = 0
for (i = 0; i < 4; i++){
b = 1400 + c + 850 + 2995
c = (a + b) * 0.015
}
But you need to determine what to use for the initial value of c. I assume that Excel uses 0, since I get the same value when running the above as I get in Excel with iterations = 4, c = 3734.69...
Where do you get the "A + B is supposed to be 249045" value? In Excel and in the above AS, b only reaches 8979 with those values.
function calcRegistrationTax( amount, iterations ) {
function roundToWhole( n, to ) {
if( n > 0 )
return Math.ceil( n/ to ) * to;
else if( n < 0)
return Math.floor( n/ to ) * to;
else
return to;
}
var a = amount;
var b = 0;
var c = 0
for (var i = 0; i < iterations; i++){
b = basicCost + ( c ) + financeDeclaration + handlingFee;
c = ( a + b ) * basicFeeRatio;
c = roundToWhole( c, 100 );
}
return b;
}
totalAmount = 240000 + calcRegistrationTax( 240000, 4 ); // This gives 249045
This did it, thanks to Benjamin for the help.

Resources