Java Bubble Sorting Array Wrong Output - java

just to preface, I am very new to coding in Java, or coding in general to be exact.
Here is what I am trying to accomplish. It is a project, where we take a input file of numbers, one integer being a competitor number, the next being their weight for a fish they caught, (Looking like this 3 26.7 (new line per two numbers) 2 2.6.. so on and so on), put them in a array, then sort them in one way or another. Now, I will post the whole code, but it is only the last method, "sort", that I am having difficulties right now.
The method is a bubble sorting method. The way I am approaching it is so that it will take the first array, compare it with the second array to see if it is less than, then swap the two competitor numbers if the logic is correct so that I can print the competitor numbers in the main method, and call the appropriate weight for the competitor (which is previously compiled in past if/then loop). Note, I do not have it currently trying to print the competitor weight.
I believe I am on the right track for this, but for some reason, the numbers printed, after calling the sort method, are not correct. If you could tell me what I am doing wrong, that would be greatly helpful. Thanks.
import java.io.*;
import java.util.Scanner;
public class Project8
{
public static void main(String[] args)
throws FileNotFoundException
{
Scanner inF = new Scanner(new File("data7.txt"));
PrintWriter outF = new PrintWriter(new File("pro7out.txt"));
int [] arrayNum = new int[7];
int [] sortedNum = new int[7];
double [] arrayWeight = new double[7];
int place, firstplace, lastplace;
double weight;
String line;
String entries[];
outF.printf("My name - Project 7: 4/10/18%nResults of the Rocking JR Fishing Contest%n");
outF.printf("Competitor Total%n Number Weight%n");
for (int m = 0; m < 7; m++)
{
arrayNum[m] = m + 1;
}
while (inF.hasNextLine())
{
line = inF.nextLine();
entries = line.split(" +");
place = Integer.parseInt(entries[0]);
weight = Double.parseDouble(entries[1]);
if (place == 1)
arrayWeight[0] += weight;
else if (place == 2)
arrayWeight[1] += weight;
else if (place == 3)
arrayWeight[2] += weight;
else if (place == 4)
arrayWeight[3] += weight;
else if (place == 5)
arrayWeight[4] += weight;
else if (place == 6)
arrayWeight[5] += weight;
else
arrayWeight[6] += weight;
}
for (int k = 0; k < 7; k++)
outF.printf("%5d %15.2f%n", arrayNum[k], arrayWeight[k]);
firstplace = first(arrayNum, arrayWeight);
lastplace = last(arrayNum, arrayWeight);
sortedNum = sort(arrayNum, arrayWeight);
outF.printf(" Winner is%n %d %3.2f%n", firstplace, arrayWeight[firstplace-1]);
outF.printf(" Not as successful%n %d %3.2f%n", lastplace, arrayWeight[lastplace-1]);
for (int k = 0; k < 7; k++)
outF.printf("%d", sortedNum[k]);
outF.printf(" Contest Over%n");
inF.close();
outF.close();
}
public static int first(int number[], double weight[])
{
int firstplace=0;
double max=0;
for (int k = 0; k < 7; k++)
{
if (weight[k] > max)
{
max = weight[k];
firstplace = number[k];
}
}
return firstplace;
}
public static int last(int number[], double weight[])
{
int lastplace=0;
double minimum=weight[0];
for (int k = 0; k < 7; k++)
{
if (weight[k] < minimum)
{
minimum = weight[k];
lastplace = number[k];
}
}
return lastplace;
}
public static int[] sort(int number[], double weight[])
{
int n = number.length;
int tempNum = 0;
for (int i = 0; i < n; i++)
{
for (int j = 1; j < (n-1); j++)
{
if (weight[j - 1] < weight[j])
{
tempNum = number[j - 1];
number[j - 1] = number[j];
number[j] = tempNum;
}
}
}
return number;
}
}

Related

How to find the sum of factorial of all numbers in a series?

