I wrote a class in Java with 5 methods. Linear search, which returns true if the value is found and false if it's not found. Linear search 2, which returns the location of the value, if found. binary search. which searches for the value within the array as well, print Int array, which prints 10 numbers a time, and selection sort, which sorts the array so I can do the binary search. Everything is compiling fine, but for some reason, none of my methods are returning anything (except the void printIntArray method).
EDIT:
Thanks, guys, I didn't realize I needed that. For some reason I thought it would return the value on its own... Another question, though. The binarySearch method doesn't appear to be doing anything. After the print statement "Searching for 11 in the random array using binary search"...., nothing is printed.
EDIT 2:
My binarySearch method wasn't working because I accidentally had mid + 1 for both else statements (else if (key < array[mid]) should have been mid - 1). THANKS so much to everyone! I added the fixes.
public class sortingSearching {
public static boolean linearSearch (int [] array, int key) {
for (int i = 0; i < array.length; i++) {
if (array [i] == key)
return true;
}// end for
return false;
}
public static int linearSearch2 (int [] array, int key) {
for (int i = 0; i < array.length; i++) {
if (array [i] == key)
return i;
}//end for
return -1;
}//end linearSearch2
public static boolean binarySearch (int [] array, int key) {
int left = 0;
int right = array.length - 1;
int mid = (left + right) /2;
while (left <= right) {
if (array[mid] == key)
return true;
else if ( key < array[mid])
right = mid - 1;
else
left = mid + 1;
mid = (left + right) /2;
} //end while
return false;
}//end binarySearch
public static void printIntArray (int [] array) {
for (int i = 0; i < array.length; i++) {
if (i%10 == 0)
System.out.println();
System.out.print(array[i] + " ");
} // end for
}
public static void selectionSort (int [] array) {
for (int start = 0; start < array.length - 1; start ++) {
int minI = start;
for (int i = start + 1; i < array.length; i++)
if (array[i] < array[start])
minI = i;
int temp = array[start];
array[start] = array[minI];
array[minI] = temp;
}//end for
} //end selectionSort
public static void main (String args []) {
int [] array = new int [20];
for (int i =0; i < array.length; i++)
array[i] = (int)((Math.random() * 100) + 1);
//print the array using printArray
printIntArray(array);
System.out.println();
//use linearSearch to search for 30, 86, and 87
System.out.println("Searching for 30 in the random array. If true is returned, " +
"the value was found. If false was returned, the value was not found.");
System.out.println(linearSearch(array, 30));
System.out.println("Searching for 86 in the random array. If true is returned, " +
"the value was found. If false was returned, the value was not found.");
System.out.println(linearSearch(array, 86));
System.out.println("Searching for 87 in the random array. If true is returned, " +
"the value was found. If false was returned, the value was not found.");
System.out.println(linearSearch(array, 87));
//use linearSearch to locate the first occurrences of 25, 80, and 91
System.out.println("Searching for the location of 25 in the random array. If -1 is " +
"returned, the number was not found in the array.");
System.out.println(linearSearch2(array, 25));
System.out.println("Searching for the location of 80 in the random array. If -1 is " +
"returned, the number was not found in the array.");
System.out.println(linearSearch2(array, 80));
System.out.println("Searching for the location of 91 in the random array. If -1 is " +
"returned, the number was not found in the array.");
System.out.println(linearSearch2(array, 91));
//use selectionSort to sort the array
selectionSort(array);
//use binarySearch to search for 11, 28, 74, and 99
System.out.println("Searching for 11 in the random array using binary search. If true is returned, " +
"the value was found. If false was returned, the value was not found.");
System.out.println(binarySearch (array, 11));
System.out.println("Searching for 28 in the random array using binary search. If true is returned, " +
"the value was found. If false was returned, the value was not found.");
System.out.println(binarySearch (array, 28));
System.out.println("Searching for 74 in the random array using binary search. If true is returned, " +
"the value was found. If false was returned, the value was not found.");
System.out.println(binarySearch (array, 74));
System.out.println("Searching for 99 in the random array using binary search. If true is returned, " +
"the value was found. If false was returned, the value was not found.");
System.out.println(binarySearch (array, 99));
} //end main
} //end sortingSearching
Also, I'm sorry all the print statements in the main method are distracting. I thought about taking them out for ease of reading, but I wanted it to be exactly as I've been running it.
linearSearch(array, 30);
They do return something. But DO something with the return value!
boolean value = linearSearch(array, 30);
System.out.println(value);
or even simpler:
System.out.println(linearSearch(array, 30));
In response to your edit
You need to initiate left to 1. You're performing integer division, which can never reach zero. Hence right gets stuck on 1 and left is always less than it.
They don't return anything because you are not assigning the return value to any variable.
Make this:
boolean foo= linearSearch(array, 86);
System.out.println(foo);
or
System.out.println(linearSearch(array, 86));
And so on.
You must put the sorting/searching method calls inside the println() statements, otherwise the results won't get printed! Like this:
System.out.println(
"Searching for 30 in the random array. If true is returned, " +
"the value was found. If false was returned, the value was not found." +
linearSearch(array, 30));
Alternatively, store the result in a local variable - but again, you have to pass the variable to println():
boolean result = linearSearch(array, 30);
System.out.println(
"Searching for 30 in the random array. If true is returned, " +
"the value was found. If false was returned, the value was not found." +
result);
They return what they are supposed to, just that you choose not to do anything with what they return.
You can solve the problem by wrapping the function calls in a System.out.println(), or storing the return values by using ret = yourfunction(params) and displaying ret later.
Related
New guy here trying 2D arrays. I have these codes but whenever I run it, the lowest value would always end up with 0 even if I input non-zero digits. Any idea how to fix this?
import javax.swing.JOptionPane;
public class TwoDArrayActivity {
public static void main(String[] args){
// declaration of array
int a[][] = new int[3][3];
int i = 0; // rows
int j = 0; // columns
String display = "";
int low = a[i][j];
for(i=0; i < a.length; i++) { // count the number of rows
for(j = 0; j < 3; j++) { // count the number of columns
a[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Enter a Number to Array [" + i + "]" + "[" + j + "]"));
if(a[i][j] < low)
low = a[i][j];
display = display + a[i][j] + " ";
} // end of inner for
display = display + "\n"; //new line
} // end of outer for
JOptionPane.showMessageDialog(null,"Values in Array\n" + display + "Lowest value is " + low, "Values in Array", JOptionPane.INFORMATION_MESSAGE);
} // end of method
} // end of class
Replace :
int low = a[i][j];
with :
int low = Integer.MAX_VALUE;
// declaration of array
int a[][] = new int[3][3];
The issue is here, when you instantiate the array it automatically fills every emtry with 0, as this is the equivalent of the undefined value for an integer type. eg.
new int[3][3]
>> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Therefore your low variable always has the value 0 and is never replaced by something lower
When you initialize an array implicitly in Java, the memory gets set to null, 0, 0L, 0.0f, false, or 0.0, etc, as appropriate for the datatype.
That means that your statement int low = a[i][j]; is setting low to an initial value of zero. All further comparisons will be against that, so your only chance to change that value is to enter a negative number, like -1.
You can add a test to your loop to initialize low with the first element of the loop you get:
if((i == 0 && j == 0) || a[i][j] < low)
Another option is to initialize low to the largest possible integer instead of implicit zero. In this simple example, that's probably the simplest approach to take:
int low = Integer.MAX_VALUE;
A third option is to add a boolean flag:
int low = ...;
boolean isFirst = true;
...
if(isFirst || a[i][j] < low)
...
isFirst = False;
You have to input negative numbers for it to change.
Otherwise, you can change it to
if(a[i][j] < low)
low = a[i][j];
but the name low wouldn't make sense anymore (it will be a "max").
I'm trying to make it so the random generator doesn't produce the same number in the array. I also don't know how to find the missing number. I tried the if statement, and it works, but it repeats.
The question problem "find the missing number in an array. The array consists of numbers from 1 to 10 in random sequence. One of the numbers in the array is absent and you must find it. Use one loop. An example {5,6,9,4,1,2,8,3,10} – the result will be: 7
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [10];
Random rand = new Random();
int numArr = 1;
for (int i = 1; i < 9; i++)
{
int n = rand.nextInt(10) + 1;
numbers[i] = n;
if (numbers[i] == numArr)
numArr++;
else
System.out.println("The missing num is " +numArr);
}
for(int val : numbers)
{
System.out.println("The next value is " +
val);
}
}
}
Assumption:
Numbers are unique
Only one entry is missing
number ranges from [1, 10] inclusive.
Solution
return 55 - Arrays.stream(yourArr).sum();
This is with O(n) runtime and O(1) space complexity.
If we break assumptions.
You will need O(N) space to figure out which entries are missing. To hold the marker either you can use List or BitSet or 2 bytes and manage it by hand. N is here the random number generation width.
There seems to be no mention on using a temporary data structure.
You can either sort the array and find the missing number, OR use a temporary sorted data structure.
You are conflating two things: the generator algorithm for a problem case and the solution to the problem itself. You shouldn't be interested in how the "random array" is generated at all (unless you want to test your solution). What you certainly shouldn't do is try to write the code that solves the problem in the method that generates the sample array.
If you want a randomly sorted list, Collections.shuffle will handle that for you. If you want a list without a single element, just generate a list of all elements 1..n and then remove the randomly selected number (then shuffle). So much for the generator. As for the solution, there are many methods to do it, someone already suggested using the sum, that's a perfectly valid solution.
It seems you are looking for this code.
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [9];
Random rand = new Random();
int numArr = 1;
numbers[0] = rand.nextInt(10) + 1;
for (int i = 1; i < 9; i++)
{
int n = rand.nextInt(10) + 1;
numbers[i] = n;
int x =0;
while(x<i){
if(numbers[x] == n){
i = i-1;
break;
}
x++;
}
}
int sum = 0;
for (int val : numbers) {
sum = sum + val;
System.out.println("The next value is " +
val);
}
System.out.println("Missing number is " + (55 - sum));
}
}
Output is -
The next value is 6
The next value is 2
The next value is 8
The next value is 1
The next value is 4
The next value is 3
The next value is 9
The next value is 10
The next value is 7
Missing number is 5
I am generating 9 Numbers between(1 to 10) randomly and then printing which number is missing among them.
You have two options:
The way I did it in the code below: setting the random array without repeating the same number. And then a for loop from 1 to 10 and check if that number exist in the array.
You know that 1 + 2 + 3 + 2 + 3 + 4 + 5 + 6 + 8 + 9 + 10 = 55. So if you get the sum of all ints in the array you will have 55 - (the missing number). So now the missing number = 55 - sum.
This is the code I did (first method):
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [9];
Random rand = new Random();
for (int i = 0; i <9; i++)
{
//setting random numbers in array without repeating
numbers[i] = checkForANumber(rand, numbers, i);
}
//print all nums
for(int val: numbers) System.out.println("The next value is " +
val);
for (int i = 1; i <= 10; i++)
{
boolean exist = false;
for(int val : numbers)
{
if(val == i){
exist = true;
}
}
if (!exist) System.out.println("The missing number is " + i);
}
}
private static int checkForANumber(Random rand, int[] numbers, int i){
int n = rand.nextInt(10) + 1;
boolean NumAlreadyExist = false;
for(int j = 0; j < i; j++)
{
if(numbers[j] == n){
NumAlreadyExist = true;
}
}
if(NumAlreadyExist) return checkForANumber(rand, numbers, i);
else return n;
}
}
Output:
The next value is 9
The next value is 3
The next value is 8
The next value is 6
The next value is 7
The next value is 10
The next value is 4
The next value is 2
The next value is 1
The missing number is 5
My question is related to the fibonacci sequence of numbers (but for simplicity, you could apply it to things like square/prime numbers etc)
long f1 = 0;
long f2 = 1;
long fibonacci = 0;
long[] fibonaccinumbers = new long[52];
fibonaccinumbers[0]=0;
fibonaccinumbers[1]=1;
for(int count = 2; count<=51; count++)
{
fibonacci = f2+f1;
fibonaccinumbers[count] = fibonacci;
f1 = f2;
f2 = fibonacci;
}
The above code generates the array for fibonacci numbers 0-51.
Now what I'm looking to do is enter a number, we'll use 30 as an example. and then find and display the numbers before and after it in the sequence, which would be 21 and 34.
What is tripping me up is getting into the array and searching above and below my given number to find a match. How could I do this?
Since the Fibonaccy series is a sorted array (having ascending order), you can use int index = Arrays.binarySearch(fibonaccinumbers,30); to get the index such that fibonaccinumbers[index-1] < 30 < fibonaccinumbers[index].
Therefore fibonaccinumbers[index-1] will contain 21 and fibonaccinumbers[index] will contain 34.
Note that Arrays.binarySearch will return fibonaccinumbers.length if all the numbers in your array are smaller than the number you are searching for.
This should be very simple, you just need to access the array at +1 and -1 of the index you have entered, for example, if the user enters 30...
System.out.println("BEFORE: " + fibonaccinumbers[input-1]);
System.out.println("AFTER: " + fibonaccinumbers[input+1]);
Where input is what the user enters, so in the case, input-1 would be 29.
Just be sure to make sure input-1 and input+1 do not go out of the bounds od your array.
If you wanted to find out what the actual fibonnaci number is as opposed to its number in the sequence, you will need to do a search for this first and then use the index you find to again, find what is before and after.
If you´d don´t want to use the binary search provided by the Arrays class then you could simply loop over the array and check for the needed values. You just need an int value that indicates the index in the array.
public static void main(String[] args) {
long[] fibs = createFib();
long search = 30;
int small = 0;
for(long i : fibs) {
if(i < search) {
++small;
} else {
break;
}
}
if(small < fibs.length)
System.out.println(fibs[small-1] + " and " + fibs[small] + " do surround the value " + search);
else {
System.out.println(" the value " + search +" is to high, only " + fibs[small-1] + " is in range");
}
}
private static long[] createFib() {
long f1 = 0;
long f2 = 1;
long fibonacci = 0;
long[] fibonaccinumbers = new long[52];
fibonaccinumbers[0]=0;
fibonaccinumbers[1]=1;
for(int count = 2; count<=51; count++)
{
fibonacci = f2+f1;
fibonaccinumbers[count] = fibonacci;
f1 = f2;
f2 = fibonacci;
}
return fibonaccinumbers;
}
I am trying to search an array for an int but it only give the location of the first index it finds if the int appears more than once. For example, if the number 2 appears at index 3 and 7. It will say 3 found at location 3 twice instead of saying 2 found at location 3 and 7. How can I get the additional index of the location where the number also appears.
// random_integers is an array of random integers of size 10
Arrays.asList(random_integers);
for (int n : random_integers) {
if (n == number) {
System.out.println("Search Value: "
+ number
+ " found at location: "
+ Arrays.asList(random_integers).indexOf(n)
+ " in the unsorted array");
}
}
Thank you.
That's the behavior of indexOf. Instead, use a traditional for loop and just use the current looping variable
for (int i = 0; i < random_integers.length; i++){
if (random_integers[i] == number){
System.out.println("Search Value: " + number + " found at location: " + i);
}
}
This happens because List#indexOf() has no idea about your intention to keep last index where item was found recently, so it returns first index every time. You should iterate over array by index, printing it when occurrence found:
for (int i; i < random_number.length; i++) {
if (random_integers[i] == number) {
System.out.format("Search Value: %s found at location: %s in the unsorted array", number, i);
}
}
The indexOf() method returns the index of the first occurrence of the specified element in the list, or -1 if the list does not contain the element.
A traditional for loop will work here.
for(int i=0; i < random_integers.length;i++){
if (random_integers[i] == number){
System.out.println("number=" + number + " location=" + i);
}
}
As what all guys said, use traditional for loop instead. If you want to use asList , try the following code:
int size = Arrays.asList(a).size();
for (int i = 0 ; i < size ; i++){
if (number == Arrays.asList(a).get(i))
System.out.println(" Search Value: " + number +
" found at location: " + i +
" in the unsorted array");
}
This code only works, if you are looking to find the current and next index value of a given array, however, if you are looking to find the index of a given value, refer to Michael's answer on this thread.
int totalLength = random_integers.length;
for (int i=0; i < totalLength; i++){
int nextIndex = i+1;
if (nextIndex == totalLength){
break;
}else{
int currentIndexValue = random_integers[i];
int nextIndexValue = random_integers[nextIndex];
}
}
I created a java program that will search for a value in array but my problem is when I input the same value in a different index, the first index is the only one that will be on output.
Example index 0 = 2, index 1 = 3, index 2 = 2
Output : array 2 is found at index 0 only
I break it on the loop to stop but if I did not do that, it will loop the Output
Here's what I want for Output: array 2 is found at index 0,2
Code:
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class Buff {
public static void main(String args[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter how many index :");
int v = Integer.parseInt( in .readLine());
int x;
int[] c = new int[v];
int vv;
for (x = 0; x < v; x++) {
System.out.print("Enter your value :");
c[x] = Integer.parseInt( in .readLine());
}
System.out.print("Enter your search number :");
int xx = Integer.parseInt( in .readLine());
for (x = 0; x < v; x++) {
if (c[x] == xx) {
System.out.print("array " + xx + " found at index :" + x);
break;
} else {
System.out.print("array not found");
}
}
}
}
You can also use StringBuilder if all you care is to output the indexes.
StringBuilder sb = new StringBuilder("array" + xx +" is found at index: ");
for (x = 0; x < v; x++) {
if (c[x] == xx) {
sb.append(x).append(",");
}
}
if (sb.charAt(sb.length() - 1) == ',') {
sb.deleteCharAt(sb.length() - 1);
System.out.println(sb);
} else {
System.out.println("array not found");
}
The solution to to make a list of the indexes that match and populate it in your for loop.
then after the for loop is done, print out the results
List<Integer> foundIndexes = new ArrayList<>();
for (x = 0; x < v; x++) {
if (c[x] == xx) {
foundIndexes.add(x);
}
}
//now we looped through whole array
if(foundIndexes.isEmpty()){
System.out.print("array not found");
}else{
System.out.print("array " + xx + " found at index : ");
for(Integer i : foundIndex){
System.out.print(i + ",");
}
}
This will print out array 2 is found at index 0,2, with a trailing comma. It's slightly more complicated to not have a trailing comma at the last index but I will leave that up to you to figure out.
If I understand correctly the problem is the following:
You have elements in an array, you want to check if a particular value is in more than once position of the array, your problem is if you simply remove the break statement, it shows a message every time you don't find the desired number, that's frankly the only problem I see with removing the break statement.
Personally, what I'd do one of these two things:
Option A: You can create a boolean variable that changes if you find a number, then wait to deliver the "array not found" message until you have stopped searching for it, like this:
boolean found = false;
for( x=0; x<v; x++)
{
if(c[x] == xx)
{
System.out.println("array " + xx + " found at index :"+x);
found = true;
}
}
if (found = false)
{
System.out.println("array not found");
}
println does the same as print, only it introduces a \n at the end, so the response looks like this:
array 2 found at index :0
array 2 found at index :2
Instead of:
array 2 found at index :0
array 2 found at index :2
Option B: Probably more elegant solution would be to create other array that store the positions in which you have found the element you are looking for, then print them all at once, you could do this going over the array twice (one to count how many positions the array has to have, another to check the positions of the elements) or simply use an ArrayList, but since this looks like learning material I'm going to guess that's out of the question.
Also if it is possible, try to word your question better because I'm still not even sure if this is what you are asking.