Sorting an array and using binary search - java

I've already gotten this program to run and it almost gives me the answer I want. After running the whole program, it's supposed to print out the index of the key and what the key is equal too. I cannot for the life of me figure out how to get the index into the final message in the console. For example, if you have an array of {0,1,2,3,4,5,6,7,8,9} and your key is 0, it's supposed to return: list[0] = 0. I labeled the part I think where my problem lies with "(index???)"
import java.util.Scanner;
public class PartA {
public static void main(String[] args){
System.out.println("Please enter 10 double values:");
double [] array = inputArray();
selectionSort(array);
printArray(array);
System.out.println("Please enter a search key:");
Scanner input = new Scanner(System.in);
double key = input.nextDouble();
double x = binarySearch(array,key);
if (x != -1)
System.out.println("list[" + (index???) + "] = " + key);
else
System.out.println(key + " is not on the list");
}
public static double[] inputArray(){
Scanner array = new Scanner(System.in);
double [] list = new double[10];
for(int i = 0; i < list.length; i++){
array.hasNextDouble();
list[i] = array.nextDouble();
}
return list;
}
public static void selectionSort(double[] list){
double array[] = new double [list.length];
for(int i = 0; i < list.length; i++){
for(int j = 0; j < list.length; j++){
if (list[i] < list[j]){
double x = list[i];
list[i] = list[j];
list[j] = x;
}
}
}
}
public static void printArray(double[] list){
for (int i = 0; i < list.length; i++){
System.out.println("list[" + i + "] = " + list[i]);
}
System.out.println();
}
public static int binarySearch(double []list, double key){
int low = 0, high = list.length - 1;
while(high >= low){
int mid = (low + high)/2;
if(key < list[mid])
high = mid - 1;
else if(key == list[mid])
return mid;
else low = mid + 1;
}
return -1;
}
}

I also mentioned already in the comments of the Question the solution, but for the sake of completeness i post this answer.
public class Main {
public static void main(String[] args){
System.out.println("10 double values:");
double [] array = {0,1,2,3,4,5,6,7,8,9};
selectionSort(array);
printArray(array);
double key = 4;
System.out.println("Searched Key: " + key);
int idx = binarySearch(array,key); //use int instead of double
if (idx != -1)
//use the variable identifier to print the index
System.out.println("list[" + idx + "] = " + key);
else
System.out.println(key + " is not on the list");
}
public static void selectionSort(double[] list){
double array[] = new double [list.length];
for(int i = 0; i < list.length; i++){
for(int j = 0; j < list.length; j++){
if (list[i] < list[j]){
double x = list[i];
list[i] = list[j];
list[j] = x;
}
}
}
}
public static void printArray(double[] list){
for (int i = 0; i < list.length; i++){
System.out.println("list[" + i + "] = " + list[i]);
}
System.out.println();
}
public static int binarySearch(double []list, double key){
int low = 0, high = list.length - 1;
while(high >= low){
int mid = (low + high)/2;
if(key < list[mid])
high = mid - 1;
else if(key == list[mid])
return mid;
else low = mid + 1;
}
return -1;
}
}
Working example with Ideone:
http://ideone.com/WXrJPi

I think your code works perfect. You just have to replace (index???) with x and change the type of x from double to int so that is does not print the the value as a double value.
int x = binarySearch(array,key);
if (x != -1)
System.out.println("list[" + (x) + "] = " + key);
else
System.out.println(key + " is not on the list");
}
Output:
Please enter 10 double values:
0
1
2
3
4
5
6
7
8
9
list[0] = 0.0
list[1] = 1.0
list[2] = 2.0
list[3] = 3.0
list[4] = 4.0
list[5] = 5.0
list[6] = 6.0
list[7] = 7.0
list[8] = 8.0
list[9] = 9.0
Please enter a search key:
5
list[5] = 5.0

Related

Finding the Nth smallest number in an unsorted array using Scanner

