This method will check to see if number 'n'
is in the array of integers stored in the method more than once
It returns true if it is duplicated in the array and false
if not
*/
My code :
for (int i = 0; i < myYears.length; i ) {
for (int j = 0; j < myYears.length; j ) {
// got the duplicate element
System.out.println("Got dublicate");
return true;
}
}
return false;
However all i get is "got Dublicate" no matter the input.
Edit 1
package main;
public class Array1 {
public static void main(String[] args) {
findMoreThanOneInArray(1231); // test will return true
} // end main
/*
* This method will check to see if number 'n'
* is in the array of integers stored in the method more than once
*
* It returns true if it is duplicated in the array and false
* if not
*/
private static boolean findMoreThanOneInArray(int n) {
boolean result = false; // default the search to false
int[] myYears = { 2176, 2311, 2472, 2131, 2046, 2209, 2473, 2364, 2116, 2462, 2405, 2032, 2226, 2223, 2065, 2336, 2372, 2084, 2000, 2074, 2263, 2092, 2485, 2229, 2222, 2369, 2130, 2381, 2487, 2271, 2432, 2011, 2264, 2328, 2251, 2002, 2036, 2410, 2166, 2022, 2064, 2168, 2122, 2409, 2100, 2276, 2361, 2042, 2387, 2211, 2479, 2327, 2044, 2319, 2308, 2265, 2368, 2021, 2325, 2395, 2256, 2086, 2449, 2171, 2098, 2117, 2468, 2338, 2214, 2314, 2204, 2073, 2045, 2295, 2020, 2447, 2233, 2060, 2094, 2383, 2457, 2260, 2224, 2105, 2261, 2405, 2472, 2477, 2253, 2175, 2107, 2441, 2379, 2027, 2386, 2090, 2496, 2280, 2285, 2117 };
/*
* you code goes here
* return true if n is duplicated in the array, false otherwise
*/
for (int i = 0; i < myYears.length; i ) {
for (int j = i 1 ; j < myYears.length; j ) {
if (myYears[i] == myYears[j]) {
System.out.println("Got dublicate");
return true;
}
}
}
return false;
} // end of method
} // end class
Edit 2
for (int i = 0; i < myYears.length; i ) {
if (myYears[i] == n) {
System.out.println("Got dublicate");
return true;
}
}
System.out.println("false");
return false;
The Edit 2 passed all tests but one, for value of n = 2222; can anyone suggest why ?
CodePudding user response:
I think this is what you are searching for...
int count = 0;
for (int i = 0; i < myYears.length; i ) {
if (myYears[i] == n) {
count ;
}
}
if (count >= 2) {
System.out.println("true");
return true;
}
System.out.println("false");
return false;
This code basically increments the variable count
every time by 1 if the given value is found in the array. After the for loop, we check if the variable count
is greater or equal to the value 2
(because we need to know if the given number n
is appearing more than once)
CodePudding user response:
I recommend floyd's tortoise and hare algorithm. Basically you treat array like graph and find cycle - which is your dublicate number
https://dev.to/alisabaj/floyd-s-tortoise-and-hare-algorithm-finding-a-cycle-in-a-linked-list-39af