Given this contract for the method swapNN: 1 2 3 4 5 6 7 8 9 10 11 12 /** * Swap
ID: 3669747 • Letter: G
Question
Given this contract for the method swapNN:
1
2
3
4
5
6
7
8
9
10
11
12
/**
* Swaps the two given {@code NaturalNumber}s.
*
* @param n1
* the first {@code NaturalNumber}
* @param n2
* the second {@code NaturalNumber}
* @updates n1
* @updates n2
* @ensures n1 = #n2 and n2 = #n1
*/
private static void swapNN(NaturalNumber n1, NaturalNumber n2) {...}
Implement the swapNN method using copyFrom (and not transferFrom).
Provide a second implementation for the swapNN method specified above using transferFrom (and not copyFrom)
1
2
3
4
5
6
7
8
9
10
11
12
/**
* Swaps the two given {@code NaturalNumber}s.
*
* @param n1
* the first {@code NaturalNumber}
* @param n2
* the second {@code NaturalNumber}
* @updates n1
* @updates n2
* @ensures n1 = #n2 and n2 = #n1
*/
private static void swapNN(NaturalNumber n1, NaturalNumber n2) {...}
Explanation / Answer
import components.naturalnumber.NaturalNumber;
public class Main {
/**
* Swaps the two given {@code NaturalNumber}s.
*
* @param n1
* the first {@code NaturalNumber}
* @param n2
* the second {@code NaturalNumber}
* @updates n1
* @updates n2
* @ensures n1 = #n2 and n2 = #n1
*/
private static void swapNN(NaturalNumber n1, NaturalNumber n2) {
NaturalNumber temp = n1;
n2.copyFrom(n1);
n1.copyFrom(temp);
}
/**
* Swaps the two given {@code NaturalNumber}s.
*
* @param n1
* the first {@code NaturalNumber}
* @param n2
* the second {@code NaturalNumber}
* @updates n1
* @updates n2
* @ensures n1 = #n2 and n2 = #n1
*/
private static void swapNN2(NaturalNumber n1, NaturalNumber n2) {
NaturalNumber temp = n1;
n2.transferFrom(n1);
n1.transferFrom(temp);
}
/**
* Squares a given {@code NaturalNumber}.
*
* @param n
* the number to square
* @updates n
* @ensures n = #n * #n
*/
private static void square(NaturalNumber n) {
n.multiply(n);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.