Selection sorting java array - java

I'm doing a project in which I must generate an array list the size of a user input(in this case i chose 4), with random numbers between -1000 and 1000. Then I have to have it do a selection sort and display both the unsorted numbers in output1 and the sorted numbers in output2 Heres what I have thus far
ArrayList <Integer> unSortedNumbers = new ArrayList <Integer>();
Integer [] numberSort;
...
private void SortActionPerformed(java.awt.event.ActionEvent evt) {
String input, sortedNumberOutput = "";
int int1, int2 = 0, min = -1000, max = 1000, j, minimum, temp = 0;
input = Input.getText();
int1 = Integer.parseInt(input);
Random number = new Random();
while (int2 < int1) {
for (int i = 0; i < int1; i++) {
int randomInt = number.nextInt(max - min + 1) + min;
unSortedNumbers.add(randomInt);
int1--;
}
}
numberSort = new Integer[unSortedNumbers.size()];
unSortedNumbers.toArray(numberSort);
for (int i = 0; i < numberSort.length; i++) {
sortedNumberOutput += numberSort[i] + (i != numberSort.length ? "," : "");
}
if (Selection.isSelected() && Ascending.isSelected()) {
for (int i = 0; i < numberSort.length - 1; i++) {
minimum = numberSort[i];
for (j = i + 1; j <= numberSort.length - 1; j++) {
if (minimum > numberSort[j]) {
numberSort[temp] = numberSort[i];
numberSort[i] = numberSort[j];
numberSort[j] = numberSort[temp];
}
}
}
}
Output1.setText("Unsorted Numbers " + unSortedNumbers);
Output2.setText("Sorted Numbers " + numberSort);
unSortedNumbers.clear();
numberSort = null;
}
So when I run that, the unSortedNumbers are displayed properly in output1, but instead of displaying the sorted numbers in output2, it displays this :
Sorted Numbers [Ljava.lang.Integer;#7a279c
I'm not sure why this is happening, my could is probably wrong somewhere, If you can help, thank you!

What you are seeing is the result of the default toString() method being called on an array object. [Ljava.lang.Integer tells you it is an array of Integers and the #7a279c gives you the hex string of the hashcode. Do as ZouZou suggests and use Arrays.toString(unSortedNumbers);

Related

Finding Similar Birthday through structure data

Hey guys I am trying to get the number of people who have the same birthday but this solution isn't working.This program is showing 0.0% .Please help me ...!.
public double calculate(int size, int count) {
int matches = 0;//initializing an integer variable
boolean out = false;
List<Integer> days=new ArrayList<Integer>();// creating arraylist name days of type int
for (int j = 0; j <count; j++) {
for (int i = 0; i < size; i++) {// initializing for loop till less than size
Random rand = new Random(); // creating an object of random function
int Brday = rand.nextInt(364) + 0;//initializing the limit of randomc number chozen
days.add(Brday); //adding values to arraylist
}
for (int l = 0; l < size; l++) {
int temp = l;//assigning value of l to a variable
for (int k = l + 1; k < size; k++) {
if (days.get(k) == temp) {// check statement to check values are same
matches++;//incrementing variable
out = true;
mOut.print("Count does have same birthday" + matches);
break;
} else {
mOut.print("does not have same birthday");
}
}
if (out) {
out = false;
break;
}
}
}
double prob = (double) matches / count;
mOut.print("The probability for two students to share a birthday is " + prob*100 + ".");
return prob;//returning double value of the function
}
Actually, you get either 0 percent or 100 percent with your code. Try invoking it with calculate(100, 100) if you want to see.
There are two things that are wrong in this code. First, if you run the simulation more than once (count > 1) then you never clear the list of birthdays before the second iteration.
Your method should begin with:
public double calculate(int size, int count) {
int matches = 0;
boolean out = false;
List<Integer> days;
for (int j = 0; j <count; j++) {
days = new ArrayList<Integer>();
Secondly, you're not comparing two birthdays but you're comparing a birthday to the index in the list.
This line:
int temp = l;//assigning value of l to a variable
Should read:
int temp = days.get(l); // Remember the birthday at index l
With those changes you'll get a much better result.

Getting the most "popular" number from array

I need for homework to get the most "popular" number in an array (the number in the highest frequency), and if there are several numbers with the same number of shows, get some number randomly.
After more then three hours of trying, and either searching the web, this is what I got:
public int getPopularNumber(){
int count = 1, tempCount;
int popular = array[0];
int temp = 0;
for ( int i = 0; i < (array.length - 1); i++ ){
if ( _buses[i] != null )
temp = array[i];
tempCount = 0;
for ( int j = 1; j < _buses.length; j++ ){
if ( array[j] != null && temp == array[j] )
tempCount++;
}
if ( tempCount > count ){
popular = temp;
count = tempCount;
}
}
return popular;
}
This code work, but don't take into account an important case- if there is more than one number with the same count of shows. Then it just get the first one.
for example: int[]a = {1, 2, 3, 4, 4, ,5 ,4 ,5 ,5}; The code will grab 4 since it shown first, and it's not random as it should be.
Another thing- since it's homework I can't use ArrayList/maps and stuff that we still didn't learn.
Any help would be appreciated.
Since they didn't give you any time complexity boundary, you can "brute force" the problem by scanning the the array N^2 times. (disclaimer, this is the most intuitive way of doing it, not the fastest or the most efficient in terms of memory and cpu).
Here is some psuedo-code:
Create another array with the same size as the original array, this will be the "occurrence array"
Zero its elements
For each index i in the original array, iterate the original array, and increment the element in the occurrence array at i each time the scan finds duplicates of the value stored in i in the original array.
Find the maximum in the occurrence array
Return the value stored in that index in the original array
This way you mimic the use of maps with just another array.
If you are not allowed to use collection then you can try below code :
public int getPopularNumber(){
int inputArr[] = {1, 2, 3, 4, 4, 5 ,4 ,5 ,5}; // given input array
int[] tempArr = new int[inputArr.length];
int[] maxValArr = new int[inputArr.length];
// tempArr will have number as index and count as no of occurrence
for( int i = 0 ; i < inputArr.length ; i++){
tempArr[inputArr[i]]++;
}
int maValue = 0;
// find out max count of occurrence (in this case 3 for value 4 and 5)
for( int j = 0 ; j < tempArr.length ; j++){
maValue = Math.max(maValue, tempArr[j]);
}
int l =0;
// maxValArr contains all value having maximum occurrence (in this case 4 and 5)
for( int k = 0 ; k < tempArr.length ; k++){
if(tempArr[k] == maValue){
maxValArr[l] = k;
l++;
}
}
return maxValArr[(int)(Math.random() * getArraySize(maxValArr))];
}
private int getArraySize(int[] arr) {
int size = 0;
for( int i =0; i < arr.length ; i++){
if(arr[i] == 0){
break;
}
size++;
}
return size;
}
that's hard as hell :D
After some trying, I guess I have it (If there will be 2 numbers with same frequency, it will return first found):
int mostPopNumber =0;
int tmpLastCount =0;
for (int i = 0; i < array.length-1; i++) {
int tmpActual = array[i];
int tmpCount=0;
for (int j = 0; j < array.length; j++) {
if(tmpActual == array[j]){
tmpCount++;
}
}
// >= for the last one
if(tmpCount > tmpLastCount){
tmpLastCount = tmpCount;
mostPopNumber = tmpActual;
}
}
return mostPopNumber;
--
Hah your code give me idea- you cant just remember last most popular number, btw I've found it solved there Find the most popular element in int[] array
:)
EDIT- after many, and many years :D, that works well :)
I've used 2D int and Integer array - you can also use just int array, but you will have to make more length array and copy actual values, Integer has default value null, so that's faster
Enjoy
public static void main(String[] args) {
//income array
int[] array= {1,1,1,1,50,10,20,20,2,2,2,2,20,20};
//associated unique numbers with frequency
int[][] uniQFreqArr = getUniqValues(array);
//print uniq numbers with it's frequency
for (int i = 0; i < uniQFreqArr.length; i++) {
System.out.println("Number: " + uniQFreqArr[i][0] + " found : " + uniQFreqArr[i][1]);
}
//get just most frequency founded numbers
int[][] maxFreqArray = getMaxFreqArray(uniQFreqArr);
//print just most frequency founded numbers
System.out.println("Most freq. values");
for (int i = 0; i < maxFreqArray.length; i++) {
System.out.println("Number: " + maxFreqArray[i][0] + " found : " + maxFreqArray[i][1]);
}
//get some of found values and print
int[] result = getRandomResult(maxFreqArray);
System.out.println("Found most frequency number: " + result[0] + " with count: " + result[1]);
}
//get associated array with unique numbers and it's frequency
static int[][] getUniqValues(int[] inArray){
//first time sort array
Arrays.sort(inArray);
//default value is null, not zero as in int (used bellow)
Integer[][] uniqArr = new Integer[inArray.length][2];
//counter and temp variable
int currUniqNumbers=1;
int actualNum = inArray[currUniqNumbers-1];
uniqArr[currUniqNumbers-1][0]=currUniqNumbers;
uniqArr[currUniqNumbers-1][1]=1;
for (int i = 1; i < inArray.length; i++) {
if(actualNum != inArray[i]){
uniqArr[currUniqNumbers][0]=inArray[i];
uniqArr[currUniqNumbers][1]=1;
actualNum = inArray[i];
currUniqNumbers++;
}else{
uniqArr[currUniqNumbers-1][1]++;
}
}
//get correctly lengthed array
int[][] ret = new int[currUniqNumbers][2];
for (int i = 0; i < uniqArr.length; i++) {
if(uniqArr[i][0] != null){
ret[i][0] = uniqArr[i][0];
ret[i][1] = uniqArr[i][1];
}else{
break;
}
}
return ret;
}
//found and return most frequency numbers
static int[][] getMaxFreqArray(int[][] inArray){
int maxFreq =0;
int foundedMaxValues = 0;
//filter- used sorted array, so you can decision about actual and next value from array
for (int i = 0; i < inArray.length; i++) {
if(inArray[i][1] > maxFreq){
maxFreq = inArray[i][1];
foundedMaxValues=1;
}else if(inArray[i][1] == maxFreq){
foundedMaxValues++;
}
}
//and again copy to correctly lengthed array
int[][] mostFreqArr = new int[foundedMaxValues][2];
int inArr= 0;
for (int i = 0; i < inArray.length; i++) {
if(inArray[i][1] == maxFreq){
mostFreqArr[inArr][0] = inArray[i][0];
mostFreqArr[inArr][1] = inArray[i][1];
inArr++;
}
}
return mostFreqArr;
}
//generate number from interval and get result value and it's frequency
static int[] getRandomResult(int[][] inArray){
int[]ret=new int[2];
int random = new Random().nextInt(inArray.length);
ret[0] = inArray[random][0];
ret[1] = inArray[random][1];
return ret;
}

Checking if a value is equal to another within a loop(java)

I need to do find values 10 different times or until the value of difference is found twice. Im not really sure how to break the loop if found.
Here goes the code:
public class Algorithm {
private static int small; //global field so it is usable in zeros method
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int number = 0;
// object array to use collections class
Integer [] digit = new Integer [4];
// loop for handling 10 different numbers
for (int index=0; index<10; index++){
number = random();
String smaller =""; String bigger=""; // strings used to display zeros/ easier processing
for (int i = 3; i >= 0; i--) {
digit[i] = number % 10;
number /= 10;
}
// prints initial random number
System.out.println(digit[0] + " " +digit[1] + " " +
digit[2]+ " "+ digit[3] + " Random Number");
// sorts the digits increasingly
Arrays.sort(digit);
// adds the numbers to the smaller string
for (int i=0; i <digit.length; i++){
smaller += digit[i];
}
// convert string to int
int small = Integer.parseInt(smaller);
String zerosNr = null;
zerosNr = zeros();
System.out.printf(" smaller " +zerosNr, small );
// Reverse sort order and adds results to bigger for displaying
Arrays.sort(digit, Collections.reverseOrder());
for (int i=0; i < digit.length; i++){
bigger += digit[i];
}
int big = Integer.parseInt(bigger);
System.out.println("bigger " + big);
int difference = 0;
int [] copy;
copy = new int[11];
difference = big - small;
copy[index] = big - small;
// here i tried to do it
System.out.println( index + " Difference "+ difference);
if (difference == copy[index+1])
break;
}
}
//method that creates random numbers
public static int random(){
final int n = 9999;
Random rad = new Random();
int number = rad.nextInt(n);
return number;
}
//method that adds zeros where necesarry to smaller
public static String zeros(){
String zerosNr = null;
if (small < 1000)
return " %04d\n ";
else if (small < 100)
return " %03d\n ";
else
return " %02d\n ";
}
}
A problem with your approach is that you're trying to break based on "future" values, i.e. when you compare difference == copy[index+1] you have not yet populated copy[index+1]. You just haven't gotten that far yet.
Instead, you should be comparing difference to past values of copy. And you'll have to compare each difference to all preceding values of copy. So something like:
boolean iShouldBreak = false;
for (int j = 0; j < index; j++) {
if (difference == copy[j]) {
iShouldBreak = true;
}
}
if (iShouldBreak)
{
break;
]
You'll want to use a label:
For example:
OUTERFOR: for(Object1 object1: objects){
for(Object2 object2: object1.getMoreObjects()){
if( object2.isWhatever()) {
break OUTERFOR;
}
}// inner for loop ends here
}// outer for loop ends here

Java - I have a 2D array. How can I add blocks of it together?

I'm not sure if this is the best way to ask my question.
Basically, I have a 2D array that is being built from a text file.
It takes the first two int's for the dimensions. Then fills the array with the remaining data. That part is working fine.
In my array, I need to add each value with each adjacent value. To determine which value, when added with all of its adjacent values, is the highest. I need to do the reverse also, to find the lowest.
What kind of loop or function could I use to accomplish this? I'l create a small example below.
2 4 3 7 8
1 5 7 9 2
2 9 2 5 7
So the 2 would become a 7, the 4 would become a 14, and so on. After the math is done I need to detect which coordinate in the array is the largest number.
For simplicity, lets use the example you provided. The array is 5 by 3. Lets call the array data Try this
int totals[5][3];
for(int x = 0;x<5;x++){
for(int y = 0;y<5;y++){
int total = data[x][y]
if(x>0){
total+= data[x-1][y];
}
if(x<4){
total+= data[x+1][y];
}
if(y>0){
total+= data[x][y-1];
}
if(y<2){
total+= data[x][y+1];
}
totals[x][y] = total;
}
}
Then loop through the arrays and compare the values.
My approach would be the following:
public int largeNeighbor(int[][] numbers) {
int max = 0;
for (int i = 0; i < numbers.length ; i++) {
for (int j = 0; j < numbers[0].length; j++) {
int temp = numbers[i][j];
if (i > 0) {
temp += numbers[i-1][j];
}
if (i < numbers.length - 1) {
temp += numbers[i+1][j];
}
if (j > 0) {
temp += numbers[i][j-1];
}
if (j < numbers[0].length - 1) {
temp += numbers[i][j+1];
}
if (temp > max) {
max = temp;
}
}
}
return max;
}
When given a 2D integer array, the method will compare every value with added neighbors to the current max value.
You explained your situation well but in future questions you should include what you already have in small blocks of code. :)
I did this for fun. Hope someone enjoys.
import java.lang.ArrayIndexOutOfBoundsException;
import java.util.Random;
public class HelloWorld{
int smallest = 10000;
int largest = -1;
int xCoords_small = -1;
int yCoords_small = -1;
int xCoords_large = -1;
int yCoords_large = -1;
//Make it as big as you want!!!!!
int iSize = 5;
int jSize = 3;
int[][] totals = new int[iSize][jSize];
int[][] yourNumbers = new int[iSize][jSize];
Random r = new Random();
//Initializes the array. With random numbers. Yours would read in the
//the file here and initialize the array.
public HelloWorld(){
for(int i = 0; i < iSize; i++){
for(int j = 0; j < jSize; j++){
yourNumbers[i][j] = r.nextInt(10);
}
}
}
//Calculates the total and whether or not it's the largest number and
//tracks position in array and the total number.
//It has crumby error catching but this way you can make your array
//as big as you want without needing to change anything but the two
//two size variables.
public void calculate(){
for(int i = 0; i < iSize; i++){
for(int j = 0; j < jSize; j++){
int total = 0;
try{
total += yourNumbers[i][j];
}catch(ArrayIndexOutOfBoundsException ex ){
//do nothing
}
try{
total += yourNumbers[i-1][j];
}catch(ArrayIndexOutOfBoundsException ex){
//do nothing
}
try{
total += yourNumbers[i][j-1];
}catch(ArrayIndexOutOfBoundsException ex){
//do nothing
}
try{
total += yourNumbers[i+1][j];
}catch(ArrayIndexOutOfBoundsException ex){
//do nothing
}
try{
total += yourNumbers[i][j+1];
}catch(ArrayIndexOutOfBoundsException ex){
//do nothing
}
totals[i][j] = total;
if(total > largest){
largest = total;
xCoords_large = i;
yCoords_large = j;
}
if(total < smallest){
smallest = total;
xCoords_small = i;
yCoords_small = j;
}
System.out.println(total);
}
}
System.out.println(largest + " = Largest Total and it's beginning number in your 2D array. " + xCoords_large+ "," + yCoords_large+ " Its value = " + yourNumbers[xCoords_large][yCoords_large]);
System.out.println(smallest + " = Smallest Total and it's beginning number in your 2D array. " + xCoords_small + "," + yCoords_small + " Its value = " + yourNumbers[xCoords_small][yCoords_small]);
}
public static void main(String []args){
HelloWorld hw = new HelloWorld();
hw.calculate();
}
}

