Detecting duplicates in an array - java

Pretty new to this and I've exhausted numerous attempts to figure out why this isn't working but can't get it.
private int indexOf(int searchingNum)
{
int x = searchingNum;
for (int i = 0; i<numberArray.length; i++){
if (numberArray[i]==x)
index = i;
else
index = -1;
}
return index;
}
public boolean addNumber(int numberToAdd)
{
int x = numberToAdd;
if (indexOf(x)!=-1)
return false;
if (count<numberArray.length&&indexOf(x)==-1){
count++;
numberArray[count-1] = x;
return true;
}
if (count>=numberArray.length&&indexOf(x)==-1){
count++;
newArray = Arrays.copyOf(numberArray, 2* numberArray.length);
numberArray = newArray;
numberArray[count-1] = x;
}
return true;
}
The method should't allow for duplicates but does. Any pointers in the right direction would be much appreciated.
Thank you.

Your indexOf is incorrect: since you continue the loop after finding a match, your code returns -1 unless the last item in the array happens to match.
To fix this problem, return i from inside the loop:
for (int i = 0 ; i < numberArray.length ; i++) {
if (numberArray[i]==x)
return i;
}
// If we are here, we did not find anything; return -1
return -1;

Here's a precise version of your code :
private boolean contains(int searchingNum)
{
for (int i = 0; i<numberArray.length; i++){
if (numberArray[i]==x)
return true;
}
return false;
}
public boolean addNumber(int numberToAdd)
{
int x = numberToAdd;
if (contains(x))
return false;
if (count<numberArray.length){
count++;
numberArray[count-1] = x;
}
else{
count++;
int []newArray = Arrays.copyOf(numberArray, 2* numberArray.length);
numberArray = newArray;
numberArray[count-1] = x;
}
return true;
}
Try this. Meanwhile, it can only gurantee you the uniqueness of the elements if the array wasn't previously initialised, i.e. all elements are added in the array using this method only.

Related

How to count the number of subarrays within a bigger array using recursion

How can you get a subarray from a bigger array recursively, and without using copyOfRange?
For example if int[] a = {1,2,1,3,1,2,1,1,2}, and int[] b = {1,2}, the correct answer is 3.
This is the only recursive call I have, but I'm not sure what to do beyond this.
I know the base case should be if(a.length < b.length), but I don't understand how to count the occurrences.
The function returns return numSubstring(a,b,low, mid-1) + numSubstring(a,b, mid+1,high);
public static int countSubs(int [] data, int [] sub) {
int cnt = 0;
if (data.length < sub.length) {
return cnt;
}
boolean found = true;
for (int i = 0; i < sub.length; i++) {
if (data[i] != sub[i]) {
found = false;
break;
}
}
if (found) {
cnt++;
}
cnt += countSubs(Arrays.copyOfRange(data, 1, data.length), sub);
return cnt;
}

I am confused on how to properly code the while loop. How to make sure it iterates through all the values in the array

The output should be that the array is sorted into descending order but my code stops after one iteration and doesn't fully sort the entire array and I don't know how to fix it. I am a beginner to please explain the logic in simple terms
public static int[] insertionSort(int[] array){
for(int i1 = 1; i1 < array.length; i1++){
int indexCurrent = i1;
boolean done = false;
while(indexCurrent <= (array.length -1) && done == false){
if(array[indexCurrent] > array[indexCurrent-1]){
int temp = array[indexCurrent-1];
array[indexCurrent-1] = array[indexCurrent];
array[indexCurrent] = temp;
indexCurrent++;
}else{
done = true;
}
}
}
return array;
}
You should be decrementing indexCurrent.
while(indexCurrent > 0 && !done){
if(array[indexCurrent] > array[indexCurrent-1]){
int temp = array[indexCurrent-1];
array[indexCurrent-1] = array[indexCurrent];
array[indexCurrent] = temp;
indexCurrent--;
}else{
done = true;
}
}

Is x in the Array Stack. I do not know why my code does not work. As it returns false even if I give x which is in the ArrayStack

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)

Finding a sub array in an array in Java

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;
}