I've scoured the forums and can't find an example of how to find the Nth smallest number in an array in combination with scannner, so I'm sorry if this has been answered here before. Also, is there any way to display the number of comparisons that was made by the program to find an element within the array? I've attached an image of the assignment instructions if it will help. assignment instructions
public static void main(String[] args) {
System.out.println("IDS201 HW3:\n");
System.out.println("1. Generate " + RANDOM_NUMBER_COUNT + " random integer unsorted list.\n");
int[] randomNumbers = generateRandomNUmbers();
System.out.print("\n2. Search value? ");
Scanner stdin = new Scanner(System.in);
int x = stdin.nextInt();
int count = search(randomNumbers, x);
if (count == 0) {
System.out.println(x + " is not in the list");
}
System.out.println("\n3. Sort the list:");
sort(randomNumbers);
System.out.print("Now the Array after Sorting is :\n\n");
display(randomNumbers);
}
private static final int RANDOM_NUMBER_COUNT = 50;
private static void display(int[] randomNumbers) {
int count = 0;
for (int i = 0; i < RANDOM_NUMBER_COUNT; i++) {
System.out.print(randomNumbers[i] + ",");
count++;
if (count == 10) {
System.out.println();
count = 0;
}
}
}
private static int[] generateRandomNUmbers() {
int[] randomNumbers = new int[RANDOM_NUMBER_COUNT];
for (int index = 0; index < RANDOM_NUMBER_COUNT; index++) {
randomNumbers[index] = (int) (Math.random() * 100);
}
display(randomNumbers);
return randomNumbers;
}
private static int search(int[] randomNumbers, int x) {
int i;
int count = 0;
for (i = 0; i < randomNumbers.length; i++) {
if (randomNumbers[i] == x) {
System.out.println("\nFound " + x + " in array [" + i + "]");
count++;
}
}
return count;
}
private static int[] sort(int[] randomNumbers) {
int size = randomNumbers.length;
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (randomNumbers[i] > randomNumbers[j]) {
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
}
}
}
return randomNumbers;
}
}
You can find the order statistics algorithm to find the k-th smallest element in O(n) time here. For the Scanner part, you don't need anything other than reading k from the command line and passing it into the algorithm. Nothing really different from the original algorithm, both takes a parameter k and in this case, you read the parameter k from the command line.
Note: There are other approaches to the k-th smallest element problem, but they are slower. For example, you can sort your array and then find the k-th element from the last index. You can also find other approaches from previous entries on the given link.
here you go:
import java.util.Scanner;
public class Main
{
public static void main (String[]args)
{
System.out.println ("IDS201 HW3:\n");
System.out.println ("1. Generate " + RANDOM_NUMBER_COUNT +
" random integer unsorted list.\n");
int[] randomNumbers = generateRandomNUmbers ();
System.out.print ("\n2. Search value? ");
Scanner stdin = new Scanner (System.in);
int x = stdin.nextInt ();
int count = search (randomNumbers, x);
if (count == 0)
{
System.out.println (x + " is not in the list");
}
else
{
System.out.println ("compared " + count + " times to search");
}
System.out.print ("\n2. Nth Smallest value? ");
int nth_value = stdin.nextInt ();
System.out.print ("K'th smallest element is " +
nth_search (randomNumbers, 0, RANDOM_NUMBER_COUNT-1,nth_value));
System.out.println ("\n3. Sort the list:");
sort (randomNumbers);
System.out.print ("Now the Array after Sorting is :\n\n");
display (randomNumbers);
}
private static final int RANDOM_NUMBER_COUNT = 50;
private static int partition (int[]randomNumbers, int l, int r)
{
int x = randomNumbers[r], i = l;
for (int j = l; j <= r - 1; j++)
{
if (randomNumbers[j] <= x)
{
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
i++;
}
}
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[r];
randomNumbers[r] = temp;
return i;
}
private static void display (int[]randomNumbers)
{
int count = 0;
for (int i = 0; i < RANDOM_NUMBER_COUNT; i++)
{
System.out.print (randomNumbers[i] + ",");
count++;
if (count == 10)
{
System.out.println ();
count = 0;
}
}
}
private static int[] generateRandomNUmbers ()
{
int[] randomNumbers = new int[RANDOM_NUMBER_COUNT];
for (int index = 0; index < RANDOM_NUMBER_COUNT; index++)
{
randomNumbers[index] = (int) (Math.random () * 100);
}
display (randomNumbers);
return randomNumbers;
}
private static int search (int[]randomNumbers, int x)
{
int i;
int count = 0;
for (i = 0; i < randomNumbers.length; i++)
{
if (randomNumbers[i] == x)
{
System.out.println ("\nFound " + x + " in array [" + i + "]");
count++;
}
}
return count;
}
private static int nth_search (int[]randomNumbers, int l, int r, int k)
{
if (k > 0 && k <= r - l +1)
{
int pos = partition (randomNumbers, l, r);
if (pos - l == k - 1)
return randomNumbers[pos];
if (pos - l > k - 1)
return nth_search (randomNumbers, l, pos - 1, k);
return nth_search (randomNumbers, pos + 1, r, k - pos + l - 1);
}
return -1;
}
private static int[] sort (int[]randomNumbers)
{
int size = randomNumbers.length;
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (randomNumbers[i] > randomNumbers[j])
{
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
}
}
}
return randomNumbers;
}
}
nth smallest term function
private static int nth_search (int[]randomNumbers, int l, int r, int k)
{
if (k > 0 && k <= r - l +1)
{
int pos = partition (randomNumbers, l, r);
if (pos - l == k - 1)
return randomNumbers[pos];
if (pos - l > k - 1)
return nth_search (randomNumbers, l, pos - 1, k);
return nth_search (randomNumbers, pos + 1, r, k - pos + l - 1);
}
return -1;
}
and 2nd function
private static int partition (int[]randomNumbers, int l, int r)
{
int x = randomNumbers[r], i = l;
for (int j = l; j <= r - 1; j++)
{
if (randomNumbers[j] <= x)
{
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
i++;
}
}
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[r];
randomNumbers[r] = temp;
return i;
}