I want to create a program to find the sum of factorial of all numbers in a series till 20.
I have to find 's' in s = 1 + (1*2) + (1*2*3) + ...(1*2*3...20).
I tried a program but it is not working. I am using BlueJ IDE.
int a =1;
int s = 0;
for(int i = 1; i <= 10; i++)
{
while (i >0)
{
a = a * i;
i--;
}
s = s+a;
}
System.out.println(s);
The compiler does not show any error message but when I run the program the JVM(Java Virtual Machine) keeps loading and the output screen does not show up.
You can try this one :
public class Main
{
public static void main (String[]args)
{
int fact = 1;
int sum = 0;
int i, j = 1;
for (i = 1; i <= 20; i++)
{
for (j = 1; j <= i; j++)
{
fact = fact * j;
}
sum += fact;
System.out.println ("sum = " + sum);
fact = 1;
}
}
}
Always give proper variable name and Try to avoid to use same variable at different places i.e you have use variable i in outer and inner loop which is not good habit.
You should be using a different loop variable name in your inner loop, and you also need to use a long to store your sum. In fact, I would first write a method to multiply up to a number in the series. Like,
static long multiplyTo(int n) {
long r = 1L;
for (int i = 2; i <= n; i++) {
r *= i;
}
return r;
}
Then you can invoke that and calculate your sum with a simple loop. Like,
long sum = 0L;
for (int i = 1; i <= 20; i++) {
sum += multiplyTo(i);
}
System.out.println(sum);
I get
2561327494111820313
Using streams:
long s = LongStream.rangeClosed(1, 20)
.map(upper -> LongStream.rangeClosed(1, upper)
.reduce(1, (a, b) -> a * b))
.sum();
System.out.println(s);
Prints 2561327494111820313
I did the same program using Scanner Class
import java.util.*;
class Sum_Factorial
{
public static void main()
{
Scanner in = new Scanner(System.in);
int i; //Denotes Integer
int n; //Denotes Number
int f=1; //Denotes Factorial
int s=0; //Denotes Sum
System.out.println("Enter the value of N : ");
n=in.nextInt();
for(i=1; i<=n; i++)
{
f=f*i;
s=s+f;
}
System.out.println("Sum of the factorial numbers is "+s);
}
}

Determining if a program is fast, memory-efficient and does not have large time-complexity

Could someone please help me how I could determine whether my program is memory-efficient, fast and has low time-complexity? For one of my programs, I implemented merge sort and then called some methods here and there but since it has around 100 lines of code, I am skeptical whether it is memory efficient. Thanks guys
import java.util.*;
public class Question6 {
static void mergeSort(Integer arr1[], int o, int k, int x) {
int num1 = k - o + 1;
int num2 = x - k;
int temp1[] = new int[num1]; //creation of two temporary arrays to store in
int temp2[] = new int[num2];
for (int i = 0; i < num1; ++i) //for loops to copy the data to the temporary arrays
temp1[i] = arr1[o + i];
for (int j = 0; j < num2; ++j)
temp2[j] = arr1[k + 1 + j];
int i = 0, j = 0; //starting position of temporary arrays
int s = o; //starting position of the merged two temporary arrays
while (i < num1 && j < num2) {
if (temp1[i] <= temp2[j]) {
arr1[s] = temp1[i];
i++;
} else {
arr1[s] = temp2[j];
j++;
}
s++;
}
//code to copy elements from temp1
while (i < num1) {
arr1[s] = temp1[i];
i++;
s++;
}
//code to copy elements from temp2
while (j < num2) {
arr1[s] = temp2[j];
j++;
s++;
}
}
void forSorting(Integer arr2[], Integer t, Integer x) //main method that carries out merge sort
{
if (t < x) {
// Find the middle point
Integer a = (t + x) / 2;
// Sort first and second halves
forSorting(arr2, t, a);
forSorting(arr2, a + 1, x);
// Merge the sorted halves
mergeSort(arr2, t, a, x);
}
}
public static void main(String[] args) {
Question6 qs = new Question6();
Scanner sc = new Scanner(System.in);
Integer[] duplicate = new Integer[10];
System.out.println("Please input the numbers to be checked for repetition.");
for (int x = 0; x < 10; x++) {
duplicate[x] = sc.nextInt(); //filling array
}
int length = duplicate.length;
qs.forSorting(duplicate, 0, length - 1); //calling method forSorting
System.out.println(Arrays.toString(duplicate)); //displays the array which user fills
List<Integer> list = Arrays.asList(duplicate); //makes the array duplicate available as a list
Set<Integer> set = new LinkedHashSet<Integer>(list);
for ( Integer element : set) {
if(Collections.frequency(list, element) > 1) {
System.out.println(" Duplicate: " + element);
}
}
}
}
You can use Profiler. For Java - JProfiler, VisualVM, etc. You can check there all you looking for - how much memory yours algorithms need, the time complexity, and some more stuff.

