I was given a homework assignment to check if all the elements of an array are the same value. I return true if they are, otherwise I return false. I was instructed to return true if the array was empty. The following code works in all cases except when the array has no elements - a length of zero. How could I go about addressing this issue?
public static boolean allSame (double[] list) {
double sameReference = list[0];
for (int i = 0; i < list.length; i++) {
if (list [i] != sameReference)
return false;
}
return true;
}
Just add an empty check
public static boolean allSame (double[] list) {
if (list.length() == 0){
return true;//list empty so return true
}
double sameReference = list[0];
for (int i = 0; i < list.length; i++) {
if (list [i] != sameReference)
return false;
}
return true;
}
Related
I am looking to return true if all the elements in A are found within B and false otherwise. Currently, I have written the code below but the function seems to only return false.
public static boolean con(int[] a, int[] b) {
if (a == null || a.length == 0) {
return false;
}else if (b == null || b.length == 0) {
return false;
}
for (int i = 0; i < a.length; i++)
{
for (int j = i + 1; j < b.length;j++)
{
if (a[i] == (b[j])) {
return true;
}
}
}
return false;
}
It is easy to make mistakes when you program with indices. Luckily, in this case there is no need to do that:
public static boolean con(int[] a, int[] b) {
loop: for (int ai : a) {
for (int bi : b) {
if (ai == bi) {
continue loop;
}
}
return false;
}
return true;
}
Always use the strengths of the language, not the weaknesses.
There are a couple of issues in your code as pointed out in the comments that are causing your code to return false, however, the other issue is that your return true if a[i] == (b[j]) which will be true and cause a return if the first element in the array is a match regardless of the rest of the array and if it matches or not.
Here is a working version with comments that help explain what has been changed:
public static boolean con(int[] a, int[] b) {
//Use a flag to track if the integers are found
Boolean flag = true;
//return false for null or 0 length
if (a == null || a.length == 0 || b == null || b.length == 0) {
return false;
}
//Check integers
for (int i = 0; i < a.length; i++){
//Use an inner flag to track each integer
Boolean innerFlag = false;
//Start the inner loop from 0 and incriment it
//Only use j = i if you need the integers to be in order?
for (int j = 0; j < b.length; j++){
if (a[i] == (b[j])) {
//we can not return from the method until all elements are checked
//so set the flag instead and break so the next element can be checked
innerFlag = true;
break;
}
}
//if an element does not exist we can set the flag false and break and return immediatly
if (innerFlag == false){
flag = false;
break;
}
}
return flag;
}
Why you use the int j = i + 1 and not just j to compare all b from the beginning of the array with j = 0... anyway if you change that and test it with two equals filled array it will give true at the first element, and if the array are different will give you true when both coincide, but you are not storing the results in any place,
I think what you could do is add a counter with the length of a:
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (a[i] == (b[j])) {
count--;
if(count == 0)
return true;
}
It kinda work, test it thoroughly and tell me.
If you really want to do it manually, you could use something like this:
private static boolean containsAll(Integer[] arrayA, Integer[] arrayB) {
Set<Integer> matches = new HashSet<>();
boolean containsAll = false;
for (int i = 0; i < arrayA.length; i++) {
for (int j = 0; j < arrayB.length; j++) {
if (arrayA[i] == arrayB[j]) {
matches.add(arrayA[i]);
}
}
}
if (matches.size() == arrayA.length) {
containsAll = true;
}
return containsAll;
}
Since a set can only store unique values, even if arrayB has duplicated elements, it will still work. It won't work if arrayA has duplicated elements, though.
I'm not the best but this is what I have so far. Whenever I change any of the elements in array1, it still holds true even if it is above a .001 threshold. Where did I go wrong?
public static boolean equals(double[] arr1, double[] arr2) {
if (arr1.length != arr2.length)
return false;
for (int i = 0; i < arr1.length; ++i) {
if ((arr1[i] - arr2[i]) < .001) {
return true;
}
}
return false;
}
public static void main(String[] args) {
question2 object = new question2();
double[] arr1 = { 95.0, 14.0, 16.5, 11.1 };
double[] arr2 = { 95.0, 12.9, 16.5, 11.1 };
System.out.println(question3.equals(arr1, arr2));
At the moment, this script will return true if ANY of the array elements are within 0.001.
You need to reverse your logic/thinking.
You want to return false if any of the array elements are NOT within 0.001.
Also consider if array 2 is greater than array 1. Their difference will be negative in that case. You probably want to take the absolute value of the difference and see if THAT is less than 0.001.
You are returning true if any value difference is less than 0.001 which is wrong as you should compare all of them
secondly, You need to compare Absolute value to check threshold as in some cases value of 2nd array can be greater than 1st so it will voilate the condition, so try this:
public static boolean equals(double[] arr1, double[] arr2) {
if (arr1.length != arr2.length)
return false;
for (int i = 0; i < arr1.length; ++i) {
if (Math.abs(arr1[i] - arr2[i]) >= .001) { // <-- Note Absolute difference
return false; //here if any value voilates the rule it should return false
}
}
return true;
}
Replace
if ((arr1[i] - arr2[i]) < .001)
With
if (Math.abs(arr1[i] - arr2[i]) < .001)
I think you have problem in your logic.You should write code like this
boolean test = true;
for (int i = 0; i < arr1.length; ++i) {
if (Math.abs((arr1[i] - arr2[i])) > .001) {
test = false;
break;
}
}
return test;
The reason being, the code is checking for the first occurrence of true scenario from the array and it is returning as True.
public static boolean equals(double[] arr1, double[] arr2) {
if (arr1.length != arr2.length)
return false;
for (int i = 0; i < arr1.length; ++i) {
if ((arr1[i] - arr2[i]) < .001) {
return true;
}
}
// Code flow will come to false return statement, only if, the 'if' condition doesn't match for all the comparison.
return false;
}
double[] arr1 = { 95.0, 14.0, 16.5, 11.1 };
double[] arr2 = { 95.0, 12.9, 16.5, 11.1 };
// Will return True on first occurrence (95.0-95.0 < .001) and the code flow goes back to the function call and print as True.
Check the below solution:
public static boolean equals(double[] arr1, double[] arr2) {
if (arr1.length != arr2.length)
return false;
boolean flag = false;
for (int i = 0; i < arr1.length; ++i) {
if (arr1[i] - arr2[i] < .001) {
flag = true;
} else {
flag = false;
break;
}
}
return flag;
}
public static boolean xIn(Stack<Integer> st, int x) throws Exception {
int result;
int size = st.getSize();
for (int i = 0; i < size; i++) {
result = st.pop();
if (x == result) {
return true;
}
st.push(result);
}
return false;
}
When you pop an item from a stack, you remove it from the top. And when you push an item to a stack, you put it on the top.
You are continually checking only the first element on the top of the stack.
Also, another thing, shouldn't you push the element back to the stack just before you return true?
You always check the last element, popping it and then pushing it again.
Use e.g. an enhanced for loop to iterate the stack.
public static boolean xIn(Stack<Integer> st, int x) throws Exception {
Stack<Integer> temp=new ArrayStack();
int result;
int size = st.getSize();
for (int i = 0; i < size; i++) {
result = st.pop();
if (x == result) {
return true;
}
temp.push(result);
}
for (int i = 0; i < size; i++) {
result=temp.pop();
st.push(result);
}
return false;
}
Try this instead:
public static boolean xIn(Stack<Integer> st, int x){
int result;
int size = st.getSize();
for (int i = 0; i < size; i++) {
if (x == st.get(i)) {
return true;
}
}
return false;
}
Also, I advice you to have a look here https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html
There is alot of predefined methods that do your job such as:
search(obj o)
contains(obj o)
I'm trying to write the remove method for Set but it doesn't work when I test it. Am I doing it wrong? the size doesn't reduce after I remove the element.
public class MySet<T> implements Set<T> {
private T[] arrayB;
private int elements;
#Override
public boolean remove(Object f) {
T h = (T) f;
for (T z : arrayB) {
if(z == h) {
z = null;
}
}
return true;
}
#Override
public int size() {
int count = 0;
for(int arr = 0; arr < arrayB.length; arr++){
if(arrayB[arr] != null) {
count++;
}
}
return count;
}
The test code is:
MySet<Integer> ints = new MySet<Integer>();
for (int i = 0; i < 100; i++) {
ints.add(i);
}
for (int i = 0; i < 100; i += 2) {
ints.remove(i);
}
}
Your size method relies on whether the element is null to decide whether to count it. Assuming that you are attempting to place a null in the array, you're doing it wrong. All you've done is assign null to z, which is just a local variable. The array is not changed.
You must use a traditional for loop and use an array access expression to assign null to the array element. You'll also want to call equals instead of using == to find the element.
for (int i = 0; i < array.length; i++)
{
if (array[i] != null && array[i].equals(h))
{
array[i] = null;
}
}
Depending on whether you want to remove all elements that match, or just the first one, you may consider adding a break statement inside the if.
I am trying to write a program using two methods that determines if a sub array is located within an array. subArray() is supposed to receive two arrays and return the index of the start of the sub array within the array. If the sub array is not located in the array it returns -1. subArray() then calls subArrayAppearsAt() and passes in the two arrays and a location. subArrayAppearsAt() is supposed to return true if the sub array is located in the array starting at the location passed in, false otherwise.
Currently if I pass in array {1,2,3} and sub array {2,3}, it returns 2 as the starting position but it should return 1.
If I pass in array {1,2,3,4,5} and sub array {4}, it returns -1, but it should return 3.
Does anyone see why this might be happening?
public static int subArray(int [ ] array, int [ ] subArray )
{
boolean result=true;
int subArrayLength = subArray.length;
if (subArrayLength == 0) {
return -1;
}
int limit = array.length - subArrayLength;
int i;
for ( i = 0; i <= limit; i++)
result = subArrayAppearsAt(array, subArray, i );
if (result==true)
return i;
else
return -1;
}
public static boolean subArrayAppearsAt(int[] largeArray, int[] subArray, int i) {
{
if (subArray[0] == largeArray[i])
{
boolean subArrayFound = true;
for (int j = 1; j < subArray.length; j++)
{
if (subArray[j] != largeArray[i+j])
{
subArrayFound = false;
j=subArray.length;
}
/* Sub array found - return its index */
if (subArrayFound==true)
{
return true;
}
}
}
}
/* Return default value */
return false;
}
Look at this part
for ( i = 0; i <= limit; i++)
result = subArrayAppearsAt(array, subArray, i );
it sets result every time it goes through the loop. If you test if {4} is conatined in {1, 2, 3, 4, 5} it will set result to the return value of subArrayAppearsAt(array, subArray, 4); which will return false
So for that problem you could do something like
for ( i = 0; i <= limit; i++) {
result = subArrayAppearsAt(array, subArray, i );
if (result==true)
return i;
}
return -1;
The other problem is, that i will be incremented after it goes into the for-loop the last time, and then you return that value. That problem should be solved with my code solution too.
I didn't test my solution but it should work ;)
EDIT
Sorry that wasn't all correct. Your subArrayAppearsAt() returns true too early. Edit your subArrayAppearsAt() function to this and it should work
public static boolean subArrayAppearsAt(int[] largeArray, int[] subArray, int i)
{
if (subArray[0] == largeArray[i])
{
for (int j = 1; j < subArray.length; j++)
{
if (subArray[j] != largeArray[i+j])
{
return false;
}
}
return true;
}
return false;
}
The problem is that if you want to know the start position you should put the if that checks the result inside de loop
public static int subArray(int [ ] array, int [ ] subArray )
{
boolean result=true;
int subArrayLength = subArray.length;
if (subArrayLength == 0) {
return -1;
}
int limit = array.length - subArrayLength;
int i;
for ( i = 0; i <= limit; i++){
result = subArrayAppearsAt(array, subArray, i );
if (result==true)
return i;
}
return -1;
}
public static void main(String[] args) {
int[] first = {1,2,4,5,3,2,1,3,4,5,6,33,432,21,5};
int[] second = {2,1};
System.out.println(findpos(first, second));
}
private static int findpos(int[] a, int[] b){
for(int i=0; i<a.length; i++){
if(a[i]!=b[0]){
continue;
}
if(a.length - i < b.length) return -1;
int itemp = i;
boolean found = true;
for(int j=0; j<b.length; j++){
if(itemp < a.length && a[itemp]!=b[j]){
found = false;
}
itemp++;
}
if(found){
return i;
}
}
return -1;
}