Using for loop to find an element that appears multiple times in a random, unsorted array

My goal is to print out a user input value (and its corresponding index) if it appears 1 or more times in a random generated array of 50 integers. If I search the array for a value, and it happens to appear more than once, however, only one location of the element is printed, and then the if-else statement is executed. If I remove the break at the end of the third for loop, the whole thing falls apart. I've attached an image but here is the part of it that is giving me an issue. Apologies if the code is not clean, I'm very new.
public static void main(String[] args) {
System.out.println("IDS201 HW3:\n");
System.out.println("1. Generate 50 random integer unsorted list.\n");
Scanner stdin = new Scanner(System.in);
int[] randomNumbers = new int[50];
for(int index = 0; index < randomNumbers.length; index++) {
randomNumbers[index] = (int) (Math.random()*100);
}//end for
int count = 0;
for(int i = 0; i < randomNumbers.length; i++) {
System.out.print(randomNumbers[i] + ",");
count++;
if(count == 10) {
System.out.println();
count = 0;
}
}//end for
System.out.println("\nSearch value?");
int x = stdin.nextInt();
int i;
for(i = 0; i < randomNumbers.length; i++) {
if(randomNumbers[i] == x)
break;}
if (i != randomNumbers.length) {
System.out.println("\nFound " + x + " in array [" + i + "]");}
else {
System.out.println(x + " is not in the list");}
{int temp;
int size = randomNumbers.length;
for(i = 0; i<size; i++ ){
for(int j = i+1; j<size; j++){
if(randomNumbers[i]>randomNumbers[j]){
temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
}
}
}
System.out.println("\nSmallest element of the array is: " + randomNumbers[0]);}
System.out.println("\n3. Sort the list:");
int size = randomNumbers.length;
for(i=0; i<size; i++)
{
for(int j=i+1; j<size; j++)
{
if(randomNumbers[i] > randomNumbers[j])
{
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
}
}
}
System.out.print("Now the Array after Sorting is :\n\n");
int count1 = 0;
for(i=0; i<size; i++)
{
System.out.print(randomNumbers[i]+ ",");
count++;
if(count == 10) {
System.out.println();
count = 0;
}
}
}
}
if statement in for loop
Implementing the comments to your question:
import java.util.Scanner;
public class NumCount {
private static final int RANDOM_NUMBER_COUNT = 50;
private static void display(int[] randomNumbers) {
int count = 0;
for (int i = 0; i < RANDOM_NUMBER_COUNT; i++) {
System.out.print(randomNumbers[i] + ",");
count++;
if (count == 10) {
System.out.println();
count = 0;
}
}
}
private static int[] generateRandomNUmbers() {
int[] randomNumbers = new int[RANDOM_NUMBER_COUNT];
for (int index = 0; index < RANDOM_NUMBER_COUNT; index++) {
randomNumbers[index] = (int) (Math.random() * 100);
}
display(randomNumbers);
return randomNumbers;
}
private static int search(int[] randomNumbers, int x) {
int i;
int count = 0;
for (i = 0; i < randomNumbers.length; i++) {
if (randomNumbers[i] == x) {
System.out.println("\nFound " + x + " in array [" + i + "]");
count++;
}
}
return count;
}
private static int[] sort(int[] randomNumbers) {
int size = randomNumbers.length;
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (randomNumbers[i] > randomNumbers[j]) {
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
}
}
}
return randomNumbers;
}
/**
* Start here.
*/
public static void main(String[] args) {
System.out.println("IDS201 HW3:\n");
System.out.println("1. Generate " + RANDOM_NUMBER_COUNT + " random integer unsorted list.\n");
int[] randomNumbers = generateRandomNUmbers();
System.out.print("\n2. Search value? ");
Scanner stdin = new Scanner(System.in);
int x = stdin.nextInt();
int count = search(randomNumbers, x);
if (count == 0) {
System.out.println(x + " is not in the list");
}
System.out.println("\n3. Sort the list:");
sort(randomNumbers);
System.out.print("Now the Array after Sorting is :\n\n");
display(randomNumbers);
}
}
Of-course there is no need to search for the smallest number because it will be the first element in the sorted array. Hence I removed that part of your code.

