bSearch java program - java

I don't know what it wrong with my code. Im supposed to put in an input file and sort the numbers from lowest to greatest. When i run the program it returns:Sorted array of 25 ints from P4input.txt after insertInOrder:
31 5 8 8 19 23 25 27 27 31 69 70 71 75 90 98 103 103 109 140 145 145 153 157 162
I don't know why the first number is out of order.
/* Project4.java InsertInOrder with bSearch optimization to compute insertion index */
import java.util.*;
import java.io.*;
public class Project4
{
static final int INITIAL_CAPACITY = 5;
public static void main( String args[] ) throws Exception
{
// ALWAYS TEST FIRST TO VERIFY USER PUT REQUIRED INPUT FILE NAME ON THE COMMAND LINE
if (args.length < 1 )
{
System.out.println("\nusage: C:\\> java Project4 <input filename>\n\n"); // i.e. C:\> java Project4 P4input.txt
System.exit(0);
}
// LOAD FILE INTO ARR USING INSERINORDER
Scanner infile = new Scanner( new File( args[0] ) );
int[] arr = new int[INITIAL_CAPACITY];
int count= 0;
while (infile.hasNextInt())
{
if ( count==arr.length )
arr = upSizeArr(arr);
insertInOrder( arr, count++, infile.nextInt() );
}
infile.close();
arr=trimArr(arr,count); // Now count == .length
System.out.println( "Sorted array of " + arr.length + " ints from " + args[0] + " after insertInOrder:" );
printArray( arr ); // we trimmed it thus count == length so we don't bother to pass in count
} // END MAIN
// ############################################################################################################
// USE AS IS - DO NOT MODIFY
static void printArray( int[] arr )
{
for( int i=0 ; i<arr.length ;++i )
System.out.print(arr[i] + " " );
System.out.println();
}
// USE AS IS - DO NOT MODIFY
static int[] upSizeArr( int[] fullArr )
{
int[] upSizedArr = new int[ fullArr.length * 2 ];
for ( int i=0; i<fullArr.length ; ++i )
upSizedArr[i] = fullArr[i];
return upSizedArr;
}
// USE AS IS - DO NOT MODIFY
static int[] trimArr( int[] oldArr, int count )
{
int[] trimmedArr = new int[ count ];
for ( int i=0; i<count ; ++i )
trimmedArr[i] = oldArr[i];
return trimmedArr;
}
// ############################################################################################################
static void insertInOrder( int[] arr, int count, int key )
{
int index=bSearch( arr, count, key ); // LEAVE THIS HERE
if (arr[arr.length - 1] == 0)
{
for (int i = count; i >= index + 1; i--)
{
arr[i] = arr[i - 1];
}
arr[index]=key; // LEAVE THIS HERE
}
}
static int bSearch(int[] a, int count, int key)
{
int hi = count-1;
int lo = 0;
int mid = 0;
if(hi == -1)
{
return lo;
}
else
{
mid = (hi+lo)/2;
}
while (lo <= hi)
{
if (key==a[mid])
{
return (mid+1);
}
else if (key < a[mid])
{
hi = mid-1;
mid = (hi+lo)/2;
}
else
{
lo = mid +1;
mid = (hi+lo)/2;
}
}
return (mid +1);
}
} // END PROJECT4

Related

