import java.util.Scanner;
public class ld11 {
public static void firstMethod(int[] A) {
int size = A.length;
int equal[] = new int[size];
int less[] = new int[size];
int B[] = new int[size];
int i,j,k;
for(i=0; i<size; i++){
for(j=0;j<size;j++){
if(A[i]==A[j]){equal[i]++;}
else if(A[i]>A[j]){less[i]++;}
}}
for(i=0;i<size;i++){k=less[i];for(j=0;j<equal[i];j++){B[k+j]=A[i];}}
System.arraycopy(B, 0, A,0, A.length);
}
private static void sellaMethod(int[] A){
int t;
t=(int) (Math.log(A.length)/Math.log(2)-1);
int[] h = new int[t];
h[0]=1;
for(int i=1;i<h.length;i++)
h[i]=2*h[i-1]+1;
t--;
while(t>=0){
int inc=h[t];
t--;
for(int i=inc;i<A.length;i++){
int temp=A[i];
int j=i-inc;
while (j>=0 && A[j]>temp) {
A[j+inc]=A[j];
j=j-inc;
}
A[j+inc]=temp;
}
}
}
public static void main(String[] args) {
System.out.println("1st task");
System.out.print("Method(1/2): ");
Scanner sc = new Scanner(System.in);
int x;
if (sc.hasNextInt())
x = sc.nextInt();
else {System.out.println("input-output-error");
sc.close();
return;}
if(x!=1 && x!=2){
System.out.println("input-output-error");
return;}
System.out.print("Count: ");
int y;
if (sc.hasNextInt())
y = sc.nextInt();
else {
System.out.println("input-output-error");
sc.close();
return;}
int []A = new int[y];
System.out.println("Items:");
int i = 0;
do {if(sc.hasNextInt()){
int z = sc.nextInt();
A[i]=z;
i++;}
else{System.out.println("input-output-error");sc.close();return;}} while(i<y);
sc.close();
System.out.println("Sorted:");
if(x==1){firstMethod(A);}
else if(x==2){sellaMethod(A);}
for(i=0;i<y;i++){System.out.print(A[i]+" ");}
}
The user needs to choose which method it wants to use then write how many numbers and then write them, and programme sorts numbers in a way which is described in the method. With first method everything is okay, but with second shows errors :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ld11.sellaMethod(ld11.java:26) (h[0]=1; in this row))
at ld11.main(ld11.java:79) (else if(x==2){sellaMethod(A);} in this row
As you can see it is Shell sort method.
Could you please help?
The problem in line t=(int) (Math.log(A.length)/Math.log(2)-1);
If array has length less than 6 then t will be zero. So you'll create array with zero lenght. It's a bug. Probably you need some checks, probably another formula. Anyway, you have to review code.
As mentioned, your problem is your formula for getting the length of your h array.
A simple fix is just change this line:
t = (int) (Math.log(A.length) / Math.log(2) - 1);
to:
t = A.length;
as all you want is the new array to be same length as the initial array.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I tried by creating two functions for greatest and smallest values and then subtracting them .but the code doesn't seem to work
here's the code.See if u could help me out .im new to java and still learning.
import java.io.*;
import java.util.*;
public class Main{
public static void smler(int arr[],int j){
for (int i=0;i<=j;j++){
if(arr[i]<arr[i+1]){
int temp =arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
public static void grter(int arr[],int j){
for (int i=0;i<=j;j++){
if(arr[i]>arr[i+1]){
int temp =arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
public static void main(String[] args) throws Exception {
Scanner sc= new Scanner (System.in);
int n=sc.nextInt();
int[] arr= new int[n];
for(int i=0;i<=n;i++){
arr[i]=sc.nextInt();
}
grter(arr,n);
int y= arr[n];
smler(arr,n);
int z = arr[n];
System.out.println(y-z);
}
}
There are a lot of errors in your logic.
The for loop does not need to be <= it needs to be < otherwise you will get out of bounds exception.
The way you are calculating the min and max are wrong.
Here is an example for you to study that does what you are trying to accomplish:
import java.util.Scanner;
public class ArraySpan {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter array size:");
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter value:");
arr[i] = sc.nextInt();
}
int min = findMin(arr);
int max = findMax(arr);
System.out.println("The span of the array = " + (max - min));
sc.close();
}
static int findMax(int[] a) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
if (a[i] > max)
max = a[i];
}
return max;
}
static int findMin(int[] a) {
int min = Integer.MAX_VALUE;
for (int i = 0; i < a.length; i++) {
if (a[i] < min)
min = a[i];
}
return min;
}
}
and output:
Enter array size:
3
Enter value:
1
Enter value:
2
Enter value:
3
The span of the array = 2
It would better if you could look for complexity improvement.
Idea is to get the max and the min in best possible way and this can be achieved using any sorting techniques, let us assume your sort method runs in O(n log n) time, and then you just need to get the difference of 1st element(0 th index) and last element(n-1 th index).
public static void main(String[] args) throws Exception {
Scanner sc= new Scanner (System.in);
int n=sc.nextInt();
int[] arr= new int[n];
// insert values into your array
if(arr.length >= 2){
sort(arr); // Implement your any sorting method
// Make sure that your arr has exactly n elements, ,
// Otherwise rest of the indices will all be zero(0)
System.out.println(arr[0]-arr[arr.length-1]); // last index is 'arr.length-1'
return; // Return from here
}
// arr has not sufficient elements to determine span
throw new UnsupportedOperationException("Invalid entry");
}
}
Index starts from 0 and it goes till n-1.
So, the condition in for-loop should be i<n instead of i<=n,for(int i=0;i<n;i++).
You have created 2 functions but it doesn't return any value nor changes anything. As you are passing the array by value, not by references.
You don't need the 2 functions, just one for finding max and min in linear, or sort the array in ascending order and array[0] will be the min and array[n-1] will be max.
There is an approach very similar to what you want to do.
import java.io.*;
import java.util.*;
public class Main{
public static int smler(int arr[],int N){
int smaller = arr[0];
for (int i=1;i<N;i++){
if(arr[i] < smaller){
smaller = arr[i];
}
}
return smaller;
}
public static int grter(int arr[],int N){
int greater = arr[0];
for (int i=0;i<N;i++){
if(arr[i] > greater){
greater = arr[i];
}
}
return greater;
}
public static void main(String[] args) throws Exception {
Scanner sc= new Scanner (System.in);
int n=sc.nextInt();
int[] arr= new int[n];
for(int i=0;i<=n;i++){
arr[i]=sc.nextInt();
}
System.out.println(grter(arr, n) - smler(arr, n));
}
}
Question :
Write a program that allows the entry of an integer value n, followed by two sets of n integer values into arrays A and B. The program should use a function to calculate the sum of the square of corresponding values of A and B. These values should then be displayed.
My piece of code :
import java.util.Scanner;
public class Question9_SumOfSquareInArrays {
public static void main(String[] args) {
int sumA = 0;
int sumB = 0;
int n;
int i=0;
Scanner src=new Scanner(System.in);
System.out.print("Please enter value :");
n=src.nextInt();
int [] A=new int[n];
int [] B=new int[n];
System.out.println("Enter value for array A :");
for(i=0;i<n;i++)
{
A[i]=src.nextInt();
}
System.out.println("Enter value for array B :");
for(i=0;i<n;i++)
{
B[i]=src.nextInt();
}
src.close();
System.out.println("Total sum for array A is " + SumOfA(sumA));
System.out.println("Total sum for array B is " + sumOfB(sumB));
}
public static int SumOfA(int sumA)
{
int square=1;
int sum=0;
int n=6;
int [] A= new int[n];
for(int i=0;i<n;i++)
{
square=A[i]*A[i];
sum+=square;
}
return sum;
}
public static int sumOfB(int sumB)
{
int square=1;
int n=6;
int sum=0;
int [] B=new int [n];
for(int i=0;i<n;i++)
{
square=B[i]*B[i];
sum+=square;
}
return sum;
}
}
I am not able to find out my mistakes. Can someone please help me?
public static int SumOfA(int sumA)
{
int square=1;
int sum=0;
int n=6;
int [] A= new int[n]; // you are calculating the sum of this array
for(int i=0;i<n;i++)
{
square=A[i]*A[i];
sum+=square;
}
return sum;
}
is problematic because it calculates the sum of an array of 0s.
Instead, you need to pass your array to the method, i.e.
in main you need
System.out.println("Total sum for array A is " + SumOfA(A));
and modify your SumOfA as follows. Notice it's better to use n = A.length since the length of A is not necessarily always 6.
public static int SumOfA(int[] A)
{
int square=1;
int sum=0;
int n=A.length; // use length to handle array A of any length
for(int i=0;i<n;i++)
{
square=A[i]*A[i];
sum+=square;
}
return sum;
}
The other method has the same problem
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Queuessorting {
public static int randInt(int min, int max) {
// Usually this should be a field rather than a method variable so
// that it is not re-seeded every call.
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args){
Scanner myScanner = new Scanner(System.in);
ArrayList<Integer> ar = new ArrayList<Integer>();
ArrayList<Integer> temp = new ArrayList<Integer>();
ArrayList<Integer> arf = new ArrayList<Integer>();
System.out.println("Enter n: ");
int n = myScanner.nextInt();
int count = 0;
int r=0;
for(int i = 0;i < n;i++){
ar.add(randInt(1,99));
}
System.out.println(ar.size());
for(int i=0;i<ar.size();i++)
System.out.println(ar.get(i));
int j=0;
int nctr=0;
while(ar.size() > 0){
int a = 0;
int nct = 0;
a = ar.remove(0);
if(nctr == 0){
temp.add(a);
}
else{
if(arf.size() != 0){
for(int k = 0;k<arf.size();k++){
temp.add(arf.remove(0));
}
}
while(r<temp.size() && count == 0) {
if(a > temp.get(r)){
arf.add(a);
count++;
nct++;
}
else
arf.add(temp.remove(0));
r++;
}
if(nct == 0)
arf.add(a);
}
if(temp.size()!=0){
for(int l = 0;l<temp.size();l++){
arf.add(temp.remove(0));
}
}
nctr++;
}
System.out.println("***************************");
for(int u=0;u<arf.size();u++)
System.out.println(arf.get(u));
}
}
My code works perfectly fine when having an input of 2 but if I enter any number greater than 2 the sorting is completely messed up. I'am sorting descending order being the top the number the first index of the arraylist
pseudocode: example : 72,97,2 a will get 72 from ar then store it to temp because it is the first one, next a will get 97 and compare it to 72 if a > 72, a will go to arf then the remaining values in temp will go to arf too : 92,72 <- contents of arf now. After that procedure everything in arf will go to temp and the loop goes on and on I hope you understand my explanation :(
the final output or the final arf contents will be 97,72,2
I must make a int array filled with 5000 numbers, and then take the value of each cell, which is a random number up to 1000, and multiply it by the square root of the cell index.
So far, my code is:
import java.util.*;
public class thousandArray{
public static void main (String args[]){
int numbers[] = new int[5000];
int r = 0 + (int)(Math.random()*1000);
double rt = numbers[r];
while(rt==numbers[r]){
r=0+(int)(Math.random()*1000);
double square = rt*Math.sqrt(numbers[r]);
System.out.println(square);
System.exit(0);
}
}
}
im pretty sure I did the code right, I cant figure out how to fill my array.
import java.util.*;
public class thousandArray{
public static void main (String args[]){
int numbers[] = new int[5000];
int r = 0 + (int)(Math.random()*1000);
double rt = numbers[r]; //you never assigned anything to numbers[r]
while(rt==numbers[r]){
r=0+(int)(Math.random()*1000);
double square = rt*Math.sqrt(numbers[r]);
System.out.println(square);
System.exit(0); //you exit the first time it loops
}
}
}
To fill an int array:
int[] numbers = new int[5000];
for (int i = 0; i < 5000; i++) {
numbers[i] = some_value;
}
To make the values be random, more or less as the problem states, you'd use:
numbers[i] = (int)(Math.random()*1000);
To multiply by the square root of the cell index:
numbers[i] = numbers[i] * (int)Math.sqrt(i);
Of course, that assumes that numbers should be an int array. It would make more sense for it to be a double array, in which case you'd remove the (int) casts.
public class ThousandArray {
public static void main (String args[]){
int MAX = 5000;
int numbers[] = new int[MAX];
for (int i = 0; i < MAX; i++) {
numbers[i] = (int)(Math.sqrt(i) * (Math.random()*1000));
}
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Q:
Obtain start and end integers in main method. Pass those two values into a separate function.Return all the numbers between those values (inclusive), which is divisible by 3 back to the main from the function.
I have done upto:
import java.util.*;
public class inbetween {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter range of values");
int x =in.nextInt();
int y =in.nextInt();
search(x,y);
}
public static void search(int a, int b) {
int length = (b-a)+1;
int [] arr = new int [length];
for(int i=0; i<length; i++)
{
a = a+1;
int c;
// int count=0;
c = a%3;
if (c==0) {
arr[i] = a;
System.out.println(arr[i]);
// count = count+1;
// return count;
}
}
}
}
Now my question is ..How can I return the array and print it in function and print it there??? this code works but in this, the values are getting printed in the function itself (but it should be printed in the main)...
Change it to
import java.util.*;
public class inbetween {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter range of values");
int x =in.nextInt();
int y =in.nextInt();
int[] result = search(x,y);
for (int i=0;i < result.length; i++)
System.out.println(result[i]);
}
public static int[] search(int a, int b) {
int length = (b-a)+1;
int [] arr = new int [length];
for(int i=0; i<length; i++)
{
a = a+1;
int c;
// int count=0;
c = a%3;
if (c==0) {
arr[i] = a;
}
}
return arr;
}
}
Create array in main
Pass reference to array to function to do work
Print array out in main
You need to return an array to main:
package com.stackoverflow.homework;
import java.util.Arrays;
import java.util.Scanner;
public class Homework {
public static void main(String[] args) {
int[] result;
Scanner in = new Scanner(System.in);
System.out.println("Enter range of values: ");
int x = in.nextInt();
int y = in.nextInt();
result = findNumbersBetween(x,y);
for(int i=0; i<result.length; i++) {
System.out.println(result[i]);
}
}
private static int[] findNumbersBetween(int a, int b) {
int[] temp = new int[(b-a)+1];
int x = a;
int i = 0;
while(x <= b) {
if(x % 3 == 0) {
temp[i] = x;
i++;
}
x++;
}
return Arrays.copyOfRange(temp, 0, i);
}
}
Also remember that first letter of class name should always be capitalized!