java.util.NoSuchElementException reading user input

I'm getting an error message (java.util.NoSuchElementException) in thread main when attempting to compile the following code with the input 3, then 4, 5, and 7. I've tried to tweak the code, but there's something I'm missing. I was thinking it may be due to my use of arrays since I am just learning how to use those, but I've tried to look closely at them and I didn't see anything I did wrong, but I definitely missed something. Any help would be appreciated. Thanks!
import java.util.Scanner;
public class ArrayMethods2 {
public static int[] findMinAndMax(int[] x) {
int i;
int min = x[0];
int max = x[0];
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
min = x[i];
}
if (x[i] > max) {
max = x[i];
}
}
int [] minAndMax = new int[2];
minAndMax[0] = min;
minAndMax [1] = max;
return minAndMax;
}
public static double averageWithDrop(int[] x) {
int i;
int min = x[0];
int minIndex1 = 0;
int minIndex2 = 0;
int sum = 0;
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
minIndex1 = i;
}
}
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
if (i != minIndex1)
minIndex2 = i;
}
}
for (i = 0; i < x.length; i++) {
if (i == minIndex1) {
sum = sum + 0;
}
else if (i == minIndex2) {
sum = sum + 0;
}
else {
sum = sum + x[i];
}
}
double average = sum / (x.length - 2);
return average;
}
public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many numbers would you like to enter? (must be at least 3) ");
int userValue = scnr.nextInt();
System.out.println(userValue);
while (userValue < 3) {
System.out.println("Invalid value, must be at least 3. Please try again ");
userValue = scnr.nextInt();
System.out.println(userValue);
}
int x = 0;
int indexVal;
int [] userArray = new int [userValue];
while (x <= userValue) {
System.out.print("Enter value for index " + x + ": ");
indexVal = scnr.nextInt();
System.out.println(indexVal);
userArray[x] = indexVal;
x++;
}
int [] minAndMaxVal = new int [2];
minAndMaxVal = findMinAndMax(userArray);
System.out.println("Min value: " + minAndMaxVal[1] + ", Max value: " + minAndMaxVal[2]);
double avg = averageWithDrop(userArray);
System.out.println("Average excluding two lowest values: " + avg);
}
}
Running your code, I did not get any NoSuchElementException, however I got IndexOutOfBoundsException. Check the class your are running.
Please remember arrays are 0 based.
In the main method change while (x <= userValue)to while (x < userValue)
Again, arrays are 0 based, change:
System.out.println("Min value: " + minAndMaxVal[1] + ", Max value: " + minAndMaxVal[2]);
to
System.out.println("Min value: " + minAndMaxVal[0] + ", Max value: " + minAndMaxVal[1]);
There are few problems in the code :
Update this (x <= userValue) to (x<userValue) , else it will give array index out of bounds exception
Start the for loop in minMaxFunction from 1 , since you have already stored the value of arr[0] to min and max like below . This is just an optimization in the code.
for (i = 1; i < x.length; i++) {
if (x[i] < min) {
min = x[i];
}
if (x[i] > max) {
max = x[i];
}
}
This line in main method should have index 0 and index 1 . There is no index 2 since you have declared the array of length 2 , else it will give array index out of bounds exception
minAndMaxVal = findMinAndMax(userArray);
System.out.println("Min value: " + minAndMaxVal[0] + ", Max value: " + minAndMaxVal[1]);