Find smallest number K , if exists, such that product of its digits is N. Eg:when N = 6, smallest number is k=16(1*6=6) and not k=23(2*3=6)

I have made this program using array concept in java. I am getting Exception as ArrayIndexOutOfBound while trying to generate product.
I made the function generateFNos(int max) to generate factors of the given number. For example a number 6 will have factors 1,2,3,6. Now,i tried to combine the first and the last digit so that the product becomes equal to 6.
I have not used the logic of finding the smallest number in that array right now. I will do it later.
Question is Why i am getting Exception as ArrayIndexOutOfBound? [i couldn't figure out]
Below is my code
public class SmallestNoProduct {
public static void generateFNos(int max) {
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
}
}
smallestNoProduct(ar);
}
public static void smallestNoProduct(int x[]) {
int j[] = new int[x.length];
int p = x.length;
for (int d = 0; d < p / 2;) {
String t = x[d++] + "" + x[p--];
int i = Integer.parseInt(t);
j[d] = i;
}
for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}
}
public static void main(String s[]) {
generateFNos(6);
}
}
****OutputShown****
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at SmallestNoProduct.smallestNoProduct(SmallestNoProduct.java:36)
at SmallestNoProduct.generateFNos(SmallestNoProduct.java:27)
at SmallestNoProduct.main(SmallestNoProduct.java:52)
#Edit
The improved Code using array only.
public class SmallestNoProduct {
public static void generateFNos(int max) {
int s = 0;
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
s++;
}
}
for (int g = 0; g < s; g++) {
System.out.println(ar[g]);
}
smallestNoProduct(ar, s);
}
public static void smallestNoProduct(int x[], int s) {
int j[] = new int[x.length];
int p = s - 1;
for (int d = 0; d < p;) {
String t = x[d++] + "" + x[p--];
System.out.println(t);
int i = Integer.parseInt(t);
j[d] = i;
}
/*for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}*/
}
public static void main(String s[]) {
generateFNos(6);
}
}
Maybe it better:
public class SmallestNoProduct {
public static int smallest(int n) {
int small = n*n;
for(int i = 1; i < Math.sqrt(n); i++) {
if(n%i == 0) {
int temp = Integer.parseInt(""+i+""+n/i);
int temp2 = Integer.parseInt(""+n/i+""+i);
temp = temp2 < temp? temp2: temp;
if(temp < small) {
small = temp;
}
}
}
return small;
}
public static void main(String[] args) {
System.out.println(smallest(6)); //6
System.out.println(smallest(10)); //25
System.out.println(smallest(100)); //205
}
}
Problem lies in this line
String t=x[d++]+""+x[p--];
x[p--] will try to fetch 7th position value, as p is length of array x i.e. 6 which results in ArrayIndexOutOfBound exception. Array index starts from 0, so max position is 5 and not 6.
You can refer this question regarding postfix expression.
Note: I haven't checked your logic, this answer is only to point out the cause of exception.
We are unnecessarily using array here...
below method should work....
public int getSmallerMultiplier(int n)
{
if(n >0 && n <10) // if n is 6
return (1*10+n); // it will be always (1*10+6) - we cannot find smallest number than this
else
{
int number =10;
while(true)
{
//loop throuogh the digits of n and check for their multiplication
number++;
}
}
}
int num = n;
for(i=9;i>1;i--)
{
while(n%d==0)
{
n=n/d;
arr[i++] = d;
}
}
if(num<=9)
arr[i++] = 1;
//printing array in reverse order;
for(j=i-1;j>=0;j--)
system.out.println(arr[j]);

Paul Erdos Conjecture [Java]

