I am writing a program here that takes two int[] arrays and subtracts each element from each other and stores the result in a new array.
this sounds pretty sound and i know my math is right seeing as its simple subtraction..
my method is here,
public int[] diff(int[] nums1, int[] nums2)
{
int[] diffArray = new int [nums1.length];
int tempValue = 0;
int tempValue2 = 0;
int subtract = 0;
if (nums1.length != nums2.length)
{
diffArray = new int[0];
}
else
{
for (int i = 0; i < nums1.length && i < nums2.length; ++i)
{
tempValue = nums1[i];
tempValue2 = nums2[i];
System.out.println("temp value 1: " + tempValue); //just me trying to debug
System.out.println("temp value 2: " + tempValue2); //just me trying to debug
subtract = tempValue2 - tempValue;
System.out.println("Subtracted :" + subtract); //just me trying to debug
diffArray[i] = subtract;
}
}
return diffArray;
}
to test this i wrote a couple small pieces of code in my driver class.
The problem is, i made those 3 debug print statements in my for loop to see if i had the right numbers and everything is correct it just seems like its not storing it in diffArray?
for example,
//Array of 1 element each : r(0)
givenArray = new int[] {4};
givenArray2 = new int[] {4};
diffValue = srvObj.diff(givenArray, givenArray2);
result = (diffValue == new int[] {0}) ? PASS : FAIL;
System.out.println(testNum + ": " + result);
++testNum;
//Array of multi-elements each that are diff : r({6, 10, 37})
givenArray = new int[] {4, 5, 3};
givenArray2 = new int[] {10, 15, 30};
diffValue = srvObj.diff(givenArray, givenArray2);
result = (diffValue == new int[] {6, 10, 37}) ? PASS : FAIL;
System.out.println(testNum + ": " + result);
++testNum;
note : i am subtracting array2 from array1 not the other way.
however i keep getting FAIL every time? i can see in my print statements its done the math for each element
Surely there must be a problem when i try to give diffArray[i] the resulted subtraction?
You are checking for array equality incorrectly here (and your other tests):
result = (diffValue == new int[] {0}) ? PASS : FAIL;
In Java the == operator checks for reference equality when applied to objects, and the new array you create in this statement will never be the same object as diffValue.
What you need to do is to use the equals() method in the Arrays class, which checks for value equality.
A quick example:
int[] arr1 = { 0 };
int[] arr2 = { 0 };
System.out.println(arr1 == arr2); // false
System.out.println(Arrays.equals(arr1, arr2)); // true
In Java (and a lot of other languages), arrays are objects, so == won't work to compare them. It compares the references, so it checks if they're the same object, not whether they contain the same elements:
int[] a = new int[] {1,2,3};
a == a; //true
int[] b = new int[] {1,2,3};
a == b; //false
There's a method, though, Arrays.equals(), that can compare them:
result = Arrays.equals(diffValue, new int[] {0}) ? PASS : FAIL;
You need to import Arrays at the beginning of your program, though:
import java.util.Arrays;
It looks like your diff() is working, though.
Your test condition is wrong - diffValue == new int[] {6, 10, 37} will always resolve to false because the Java equality operator checks that the two variables are REALLY the same thing, not simply equivalent. Please see Comparing two integer arrays in java for ideas on comparing int arrays.
Related
This question already has answers here:
Comparing arrays in JUnit assertions, concise built-in way?
(8 answers)
Closed 4 years ago.
This is probably a really bad way of writing code but heres a program that calculates the total of each row and print it all in brackets.
public static int[] rowsSums(int[][] array) {
int[][] numArray = {
{3, -1, 4, 0},
{5, 9, -2, 6},
{5, 3, 7, -8}
};
int rowTotal = 0;
int row2Total = 0;
int row3Total = 0;
for (int i = 0; i < numArray[0].length; i++) {
rowTotal += numArray[0][i];
row2Total += numArray[1][i];
row3Total += numArray[2][i];
}
System.out.println("(" + rowTotal + "," + row2Total + "," + row3Total + ")");
return null;
}
The output without JUnit is:
(6,18,7)
I am in the process of testing this with JUnit and my code for this:
#Test
public void rowsSums() {
int [] i = new int [] {6, 18, 7};
assertEquals(i, Exercise2.rowsSums(numArray));
}
Yes, I know my output is not supposed to be null because JUnit hates it. What other variable can I return without making JUnit fail or spit an error?
I have to keep these as it is
public static int[] rowsSums(int[][] array) {
int[][] numArray = {
UPDATE: No matter what I try, JUnit always comes up with this error PrntScrn of Error
To return the int[] containing the sums, you'd do
return new int[] { rowTotal, row2Total, row3Total };
That's something you can assert as well then
assertArrayEquals(i, Exercise2.rowsSums(numArray));
Note that it is good practice to separate calculation and output, ie you should move the System.out.println to another function accepting the returned array as a parameter.
If your method is designed to just print a message and not return anything, you should declare its return type to be void.
public static void rowsSums(int[][] array) { ...
Then just remove the return statement.
However, based on your test case, it looks like you want to return an array containing the values that you calculated. Instead of having three internal variables to hold totals (rowTotal, row2Total, and row3Total), those variables could be combined into one array where the totals are stored, then returned.
I think that your method should return the computation performed and not only print a message otherwise you would not have a clear way to test your method.
Besides method names should be verbs/actions and not common names.
So sum() would be clearer.
You could return the sum array of each row in your method and assert the result in your unit test :
public static int[] sum(int[][] array) {
...
return new int[] {rowTotal, row2Total, row3Total};
}
And in your test :
int[] sumExpected = ...
Assert.assertArrayEquals(sumExpected, Exercise2.sum(numArray));
If you will return array as a result you will be able to use it in your jUnit test and compare expected result with actual.
System.out.println("(" + rowTotal + "," + row2Total + "," + row3Total + ")");
int [] result = new int[3];
result[0] = rowTotal;
result[1] = row2Total;
result[2] = row3Total;
return result;
Why do you pass int[][] array to the method, but literally never do anything with it at all?... I'm going to assume you want to use that array structure you passed in order to count each of it's arrays (rows). You also should never mix output with functions. You should return the String, then print it in your main method. As #bill-the-Lizard said, you want to have an array in which holds the row's values and then you would just return an int[] array which contains the rows' counts. You would then have a for loop in your current one which would input the counts into their corresponding array key.
int[][] numArray = {
{3, -1, 4, 0},
{5, 9, -2, 6},
{5, 3, 7, -8}
};
public static int[] rowsSums(int[][] array) {
int[] sum = new int[array.length];
for (int i=0;i<sum.length; i++)
sum[i] = 0;
for (int i = 0; i < sum.length; i++) {
for(int j=0; j< array[i].length; j++)
sum[i] += array[i][j];
}
return sum;
}
int[] result = rowsSums(numArray);
I'm having trouble with the code in my else statement. I can't figure out how to make it recursively return the 2 adjusted items in the list. I would appreciate any help.
public static int[] fibaux(int n) {
if (n == 1) {
return new int[] {1, 0};
}
else {
int[] array = new int[2];
list[] = {fibaux(n - 1)};
return //array[0] + array[1], array[1];
}
}
Multi-value returns are not allowed in Java i.e., you can not return 2 values using the return. You can simply return an array containing the two values like this:
return new int[] {num1, num2};
I think what you're looking for doesn't involve doing the recursion as part of the return. You want to do the recursion, and then return an array that is the addition of the two elements, along with the one element you want to keep.
I think you want:
public static int[] fibaux(int n) {
if (n == 1) {
return new int[] {1, 0};
}
else {
int[] array = fibaux(n - 1);
return new int[] {array[0]+array[1], array[0]};
}
}
Given 2 int arrays, a and b, return a new array length 2 containing, as much as will fit, the elements from a followed by the elements from b. The arrays may be any length, including 0, but there will be 2 or more elements available between the 2 arrays.
I'm wondering how to use a !=, and null. This is the first question I've used it in and I'm having a few errors.
So my logic was to iterate through list a, until a null point, then go onto list b.
public int[] make2(int[] a, int[] b) {
int[] answer = new int[2];
for(int x = 0; x <= 1; x++){
if(a[x] != null)
answer[x] = a[x];
else if (b[x != null]){
answer[x] = b[x];
}
}
}
Something like this. Any tips on how to check for emptiness?
else if (b[x != null]){
Is not a valid statement, this will cause an error because (x != null) = true so is the same as else if (b[true]){ which does not make much sense.
Also, an empty array position of int will never be null but zero 0 instead.
Use this instead:
else if (b[x] != 0){
One more thing: as title says, use List to instead of array to have a variable number of elements:
public int[] make2(int[] a, int[] b) {
List<Integer> answers = new ArrayList<Integer>();
for(int x = 0; x <= 1; x++){
if(a[x] != 0) {
answers.add(a[x]);
} else if (b[x] != 0) {
answers.add(b[x]);
}
}
}
NOTES:
use answers instead of answer, is better name for a List with multiple elements.
take as usual to use ALWAYS { even if the statements inside are just one line
your function is not valid since does not include return answer
EDIT
Sorry about the title, my mistake. It is arrays
In this case, just remember arrays are not resizeable, so in the moment of creating the array check maximum size:
int maxSize = a.length > b.length ? a.length : b.length;
int[] answer = new int[maxSize];
NOTE: you can use this variable in your loop to check max number...
EDIT2
An empty array position is represented by a 0? What about the example make2({}, {1, 2}) → {1, 2}, will a[0] != 0 skip it? because index 0 doesn't exist?
you cannot use make2({}, {1, 2}), not a valid statement in this case. To simulate this do:
public static void main(String[] args) {
int a[] = new int[2];
int b[] = new int[2];
b[0] = 1;
b[1] = 2;
make2(a,b);
// if you want to see the output:
System.out.println(Arrays.toString(make2(a,b)));
}
It won't skip it, it will throw an ArrayIndexOutOfBoundsException, in this case, you must make you function failsafe, for this, just check lenghts before accessing the element to assert it will exist:
public static int[] make2(int[] a, int[] b) {
int[] answer = new int[2];
for(int x = 0; x <= 1; x++){
if(a.length >= x && a[x] != 0) {
answer[x] = a[x];
} else if (b.length >= x && b[x] != 0){
answer[x] = b[x];
}
// optional
else {
answer[x] = -1; // this tells you there's no valid element!
}
}
return answer;
}
SOLUTION:
http://www.codingbat.com/prob/p143461 Here is a url to the question :D
Ok, you were missing the examples, all would be much clearer... This code pass all tests.
public int[] make2(int[] a, int[] b) {
int[] answer = new int[2]; // create the array to fill
int y = 0; // create a variable to check SECOND array position
for(int x = 0; x <= 1; x++){ // make 2 iterations
if(a.length > x) { // if ARRAY a has a possible value at POSITION x
answer[x] = a[x]; // put this value into answer
} else if (b.length > y){ // if ARRAY a does not have possible value at POSITION x,
// check if ARRAY b has some possible value at POSITION y
// (remember y is the variable that keeps position of ARRAY b)
answer[x] = b[y++]; // put b value at answer
}
}
return answer; // return answer
}
You can check array if it string but your array is int. so you can use the following example
int arr[] = null;
if (arr != null) {
System.out.println("array is null");
}
arr = new int[0];
if (arr.length != 0) {
System.out.println("array is empty");
}
I have a few questions, before I suggest you some alternatives. 1. why are you declaring int[] answer = new int[2]; when question says 2 or more elements.
You should use :
List<int> stockList = new ArrayList<int>();
if(a[x] != null)
stockList.add(a[x]);
else if (b[x] != null){
stockList.add(b[x]);
}
int[] stockArr = new int[stockList.size()];
stockArr = stockList.toArray(stockArr);
Background: Very new at Java, have little understanding. Would prefer a "point in the right direction" with explanation, if possible, than a copy/paste answer without explanation. If I want to stop being a novice, I need to learn! :)
Anyway, my goal is, as simply as possible, to be given 2 arrays numberList and winningNumbers, compare them, and return the percentage that numberList matches winningNumbers. Both array lengths will always be 10.
I have no idea where to start. I have been googling and going at this for 2 hours. My idea is to write a for loop that compares each individually integer in a string to one in the other, but I am not sure how to do that, or if there is a simpler method. I have little knowledge of arrays, and the more I google the more confused I become.
So far the only thing I have is
public double getPercentThatMatch(int[] winningNumbers) {}
numberList is preset.
one way you could approach it is to:
1) convert both lists to sets.
2) subtract one from the other. ie if 4 are the same, the resulting set will have the 6 values not the same
3) 10 - (size of resulting set) * 100 = %
Here's a runnable example of how you would compare the two arrays of ints to get a percent match.
public class LotteryTicket {
int[] numberList;
LotteryTicket(int... numbers) {
numberList = numbers;
}
public int getPercentThatMatch(int[] winningNumbers) {
Arrays.sort(numberList);
Arrays.sort(winningNumbers);
int i = 0, n = 0, match = 0;
while (i < numberList.length && n < winningNumbers.length) {
if (numberList[i] < winningNumbers[n]) {
i++;
} else if (numberList[i] > winningNumbers[n]) {
n++;
} else {
match++;
i++;
n++;
}
}
return match * 100 / winningNumbers.length;
}
public static void main(String[] args)
{
int[] winningNumbers = { 12, 10, 4, 3, 2, 5, 6, 7, 9, 1 };
LotteryTicket ticket = new LotteryTicket(5, 2, 6, 7, 8, 4, 3, 1, 9, 0);
int percentMatching = ticket.getPercentThatMatch(winningNumbers);
System.out.println(percentMatching + "%");
}
}
Output:
80%
Since you wanted to be pointed in the right direction, rather than havving proper code, and assuming you want to use arrays to solve the problem, try to put something like this in your method:
(loop through arrayA){
(loop through arrayB){
if (current arrayA number is equal to current arrayB number){
then increase match counter by one, since this exists.
also break out of current arrayB loop. (Check next arrayA now.)
}
}
}
When done: return 100*matchCount/totalCount, as a double
So for every index in one array, you check against every other index of the other array. Increase a counter each time there's a match, and you'll be able to get a ratio of matches. If you use an integer as a counter, remember that division with integers acts funky, so you'd need to throw to a double:
double aDoubleNumber = (double) intNumber / anotherIntNumber
The problem would be easier if we consider them set. Let you have two set -
Set<Integer> s1 = //a HashSet of Integer;
Set<Integer> s2 = //a HashSet of Integer;
Now make a copy of s1 for example s11 and do the following thing -
s1.retainAll(s2);
Now s1 contains only element of both sets - that is the intersection.
After that you can easily calculate the percentage
Edit: You can convert the array to a set easily by using the following code snippet (I am assuming you have array of int) -
Set<Integer> s1 = new HashSet<Integer>(Arrays.asList(somePrimiteiveIntArray));
I think this trick will works for other primitive type also.
Hope this will help.
Thanks a lot.
I am going to attempt to beat a dead horse and explain the easiest (conceptual) way to approach this problem I will include some code but leave a lot up to interpretation.
You have two arrays so I would change the overall method to something like this:
public double getPercentage(int[] arrayA, int[] arrayB) {
double percentage=0;
for(/*go through the first array*/) {
for(/*go through second array*/) {
if(arrayA[i]==arrayB[j]) { /*note the different indices*/
percentage++; /*count how many times you have matching values*/
/* NOTE: This only works if you don't have repeating values in arrayA*/
}
}
}
return (percentage/arrayA.length)*100; /*return the amount of times over the length times 100*/
}
You are going to move through the first array with the first loop and the second array with the second loop. So you go through every value in arrayB for each value in arrayA to check.
In my approach I tried storing the winning numbers in a Hashset (one pass iteration, O(n) )
And when iterating on the numberList, I would check for presence of number in Hashset and if so, I will increment the counter. (one pass iteration, so O(n) )
The percentage is thus calculated by dividing the counter with size of array.
See if the sample code makes sense:
import java.util.HashSet;
public class Arraycomparison {
public static void main(String ... args){
int[] arr0 = {1,4,2,7,6,3,5,0,3,9,3,5,7};
int[] arr1 = {5,2,4,1,3,7,8,3,2,6,4,4,1};
HashSet set = new HashSet();
for(int j = 0; j < arr1.length; j++){
set.add(arr1[j]);
}
double counter = 0;
for(int i = 0; i < arr0.length; i++){
if(set.contains(arr0[i])){
counter++;
}
}
System.out.println("Match percentage between arrays : " + counter/arr0.length*100);
}
}
You should use List over array, because that's a convenient way, but with array:
public class Winner {
public static void main(String... args) {
double result = getPercentThatMatch(new int[]{1,2,3,4,5}, new int[]{2,3,4,5,6});
System.out.println("Result="+result+"%");
}
public static double getPercentThatMatch(int[] winningNumbers,
int[] numberList) { // it is confusing to call an array as List
int match = 0;
for (int win : winningNumbers) {
for (int my : numberList ){
if (win == my){
System.out.println(win + " == " + my);
match++;
}
}
}
int max = winningNumbers.length; // assume that same length
System.out.println("max:"+max);
System.out.println("match:"+match);
double devide = match / max; // it won't be good, because the result will be intm so Java will trunc it!
System.out.println("int value:"+devide);
devide = (double) match / max; // you need to cast to float or double
System.out.println("float value:"+devide);
double percent = devide * 100;
return percent;
}
}
Hope this helps. ;)
//For unique elements
getpercentage(arr1, arr2){
res = arr1.filter(element=>arr2.includes(element))
return res.lenght/arr2.lenght * 100;
}
//For duplicate elements
getpercentage(arr1, arr2){
const setA = Set(arr1);
const setB = Set(arr2);
Let res = [ ];
for(let i of setB){
if(setA.has(i)){
res.push(i);
}
}
return res.lenght/setA.size* 100;
The following Java code:
public static void main(String args[]) {
int[] x = new int[] {1, 2, 3};
int[] y = new int[] {1, 2, 3};
LinkedList<int[]> list = new LinkedList<int[]>();
list.add(x);
System.out.println("List contains y: " + list.contains(y));
}
gives the output
List contains y: false
which makes sense as x and y are references to different memory locations, however there is also a sense in which they are equal (they have the the same elements in the same order).
Is there a data structure which would return true to the query list.contains(y) in this example?
I don't believe there is a Java data structure that would return true for contains() as you have described.
The issue, as you probably know, is that for Java arrays, equals() only tests for Object identity and not "equality" as most would define it.
Since contains() relies on equals() in this case (and most of the time), you're stuck with the given behaviour.
You would have to implement a List that specifically overrode contains() to provide your desired behaviour for Java arrays, probably using Arrays.equals().
My suggestion is to instead use a List instead of an array; you'd then have a List<List<Integer>>. contains() should work in this scenario as it'll use equals() on the underyling List implementation.
You need to define a comparator for your arrays. Then when the list looks up the elements, it will use your comparator to see if they're the same:
public static void main(String args[]) {
int[] x = new int[] {1, 2, 3};
int[] y = new int[] {1, 2, 3};
LinkedList<int[]> list = new LinkedList<int[]>(new Comparator<int[]>() {
#Override
public int compare(int[] a1, int[] a2) {
if(a1 == a2) return 0;
if(a1 == null && a2 != null) return -1;
if(a1 != null && a2 == null) return 1;
if(a1.size() < a2.size()) return -1;
if(a1.size() > a2.size()) return 1;
for(int i = 0; i < a1.size(); i++) {
int comp = a1[i] - a2[i];
if(comp < 0) return -1;
if(comp > 0) return 1;
}
return 0;
}
});
list.add(x);
System.out.println("List contains y: " + list.contains(y));
}
It looks like you're really looking for a Set implementation.
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied
by its name, this interface models the mathematical set abstraction.
If you want to store sets of int values, you can use this Tuple class I wrote a while ago for another question on SO.
Set<Tuple> myTuples = new HashSet<Tuple>();
Tuple<Integer> x = Tuple.create(1, 2, 3);
Tuple<Integer> y = Tuple.create(1, 2, 3);
myTuples.add(x);
System.out.println("Set contains y: " + myTuples.contains(y)); // prints true
If order matters, you can use a SortedSet.
LinkedList uses equals to implement contains, so this should work:
public static void main(String args[]) {
static class Ints {
int[] array;
public Ints(int[] array) {
this.array = array;
}
public boolean equals(Object other) {
if (other instanceof Ints) {
return arraysEqual((Ints) other);
}
}
public boolean arraysEqual(Ints other) {
// check that this.array and other.array are same length and
// have same values. Do a null check somewhere too. :)
}
}
Ints x = new Ints(new int[] {1, 2, 3});
Ints y = new Ints(new int[] {1, 2, 3});
LinkedList<Ints> list = new LinkedList<int[]>();
list.add(x);
System.out.println("List contains y: " + list.contains(y));
}
You would probably want to extend LinkedList into your own custom data structure and define a custom equality method if you wanted anything outside of the standard checking that is in place.
If you could use a Set instead of an array it might be easier. Have a look here or here