string multiplication using a big integer class

I'm trying to write a code that multiplies two strings of integers. I'm not too sure where it's going wrong... It works for some numbers, but is horribly wrong for others. I'm not asking for a full solution, but just a hint (I seriously appreciate any help possible) as to where I'm making the obviously silly mistake. Thanks in advance.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a big integer. ");
String t = scan.nextLine();
System.out.print("And another. ");
String s = scan.nextLine();
BigInt a = new BigInt(t);
BigInt b = new BigInt(s);
System.out.println(a + " + " + b + " = " + a.add(b));
System.out.println(a + " - " + b + " = " + a.sub(b));
System.out.println(a + " * " + b + " = " + a.mul(b));
System.out.println(a + " / " + b + " = " + a.div(b));
}
}
class BigInt {
public BigInt() {
n = new int[1];
}
public BigInt(String s) {
n = new int[s.length()];
for (int i = 0; i < n.length; ++i) {
n[n.length - i - 1] = s.charAt(i) - '0' ;
}
}
private BigInt(int[] n) {
this.n = new int[n.length];
for (int i = 0; i < n.length; ++i) {
this.n[i] = n[i];
}
}
public String toString() {
String s = "";
for (int i : n) {
s = i + s;
}
return s;
}
public BigInt mul(BigInt o) {
int carry = 0;
int s = 0;
int digit;
int subtotal = 0;
int total = 0;
int max = n.length > o.n.length ? n.length : o.n.length;
int[] result = new int[n.length + o.n.length];
for (int i = 0; i < o.n.length; ++i) {
int bottom = i <= o.n.length ? o.n[i] : 0;
for (s = 0; s <= n.length; ++s){
int top = s < n.length ? n[s] : 0;
int prod = (top * bottom + carry);
if (s == (max-1)) {
total = Integer.valueOf((String.valueOf(prod) + String.valueOf(subtotal)));
carry = 0;
digit = 0;
subtotal = 0;
break;
}
if (prod < 10) {
digit = prod;
subtotal += digit;
carry = 0;
}
if (prod >= 10); {
digit = prod % 10;
carry = prod / 10;
subtotal += digit;
}
}
result[i] = total;
}
return new BigInt(trim(result));
}
private int[] trim(int[] nums) {
int size = nums.length;
for (int i = nums.length - 1; i > 0; --i) {
if (nums[i] != 0) {
break;
}
--size;
}
int[] res = new int[size];
for (int i = 0; i < size; ++i) {
res[i] = nums[i];
}
return res;
}
private int[] n;
}
A quick test using:
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) {
System.out.println(x + " * " + y + " = " + new BigInt(Integer.toString(x)).mul(new BigInt(Integer.toString(y))));
}
}
demonstrates that somehow your multiply of x * y is actually multiplying by 10x * y. That should give you a clear hint to the problem.

How do I populate an array with palindromes using a loop?

First time on this site and first java class ever. I am stuck trying to populate an array with palindromes. I have tried the everything with no luck. What am I doing wrong?
Here's what I've coded so far.
public class PalindromeListArray
{
public static void main(String[] args)
{
//Declare variables.
int digit1, digit2, digit3, digit4, digit5;
final int MAX = 10;
int x=0;
//Create an array of size 25.
String[] palindromeList = new String[25];
//Generate numbers.
for (digit1 = 1; digit1 < MAX; digit1++)
for (digit2 = 0; digit2 < MAX; digit2++)
for (digit3 = 0; digit3 < MAX; digit3++)
for (digit4 = 0; digit4 < MAX; digit4++)
for (digit5 = 0; digit5 < MAX; digit5++)
if (digit1 == digit5 && digit2 == digit4)
for(x=0; x < palindromeList.length; ++x){
//Populate array with palindromes.
palindromeList[x] = String.valueOf(digit1) + String.valueOf(digit2) + String.valueOf(digit3) + String.valueOf(digit4) + String.valueOf(digit5);
System.out.println(x + "\t" + palindromeList[x]);
}
}
}
Along these lines:
...
if(x == palindromeList.length) break;
palindromeList[x++] = String.valueOf(digit1) + String.valueOf(digit2) + ...
}
for(int i = 0; i < x; i++)
System.out.println(i + "\t" + palindromeList[i]);
...
You were in the ball park.

Categories

Resources