I've been trying to solve this rather easy problem on SPOJ: http://www.spoj.com/problems/HS08PAUL/.
It requires the number of prime numbers (less than n) which can be expressed in the form x^2+y^4 (where x and y are integers) to be found out.
I've whipped up a brute force solution which takes up quite a while for (n ~= 1000000), resulting in a TLE (time limit exceeded) error being thrown by the engine. Here's the source code:
import java.io.*;
import java.util.*;
class HS08PAUL {
public static int[] sieve(int n){
boolean[] prime = new boolean[n+1];
int[] primeNumbers = new int[n];
int index = 0;
Arrays.fill(primeNumbers, 0);
Arrays.fill(prime,true);
prime[0] = false;
prime[1] = false;
int m = (int)Math.sqrt(n);
for(int i = 2; i <= m; i++){
if(prime[i])
for(int k = i*i; k<=n; k+=i)
prime[k] = false;
}
for(int j = 2; j <= n; j++) {
if(prime[j]) {
primeNumbers[index] = j;
index++;
}
}
return primeNumbers;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try{
double numberOfTestCases = in.nextDouble();
while(numberOfTestCases -- > 0) {
int index = 0, y = 0, count = 0;
int num = in.nextInt();
int[] primes = sieve(num);
while(index < num/3 ) {
for(y = 1; y < 57 ; y ++) {
if(Math.ceil(Math.sqrt(primes[index] - Math.pow(y,4))) == Math.floor(Math.sqrt(primes[index] - Math.pow(y,4)))) {
count++;
break;
}
}
index++;
}
System.out.println(count);
}
}
catch(Exception e) {
}
}
}
Is there a way in which I can make this approach work?
P.S.:Please ignore the unruly exception handling.
How many numbers of the form x^2+y^4 are there below 1000000? How many prime numbers are there below 1000000? What do these two numbers tell you about how you should approach the solution?
#isnot2bad's comment is also relevant.

How to find nearest value in java from POJO properties?

class CalorieExpenditures {
String activity
int lbs90
int lbs100
int lbs110
int lbs120
int lbs130
int lbs140
int lbs150
int lbs160
int lbs170
int lbs180
int lbs190
int lbs200
int lbs220
int lbs240
int lbs260
int lbs280
int lbs300
}
From the above POGO (b'se i am using grails).
How to find the nearest lbs property from POGO
e.g
if i pass 282 it will return lbs280 and if i pass 295 it will return lbs300.
logic is the difference between two values if the difference is same will return the grater value.
You can suggest java method or grails method to work with.
I need a simple program that finds nearest value.
Thanks in advance.
Below is example to find given number from int array, with nearest lower & upper
public class FindNearestInt
{
public static void main(String[] args)
{
Random random = new Random();
int array[] = new int[30];
//Initialise array with rendom values
for (int i = 0; i < array.length; i++)
{
array[i] = random.nextInt(200);
}
System.out.println(Arrays.toString(array));
Arrays.sort(array);
System.out.println(Arrays.toString(array));
// Number you want to find in array
int searchFor = 57;
//Nearest lower you searching for
int nearestLower = 0;
//Nearest upper you searching for
int nearestUpper = Integer.MAX_VALUE;
int searchForExist = -1;
for (int i = 0; i < array.length; i++)
{
int j = array[i];
if (j < searchFor)
{
if(j > nearestLower){
nearestLower = j;
}
} else if (j > searchFor){
if(j < nearestUpper){
nearestUpper = j;
}
} else {
nearestLower = -1;
nearestUpper = -1;
searchForExist = j;
break;
}
}
System.out.println("Nearest Lower : " + nearestLower);
// This will print -1 if number exist in array
System.out.println("Provided Number Already Exist : " + searchForExist);
System.out.println("Nearest Upper : " + nearestUpper);
}
}
A simpler and faster solution is to use a formula
public static int nearest(int num) {
return num < 90 ? 90 :
num < 200 ? Math.round(num/10.0) * 10 :
num < 300 ? Math.round(num/20.0) * 20 : 300;
def calorieExpendituresWeightCategory(float weight){
int nearest = 0;
int min = Integer.MAX_VALUE
CalorieExpenditures.properties.each {
if(it.toString().startsWith("lbs")){
int j = it.toString().substring(it.toString().indexOf("lbs"))
int k = (weight - j) * (weight - j)
if(k < min){
min = k
nearest = j
}
}
}
return nearest
}
This works for me i think simple and works for me.
Thanks for the answers.

Categories

Resources