Recursive method to find max value

maxRec() is meant to calculate the maximum value within an array using a helper
method maximize(). When this code executes, it always seems to return zero, however
it will print out the correct value. When using a debugger, I noticed that
the maxRec() method will get the right return value but wont return it; instead it sets it back to zero and moves up to the else statement.I would be grateful for any suggestions that could help fix this.
public int maxRec(int[] v) {
int maxValue = 0;
int[] tempArray = maximize(v);
boolean executeCode = true;
if (tempArray.length == 1) {
maxValue = tempArray[0];
executeCode = false;
System.out.println(maxValue);
} else if (executeCode == true && tempArray.length != 1) {
maxRec(tempArray);
}
return maxValue;
}
public int[] maximize(int[] v) {
int count = 0;
int secondCount = 0;
for (int i = 0; i < v.length; i++) {
if (v[i] > v[0]) {
count++;
}
}
int[] newArray;
newArray = new int[count];
for (int i = 0; i < v.length; i++) {
if (v[i] > v[0]) {
newArray[secondCount] = v[i];
secondCount++;
}
}
return newArray;
}
Code should be changed like this.
public int maxRec(int[] v)
{
int maxValue=0;
int[] tempArray = maximize(v);
boolean executeCode = true;
if(tempArray.length==1)
{
maxValue=tempArray[0];
executeCode=false;
}
else if(executeCode==true && tempArray.length!=1 && tempArray.length > 0)
{
maxValue = maxRec(tempArray);
}
return maxValue;
}
public int[] maximize(int[] v)
{
int count=0;
int secondCount=0;
for(int i=0;i<v.length;i++)
{
if(v[i]>v[0])
{
count++;
}
}
int[] newArray;
newArray = new int[count];
if(count == 0)
{
newArray = new int[1];
newArray[0] = v[0];
return newArray;
}
for(int i=0;i<v.length;i++)
{
if(v[i]>v[0])
{
newArray[secondCount]=v[i];
secondCount++;
}
}
return newArray;
}
maximize returns an array of all values greater than the first item of the array.
To make a recursive function, one starts with the simplest case, the least work.
The rest one delegates to a clone of oneself, the recursive call.
public int maxRec(int[] v) {
if (v.length == 0) {
throw IllegalArgumentException();
}
int[] greaterThanFirst = maximize(v);
int maxValue = 0;
if (greaterThanFirst.length == 0) {
maxValue = v[0];
} else {
maxValue = maxRec(greaterThanFirst);
}
return maxValue;
}
First a sanity check, v not being empty.
If maximize did not yield a larger number, yield the first value, being the largest.
//-------------------------------------------------------------------
// 1. maxRec --> Computes the maximum item of MyList
//-------------------------------------------------------------------
/**
* The function computes the maximum item of m (-1 if m is empty).
* #param m: The MyList we want to compute its maximum item.
* #return: The maximum item of MyList
*/
public int maxRec(MyList<Integer> m){
int max = 0;
int res = 0;
int e0 = 0;
int e1 = 0;
// Scenarios Identification
int scenario = 0;
// Type 1. MyLyst is empty
if(m.length() == 0) {
scenario = 1;
}else {
scenario = 2;
}
// Scenario Implementation
switch(scenario) {
// If MyLyst is empty
case 1:
res = -1;
break;
// If there is 1 or more elements
case 2:
// Old School
for(int i = 0; i <= m.length()-1; i++)
if(m.getElement(i) > max) {
max = m.getElement(i);
}
// Recursively
//1. Get and store first element of array
e0 = m.getElement(0);
//2. We remove the first element from MyList we just checked
m.removeElement(0);
//3. We recursively solve the smaller problem
e1 = maxRec(m);
//4. Compare and store results
if(e0 > e1) {
res = e0;
}
else {
res = e1;
}
//5. Return removed element back to the array
m.addElement(0, e0);
break;
}
//6.Display the process to see what's going on
System.out.println("My Way: "+ max);
System.out.println("Recursive Way: " + res);
//7. Return result
return res;
}

Categories

Resources