Random characters showing up in my output, not sure where they're coming from [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 2 years ago.
I'm creating a program that uses two methods to print all the odd numbers in an array and then get the sum of the odd numbers. However, I'm getting an output that makes no sense. This is the code that I'm using:
public class ArrayMethods1 {
public static int[] printOdds(int[]arrayExample) {
int i;
String oddNum = "";
int [] newArray = new int [3];
int x = 0;
for (i = 0; i < arrayExample.length; i++) {
if (arrayExample[i] % 2 != 0) {
System.out.print(arrayExample[i] + " ");
}
}
int[] sumOfOdds = new int [1];
sumOfOdds = sumOdds(newArray);
return sumOfOdds;
}
public static int[] sumOdds(int[]arrayExample1) {
int i;
int[] oddsTotal = new int[1];
int total = 0;
for (i = 0; i < arrayExample1.length; i++) {
if (arrayExample1[i] % 2 != 0) {
total = total + arrayExample1[i];
}
}
oddsTotal[0] = total;
return oddsTotal;
}
public static void main(String[] args) {
int [] mainArray = new int [5];
mainArray[0] = 17;
mainArray[1] = 92;
mainArray[2] = 21;
mainArray[3] = 984;
mainArray[4] = 75;
printOdds(mainArray);
int [] oddSum = new int[1];
oddSum = sumOdds(mainArray);
System.out.println(oddSum);
}
}
And I'm getting this as output:
17 21 75 [I#51016012
I have absolutely no idea where that second part is coming from, so any help would be awesome. Thanks!
well you are storing the result of the sum in an array and then you print the reference of type int[], that's why you get [I#51016012. so you need to print oddSum[0].
It is not quite clear why you return int[] from the methods that just print and calculate the sum of the odd numbers.
So the code could be enhanced:
public static void printOdds(int[] arr) {
for (int n : arr) {
if (n % 2 == 1) {
System.out.print(n + " ");
}
}
System.out.println();
}
public static int sumOdds(int[] arr) {
int total = 0;
for (int n : arr) {
if (n % 2 == 1) {
total += n;
}
}
return total;
}
Also, it may be worth to use Java 8+ stream to implement both tasks in one run:
import java.util.Arrays;
public class PrintAndSumOdds {
public static void main(String [] args){
int[] arr = {17, 92, 21, 984, 75};
int sumOdds = Arrays.stream(arr) // get IntStream from the array
.filter(n -> n % 2 == 1) // filter out the odds
.peek(n -> System.out.print(n + " ")) // print them in one line
.sum(); // and count the sum (terminal operation)
System.out.println("\nTotal odds: " + sumOdds);
}
}
Output:
17 21 75
Total odds: 113

D-heap not producing correct order

My program runs, but it always gives the incorrect answer. Here are some sample runs:
Enter heap elements: 15 1 14 2 13 3 12 4 11 5 10 6 9 7 8
Enter d: 3
Output: Heap (d= 3): 1 2 3 4 5 6 7 15 11 13 10 14 9 12 8
It should be:
Enter heap elements: 15 1 14 2 13 3 12 4 11 5 10 6 9 7 8
Enter d: 3
Output: Heap (d=3): 1 3 4 2 7 15 12 14 11 5 10 6 9 13 8
import java.util.Scanner;
import java.util.Arrays;
public class D_heap<AnyType extends Comparable<? super AnyType>>
{
private int d;
private final static int DEFAULT_CAPACITY = 10;
private int currentSize;
private AnyType [ ] array; //
/**
* Construct the binary heap.
*/
public D_heap( )
{
this(2, DEFAULT_CAPACITY );
}
/**
* Construct the binary heap.
* #param capacity the capacity of the binary heap.
*/
public D_heap(int numChild )
{
this(numChild, DEFAULT_CAPACITY);
}
public D_heap(int numChild, int cap )
{
currentSize = 0;
d = numChild;
array = (AnyType[]) new Comparable[ cap + 1 ];
}
/**
* Construct the binary heap given an array of items.
*/
//public D_heap( AnyType [ ] items )
//{
// currentSize = items.length;
// array = (AnyType[]) new Comparable[ ( currentSize + 2 ) * 11 / 10 ];
// int i = 1;
// for( AnyType item : items )
// array[ i++ ] = item;
// buildHeap( );
//}
/**
* Insert into the priority queue, maintaining heap order.
* Duplicates are allowed.
* #param x the item to insert.
*/
public void insert( AnyType x )
{
if( currentSize == array.length - 1 )
enlargeArray( array.length * 2 + 1 );
// Percolate up
int hole = ++currentSize;
for( ; hole > 1 && x.compareTo( array[ getParent(hole)] ) < 0; hole = getParent(hole) )
array[ hole ] = array[getParent(hole)];
array[ hole ] = x;
}
private void enlargeArray( int newSize )
{
AnyType [] old = array;
array = (AnyType []) new Comparable[ newSize ];
for( int i = 0; i < old.length; i++ )
array[ i ] = old[ i ];
}
/**
* Find the smallest item in the priority queue.
* #return the smallest item, or throw an UnderflowException if empty.
*/
public AnyType findMin( )
{
if( isEmpty( ) )
throw new UnderflowException(" ");
return array[ 1 ];
}
/**
* Remove the smallest item from the priority queue.
* #return the smallest item, or throw an UnderflowException if empty.
*/
public AnyType deleteMin( )
{
if( isEmpty( ) )
throw new UnderflowException(" ");
AnyType minItem = findMin( );
array[ 1 ] = array[ currentSize-- ];
percolateDown( 1 );
return minItem;
}
/**
* Establish heap order property from an arbitrary
* arrangement of items. Runs in linear time.
*/
private void buildHeap( )
{
for( int i = currentSize / 2; i > 0; i-- )
percolateDown( i );
}
/**
* Test if the priority queue is logically empty.
* #return true if empty, false otherwise.
*/
public boolean isEmpty( )
{
return currentSize == 0;
}
/**
* Make the priority queue logically empty.
*/
public void makeEmpty( )
{
currentSize = 0;
}
public void print( )
{
for( int i = 0; i < currentSize; i++ )
System.out.printf("%d ", array[i+1]);
System.out.println();
}
/**
* Internal method to percolate down in the heap.
* #param hole the index at which the percolate begins.
*/
private void percolateDown( int hole )
{
int child = getChild(hole);
int tempChild = getChild (hole);
AnyType tmp = array[ hole ];
for( ; getChild(hole) <= currentSize; hole = child) {
child = getChild(hole);
tempChild = getChild(hole);
for(int i = 0; i < d && tempChild != currentSize; i++, tempChild++){
if(array[tempChild + 1].compareTo(array[child]) < 0){
child = tempChild + 1;
}
}
if (array[child].compareTo(tmp) < 0)
array[hole] = array[child];
else
break;
}
array[ hole ] = tmp;
}
// Test program
public static void main( String [ ] args )
{
Scanner in = new Scanner(System.in);
D_heap<Integer> h = new D_heap<Integer>();
System.out.print ("How many numeric values do you want to enter? ");
int num = in.nextInt();
System.out.print ("Enter heap elements: ");
for (int i = 1; i <= num; i++){
h.insert (in.nextInt());
}
System.out.print ("Enter d: ");
int d = in.nextInt();
System.out.printf ("Output: Heap (d= %d): ", d);
h.buildHeap();
h.print();
// Create the array of Strings containing the main menu options (Quit - option 0)
// Create the mainMenu object
String opts[] = {"Exit program", "Insert", "deleteMin", "Pick new d value", };
Menu mainMenu = new Menu(opts);
int opt = 0;
do {
opt = mainMenu.runMenu();
switch (opt) {
case 1:
System.out.print ("Enter element to insert: ");
int x = in.nextInt();
h.insert(x);
h.print();
break;
case 2:
h.deleteMin();
h.print();
break;
case 3:
System.out.print ("Enter new d: ");
d = in.nextInt();
h.buildHeap();
h.print();
break;
default:
System.out.println ("Thank you - Have a nice day!");
}
} while (opt != 0);
}
public int getChild( int p){
return d * (p - 1) + 2;
}
public int getParent (int c){
return (c - 2)/d + 1;
}
}

I need assistance with my intro to Java assignment

I have successfully compiled this java program (which generates 100 random numbers between 0 and 25, puts them in an array, and sorts them into two different arrays based on whether each is even or odd), although it does not run. I suspect I have made a mistake with one of the while loops, although I don't know for sure. Also, I struggled to get the code in properly formatted in the question, so the tabs are somewhat off, but it is still mostly legible. Here is the .java text:
public class Assignment8
{
public static void main( String [] args )
{
int storage [] = new int[100];
int j = 0;
while ( storage.length < 100 ) {
int testVariable = 0 + (int) (Math.random() * ((25 - 0) + 1));
storage[j] = testVariable;
j++;
}
int oddArray[] = OddNumbers( storage );
int evenArray[] = EvenNumbers( storage );
int currentNumber = 0;
System.out.println( "The odd numbers are: " + "\n" );
while ( currentNumber <= 99 ) {
System.out.println( oddArray[currentNumber] + "\n" );
currentNumber++;
}
System.out.println( "\n" + "The even numbers are: " + "\n" );
currentNumber = 0;
while ( currentNumber <= 99 ) {
System.out.println( evenArray[currentNumber] + "\n" );
currentNumber++;
}
}
public static int[] OddNumbers( int storage[] )
{
int currentNumber = 0;
int currentValue = storage[currentNumber];
int oddArray[] = new int[100];
while ( currentNumber <= 99 ) {
if ( storage[currentNumber] % 2 != 0 ) {
oddArray[currentNumber] = currentValue;
} else {
continue;
}
currentNumber++;
}
return oddArray;
}
public static int[] EvenNumbers( int storage[] )
{
int currentNumber = 0;
int currentValue = storage[currentNumber];
int evenArray[] = new int[100];
while ( currentNumber <= 99 ) {
if ( storage[currentNumber] % 2 == 0 ) {
evenArray[currentNumber] = currentValue;
} else {
continue;
}
currentNumber++;
}
return evenArray;
}
}
storage.length does not change throughout the program's execution, as the array is already allocated. You first while loop is thus wrong, as 100 is not less than 100, it will never execute. Instead, you could use a simple for loop:
for (int j = 0; j < storage.length; ++j) {
int testVariable = 0 + (int) (Math.random() * ((25 - 0) + 1));
storage[j] = testVariable;
}
although it does not run
Yes it does. It's just that the execution can get stuck in the infinite loops in the OddNumbers and EvenNumbers methods.
Take a closer look at this:
while ( currentNumber <= 99 ) {
if ( storage[currentNumber] % 2 != 0 ) {
oddArray[currentNumber] = currentValue;
}
else {
continue;
}
The problem is that when storage[currentNumber] is even,
the program executes the else branch with the continue statement,
and since currentNumber hasn't changed, and so storage[currentNumber] hasn't changed either, it's still even, and the else branch will be executed again, and again, and again, forever. EvenNumber has the same problem too.
Here's a fix for OddNumbers:
public static int[] OddNumbers(int[] storage) {
int[] oddArray = new int[storage.length];
int oddIndex = 0;
for (int num : storage) {
if (num % 2 != 0) {
oddArray[oddIndex++] = num;
}
}
return Arrays.copyOf(oddArray, oddIndex);
}
An extra touch I did in this method is the Arrays.copyOf call,
chopping off the excess elements of the array that would be otherwise 0.
Then when you print the content of this array in main, write like this:
System.out.println("The odd numbers are: " + "\n");
for (int num : oddArray) {
System.out.println(num);
}
Follow the same pattern to fix EvenNumbers.
As #Mureinik pointed out,
the loop in main populating storage is also broken.
And you have several other coding issues,
for example the random number generation is particularly ugly and using an obsolete technique.
The complete improved implementation:
import java.util.Arrays;
import java.util.Random;
public class Assignment8 {
public static void main(String[] args) {
Random random = new Random();
int[] storage = new int[100];
for (int i = 0; i < storage.length; i++) {
storage[i] = random.nextInt(25);
}
System.out.println("The odd numbers are: " + "\n");
int oddArray[] = OddNumbers(storage);
for (int num : oddArray) {
System.out.println(num);
}
System.out.println("\n" + "The even numbers are: " + "\n");
int evenArray[] = EvenNumbers(storage);
for (int num : evenArray) {
System.out.println(num);
}
}
public static int[] OddNumbers(int[] storage) {
int index = 0;
int[] result = new int[storage.length];
for (int num : storage) {
if (num % 2 != 0) {
result[index++] = num;
}
}
return Arrays.copyOf(result, index);
}
public static int[] EvenNumbers(int storage[]) {
int index = 0;
int[] result = new int[storage.length];
for (int num : storage) {
if (num % 2 == 0) {
result[index++] = num;
}
}
return Arrays.copyOf(result, index);
}
}

Java loop through array

How do you loop through an array until you you reach the last 50 elements of your array then??
say I have this binary search code:
public class Binary
{
public static final int NOT_FOUND = -1;
public static <AnyType extends Comparable<? super AnyType>>
int binarySearch( AnyType [ ] a, AnyType x )
{
int low = 0;
int high = a.length - 1;
int mid;
while( low <= high )
{
mid = ( low + high ) / 2;
if( a[ mid ].compareTo( x ) < 0 )
low = mid + 1;
else if( a[ mid ].compareTo( x ) > 0 )
high = mid - 1;
else
return mid;
}
return NOT_FOUND; // NOT_FOUND = -1
}
// Test program
public static void main( String [ ] args )
{
int SIZE = 8;
Integer [ ] a = new Integer [ SIZE ];
for( int i = 0; i < SIZE; i++ )
a[ i ] = i * 2;
for( int i = 0; i < SIZE * 2; i++ )
System.out.println( "Found " + i + " at " +
binarySearch( a, i ) );
}
}
I would like to search the given array till I reach to the last 50 elements of this array, then the search is concluded with sequential look up of 50 elements.
My question is that how can I construct such a loop and how to jump to the method that does the linear search.
Before you calculate mid, do something like
if(high - low + 1 <= 50) return linearSearch(low, high, a, x);
Then your linearSearch just has to iterator from low to high to find x, or else return NOT_FOUND.

Permutation of string limited by another string

I'm having a bit of trouble, mainly because I do not have much experience with recursive methods and a non-recursive method for my problem seems incredibly complex. However, I might just be looking at this the wrong way.
What I'm trying to accomplish is this:
Given one string, I want to overlap them and display all potential combinations. It's probably easiest if I explain my problem and solution with binary representations.
Given 0000 and 1111,
I want my method to return:
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
This seems incredibly trivial, but I just can't seem to figure out the most efficient way of doing this. I was thinking either recursion or maybe a binary tree. Either way, I'm having trouble setting it up.
Any ideas would be greatly appreciated.
Thank you!
Poor, but passable iterative approach.
import java.util.BitSet;
public class p {
static StringBuilder sb;
// Add one and return true on overflow
static boolean inc( BitSet s, int maxlen ) {
int i = 0;
for( ; i < maxlen; ++i ) {
if( s.get( i )) { s.clear( i ); }
else { break; }
}
if( i == maxlen )
return true;
s.set( i );
return false;
}
static String form( String x, String y, BitSet mask ) {
sb.setLength( 0 );
for( int i = 0; i < x.length(); ++i )
sb.append( (mask.get( x.length() - i - 1) ? y : x).charAt( i ));
return sb.toString();
}
public static void perms( String x, String y ) {
assert( x.length() == y.length() );
BitSet bits = new BitSet( x.length() );
do {
System.out.println( form( x, y, bits ));
} while( ! inc( bits, x.length() ));
}
public static void main( String[] args ) {
sb = new StringBuilder( args[0].length() );
perms( args[0], args[1] );
}
}
Your binary explanation actually gave me a very good idea for doing this. You can simply use a for loop and increment the variable until it is 2 ^ str.Length * 2 - 1. In each iteration, one permutation is the characters from the first string where the corresponding bit in the variable is 0, or from the second string where it is 1. Pseudo-code:
for i = 0 to 2 ^ string1.length * 2 - 1
s = ""
for j = 0 to string1.length - 1
if (i >> j) & 1 == 1 then
s = string1[string1.length - j] + s
else
s = string2[string2.length - j] + s
end if
end for
end for
You want this:
/*************************************************************************
* Compilation: javac Permutations.java
* Execution: java Permutations N
*
* Enumerates all permutations on N elements.
* Two different approaches are included.
*
* % java Permutations 3
* abc
* acb
* bac
* bca
* cab
* cba
*
*************************************************************************/
public class Permutations {
// print N! permutation of the characters of the string s (in order)
public static void perm1(String s) { perm1("", s); }
private static void perm1(String prefix, String s) {
int N = s.length();
if (N == 0) System.out.println(prefix);
else {
for (int i = 0; i < N; i++)
perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
}
}
// print N! permutation of the elements of array a (not in order)
public static void perm2(String s) {
int N = s.length();
char[] a = new char[N];
for (int i = 0; i < N; i++)
a[i] = s.charAt(i);
perm2(a, N);
}
private static void perm2(char[] a, int n) {
if (n == 1) {
System.out.println(a);
return;
}
for (int i = 0; i < n; i++) {
swap(a, i, n-1);
perm2(a, n-1);
swap(a, i, n-1);
}
}
// swap the characters at indices i and j
private static void swap(char[] a, int i, int j) {
char c;
c = a[i]; a[i] = a[j]; a[j] = c;
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String elements = alphabet.substring(0, N);
perm1(elements);
System.out.println();
perm2(elements);
}
}
Just for laughs, a very inefficient recursive solution:
import java.util.ArrayList;
public class pp {
static ArrayList<String> append(
String x, String y, ArrayList<String> ss ) {
if( x.length() == 0 )
return ss;
ArrayList<String> r = new ArrayList<String>( ss.size() * 2);
for( int i = 0; i < ss.size(); ++i ) {
r.add( ss.get( i ) + x.charAt( 0 ));
r.add( ss.get( i ) + y.charAt( 0 ));
}
return append( x.substring(1), y.substring(1), r );
}
public static void main( String[] args ) {
assert args[0].length() == args[1].length();
ArrayList<String> ss = new ArrayList<String>( 1 );
ss.add( "" );
ArrayList<String> r = append( args[0], args[1], ss );
for( int i = 0; i < r.size(); ++i )
System.out.println( r.get( i ));
}
}

Categories

Resources