SelectionSort and BubbleSort - how to count number of comparisons and number swapping?

First of all, I have seen a similar question relating to C++, but I didn't quite understand it - plus my question is about Java.
Basically I have coded two methods that can use SelectionSort and BubbleSort on an array parsed in. While I believe I have the methods working correctly (I have run tests and they all have sorted the numbers in ascending order), I am not sure if I am counting the number of comparisons and number swaps correctly. If someone is able to test my code below and offer some feedback, I will be very grateful.
Note: I can zip up my Java project files and send them to anyone if needed.
BubbleSort method:
public String bubbleSort(int[] numbers)
{
System.out.println("******|Bubble Sort|******");
StringBuilder originalArray = new StringBuilder();
for(int i = 0; i <= numbers.length - 1; i++)
{
originalArray.append(numbers[i] + " ");
}
System.out.println("Original array: " + originalArray);
int temp; // temporary variable
//Set boolean variable to true,
//to allow the first pass.
boolean pass = true;
int comparisons = 0;
int swaps = 0;
//While a pass can be made,
while(pass)
{
//Set the boolean value to false,
//indicating a number swap could
//be made.
pass = false;
for(int i = 0; i < numbers.length - 1; i++)
{
//increment the number of comparisons by 1.
comparisons++;
if(numbers[i] > numbers[i+1])
{
temp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i+1] = temp;
//increment the amount of swaps made by 1,
//to put numbers in correct order.
swaps++;
pass = true;
}
}
}
//Create a StringBuilder object - to hold
//the output of sorted numbers.
StringBuilder sb = new StringBuilder();
//Loop through the now sorted array - appending
//each subsequent number in the array to the
//StringBuilder object.
for(int i = 0; i < numbers.length; i++)
{
sb.append(numbers[i] + " ");
}
//Return the final results of the sorted array.
return "Sorted Array (asc): " + sb.toString() + "\nComparisons made: " + comparisons
+ "\nSwaps made: " + swaps;
}
SelectionSort method
public String selectionSort(int[] numbers)
{
System.out.println("******|Selection Sort|******");
StringBuilder originalArray = new StringBuilder();
int comparisons = 0;
int swaps = 0;
for(int i = 0; i <= numbers.length - 1; i++)
{
originalArray.append(numbers[i] + " ");
}
System.out.println("Original array: " + originalArray);
//Declare variable to hold first element
int first;
//declare temporary variable, to be used in
//swapping integers.
int temp;
for(int x = numbers.length - 1; x > 0; x--)
{
first = 0;
comparisons++;
for(int y = 1; y <= x; y++)
{
//comparisons++;
if(numbers[y] > numbers[first])
{
first = y;
//comparisons++;
swaps++;
}
temp = numbers[first];
numbers[first] = numbers[x];
numbers[x] = temp;
//swaps++;
}
}
//Create a StringBuilder object - to hold
//the output of sorted numbers.
StringBuilder sb = new StringBuilder();
//Loop through the now sorted array - appending
//each subsequent number in the array to the
//StringBuilder object.
for(int i = 0; i < numbers.length; i++)
{
sb.append(numbers[i] + " ");
}
//Return the final results of the sorted array.
return "Sorted Array (asc): " + sb.toString() + "\nComparisons made: " + comparisons
+ "\nSwaps made: " + swaps;
}
For BUBBLE SORT:
Key comparisons -> (n*(n-1))/2
Item assignments (swaps) -> 3*(n-1)
For SELECTION SORT:
Key comparisons -> (n*(n-1))/2 (same as bubble)
Item assignments (swaps) -> (n*(n-1))/4
(Note that n is the number of your array size)

Categories