I have this professor that wants us to make a using the method header
Public static int[] eliminateDuplicates(int[] arr)
The program uses a randomly generated array to see if there are duplications but the user gives a limit on how many indexes's the random array has. Here is what I have but it's not working.
import java.util.Random;
import java.util.Scanner;
public class Dublicates
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random generator = new Random();
System.out.println("Enter array length: ");
int[] a = new int[input.nextInt()];
for (int i = 0; i<a.length; i++)
{
a[i] = generator.nextInt(a.length*2);
}
int[] result = eliminateDuplicates(a);
System.out.println("The new numbers are: " + result.length);
System.out.println("The double numbers were:");
for (int b : result)
{
System.out.println(b + " ");
}
}
public static int[] eliminateDuplicates(int[] arr)
{
int[] temp = new int[arr.length];
int size = 0;
for (int i = 0; i < arr.length; i++) {
if (linearSearch(temp, arr[i]) == -1) {
temp[size] = arr[i];
size++;
}
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = temp[i];
}
{
return result;
}
}
}
public static int linearSearch(int[] arr, int key)
{
for(int i = 0; i<arr.length; i++)
{
if (key == arr[i])
return i;
}
return -1;
}
}
As your statements making the final result is inside the for loop, the statements inside for will only run once and will not give the right answer.
So you have to change your code as follows.
public static int[] eliminateDuplicates(int[] arr)
{
int[] temp = new int[arr.length];
int size = 0;
for (int i = 0; i < arr.length; i++) {
if (linearSearch(temp, arr[i]) == -1) {
temp[size] = arr[i];
size++;
}
}
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = temp[i];
}
return result;
}
The default values in the integer array is 0, The Random.nextInt() can generate 0 random value, When you run linear search then 0 will not be included in the final resultant array.
I have modify Random.nextInt() so that it will not generate 0 random number:
import java.util.Random;
import java.util.Scanner;
public class HelloCodiva
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random generator = new Random();
System.out.println("Enter array length: ");
int[] a = new int[input.nextInt()];
for (int i = 0; i<a.length; i++){
a[i] = generator.nextInt(a.length*2)+1;//So that 0 is not generated
}
int[] result = eliminateDuplicates(a);
for (int originalValue: a){
System.out.println(originalValue+ " ");
}
System.out.println("The new numbers are: " + result.length);
System.out.println("The double numbers were:");
for (int b : result){
System.out.println(b + " ");
}
}
public static int[] eliminateDuplicates(int[] arr)
{
int[] temp = new int[arr.length];
int size = 0;
for (int i = 0; i < arr.length; i++) {
if (linearSearch(temp, arr[i]) == -1) {
temp[size] = arr[i];
size++;
}
}
int[] result = new int[size];
System.arraycopy(temp, 0, result, 0, size);
return result;
}
public static int linearSearch(int[] arr, int key)
{
for(int i = 0; i<arr.length; i++)
{
if (key == arr[i])
return i;
}
return -1;
}
}
Related
I am working with the following code that allows the user to enter 9 numbers and it displays the mean and median of the numbers back to the user. I am trying to figure out the best way to revise my code so that before displaying the mean and median it will also show the 9 numbers the user entered. Thanks so much for any help in this matter!
import java.util.*;
class MeanMedian
{
private static float mean(int arr[]){
int n = arr.length;
float sum = 0;
for(int i = 0;i<n;i++){
sum += arr[i];
}
return sum / n;
}
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int lowindex = i;
for (int j = array.length - 1; j > i; j--)
if (array[j] < (array[lowindex]))
lowindex = j;
int temp = array[i];
array[i] = array[lowindex];
array[lowindex] = temp;
}
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static float median(int arr[]){
selectionSort(arr);
if(arr.length%2 == 0){
return arr[(arr.length/2)-1];
}
else{
return arr[arr.length/2];
}
}
public static void main(String args[]){
int n = 9;
Scanner scanner = new Scanner(System.in);
int arr[] = new int[n];
System.out.print("Enter "+ n +" integers: ");
for(int i = 0;i<n;i++){
arr[i] = scanner.nextInt();
}
System.out.println("mean: "+ mean(arr));
System.out.println("median: "+ median(arr));
}
}
I am trying to figure out the best way to revise my code so that
before displaying the mean and median it will also show the 9 numbers
the user entered.
Something like:
// ... previous code ...
System.out.println("You entered: ");
for(int i : arr) {
System.out.println(i);
}
System.out.println("mean: "+ mean(arr));
System.out.println("median: "+ median(arr));
The following code worked perfectly and passed all checks I ran on it :)
import java.util.*;
class MeanMedian
{
private static float mean(int arr[]){
int n = arr.length;
float sum = 0;
for(int i = 0;i<n;i++){
sum += arr[i];
}
return sum / n;
}
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int lowindex = i;
for (int j = array.length - 1; j > i; j--)
if (array[j] < (array[lowindex]))
lowindex = j;
int temp = array[i];
array[i] = array[lowindex];
array[lowindex] = temp;
}
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static float median(int arr[]){
selectionSort(arr);
if(arr.length%2 == 0){
return arr[(arr.length/2)-1];
}
else{
return arr[arr.length/2];
}
}
public static void main(String args[]){
int n = 9;
Scanner scanner = new Scanner(System.in);
int arr[] = new int[n];
System.out.print("Enter "+ n +" integers: ");
for(int i = 0;i<n;i++){
arr[i] = scanner.nextInt();
}
System.out.println("You entered: ");
for(int i : arr) {
System.out.println(i);
}
System.out.println("mean: "+ mean(arr));
System.out.println("median: "+ median(arr));
}
}
how I can sort and find the duplication in the array and return if there is a duplication?
I have an array with this code
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int r = input.nextInt();
int[] list = new int[r];
init(list);
static void init(int list[]) {
Random random = new Random();
for (int i = 0; i < list.length; i++) {
int n = (int) (Math.random() * 50 + 1);
list[i] = random.nextInt(50) + 1;
}
}
static void print(int list[]) {
for (int i : list) {
System.out.print(i + " ");
}
}
}
how can I sort it in another method and find the duplication
From you question I understand You want the duplicate items in an array.
Here is an example using naive approach. Please don't use it if you have very large array!!!
public static void main (String [] args) {
System.out.println("Hello world");
int [] myarray = {1,3,4,2,2,2,3};
int [] duplicates = findDuplicates(myarray);
System.out.println(Arrays.toString(duplicates));
}
private static int [] findDuplicates( int [] list) {
int [] countingArray = new int[1];
int n = 0;
for (int i = 0; i < list.length; i++) {
for (int j = i + 1 ; j < list.length; j++) {
if (list[i] == list[j]) {
boolean flag = true;
for (int k = 0; k < countingArray.length; k++) {
if ((countingArray[k] == list[i])) {
flag = false;
}
}
if (flag) {
if (n == countingArray.length) countingArray = resizeBy1(countingArray);
countingArray[n++] = list[i];
}
}
}
}
return countingArray;
}
private static int [] resizeBy1(int [] s) {
int [] newArray = new int[s.length +1];
for (int i = 0; i< s.length; i++) {
newArray[i] = s[i];
}
s = newArray;
return s;
}
If you want to know an advance approach please look at Finding repetition in array
Right now, I'm trying to find the odd and even numbers of an array. Here's the code of what I have so far. I know my findEvens() and findOdds() methods are messed up because they keep giving me off values whenever I try to print the final result. For example, if I try to find the odds of {1,5,8,3,10}, it gives me {5,3,0}. And if I try to find the evens of {2,5,8,7,19}, it gives me {2,8,0}. Anyone know why?
public class Scores {
private int[] numbers;
public Scores(int[] numbersIn) {
numbers = numbersIn;
}
public int[] findEvens() {
int numberEvens = 0;
for (int i = 0; i < numbers.length; i++) {
if (i % 2 == 0) {
numberEvens++;
}
}
int[] evens = new int[numberEvens];
int count = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
evens[count] = numbers[i];
count++;
}
}
return evens;
}
public int[] findOdds() {
int numberOdds = 0;
for (int i = 0; i < numbers.length; i++) {
if (i % 2 == 0) {
numberOdds++;
}
}
int[] odds = new int[numberOdds];
int count = 0;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] % 2 == 1) {
odds[count] = numbers[i];
count++;
}
}
return odds;
}
public double calculateAverage() {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return (double) sum / numbers.length;
}
public String toString() {
String result = "";
for (int i = 0; i < numbers.length; i++) {
result += numbers[i] + "\t";
}
return result;
}
public String toStringInReverse() {
String result = "";
for (int i = numbers.length - 1; i >= 0; i--) {
result += numbers[i] + "\t";
}
return result;
}
}
You're problem is in counting how many even numbers you have
public int[] findEvens() {
int numberEvens = 0;
for (int i = 0; i < numbers.length; i++) {
if (i % 2 == 0) {
numberEvens++;
}
}
this will always return a number that is half the size of the length of numbers because you're doing mod division on the number of elements in the array, not on the elements themselves. Add numbers[i] to the if statement
public int[] findEvens() {
int numberEvens = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
numberEvens++;
}
}
looks like you've got the same problem with odd count
'i' is used as conditional variable for looping. You should not divide this by 2. You have to divide the array element. like
if (numbers[i] % 2 == 0) {
numberEvens++;
}
then it should work. Thanks
Try This Code
import java.util.Scanner;
public class OddEven {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter number Elements in Array");
int n = s.nextInt();
int arr[] = new int[n];
System.out.println("enter Elements ");
for(int i=0; i<n; i++) {
arr[i]=s.nextInt();
}
int [] odd = filterOdd(arr);
try {
for(int i=0; i<n; i++) {
System.out.println("Odd" + odd[i]);
}
} catch(ArrayIndexOutOfBoundsException e) {}
int [] even = filterEven(arr);
try {
for(int i=0; i<n; i++) {
System.out.println("Even" + even[i]);
}
} catch(ArrayIndexOutOfBoundsException e) {}
}
public static int[] filterOdd(int[] a) {
int l = 0;
int j = 0;
for(int i=0; i<a.length; i++) {
if(a[i]%2==1) {
l++;
}
}
int k[]=new int[l];
for(int i=0; i<a.length; i++) {
if(a[i]%2==1) {
k[j] = a[i];
j++;
}
}
return k;
}
public static int[] filterEven(int[] a) {
int l = 0;
int j = 0;
for(int i=0; i<a.length; i++) {
if(a[i]%2==0) {
l++;
}
}
int k[] = new int[l];
for(int i=0; i<a.length; i++) {
if(a[i]%2==0) {
k[j] = a[i];
j++;
}
}
return k;
}
}
public class Array {
public static void main(String[] args) {
// TODO code application logic here
//Array declaration and value asign
int number[]=new int[]{1,2,3,4,5,6,7,8,9};
// for loop to move number
for(int p=0;p<number.length;p++)
{
// check number is even or odd??
if(number[p]%2==0)
System.out.println(number[p]+ " is Even number");
else
System.out.println( number[p]+" is odd umber");
}
}
}
Odd array one columns and another columns even array
public class OddEven {
public static void main(String[] args) {
int arr[]={1,2,3,4,5,6,7,8};
int ss[]=new int[10];
int odd[]=new int[10];
int i;
int k;
for( i=0;i<arr.length;i++)
{
if(arr[i]%2==0)
{
ss[i]=arr[i];
System.out.print(""+ss[i]);
System.out.print(" ");
}
if((arr[i]%2)!=0)
{
odd[i]=arr[i];
System.out.print(""+odd[i]);
System.out.print(" ");
}else
{
System.out.println(" ");
}
}
}
}
========================================output==============================
1 2
3 4
5 6
7 8
Okay, I know this question doesn't show research effort, but I've been going through this code so many times and I couldn't figure out was I was doing wrong. I know there are many Mergesort implementation examples but I wanted to do it my way. Any help is appreciated, thanks.
import java.util.Scanner;
public class MergeSort
{
public static int[] mergeSort(int[] arr)
{
if (arr.length > 1)
{
int[] arr1 = splitLeft(arr);
int[] arr2 = splitRight(arr);
arr1 = mergeSort(arr1);
arr2 = mergeSort(arr2);
return merge(arr1, arr2);
}
else
return arr;
}
public static int[] splitLeft(int[] arr)
{
int middle = arr.length / 2;
int[] newarr = new int[middle];
for (int i = 0; i < middle; i++)
newarr[i] = arr[i];
return newarr;
}
public static int[] splitRight(int[] arr)
{
int middle = arr.length / 2;
int[] newarr = new int[arr.length - middle];
for (int i = 0; i + middle < arr.length; i++)
newarr[i] = arr[i + middle];
return newarr;
}
public static int[] merge(int[] arr1, int[] arr2)
{
int[] sorted = new int[arr1.length+arr2.length];
int i1 = 0;
int i2 = 0;
int i = 0;
while (i1 < arr1.length && i2 < arr2.length)
{
if (arr1[i1] < arr2[i2])
{
sorted[i] = arr1[i1];
i1++;
}
else
{
sorted[i] = arr2[i2];
i2++;
}
i++;
}
while (i1 < arr1.length)
{
sorted[i] = arr1[i1];
i1++;
i++;
}
while (i2 < arr2.length)
{
sorted[i] = arr1[i2];
i2++;
i++;
}
return sorted;
}
public static int getNum(int x)
{
int num = (int)(Math.random()*x + 1);
return num;
}
public static void printArr(int[] arr)
{
System.out.println();
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
static Scanner reader = new Scanner(System.in);
public static void main(String [ ] args)
{
int i;
System.out.println("Type the length of the array");
int n = reader.nextInt();
System.out.println("Type the range of the random numbers generator");
int range = reader.nextInt();
int[]arr = new int[n];
for (i = 0; i < n; i++)
arr[i] = getNum(range);
printArr(arr);
int[] sorted = new int[n];
sorted = mergeSort(arr);
printArr(sorted);
}
}
I think the problem is in your splitRight function. Consider this code:
for (int i = middle; i < arr.length; i++)
newarr[i] = arr[i];
This tries to copy the ith element from arr to the ith position of newarr, but this is incorrect. For example, if the array arr has ten elements, you want to copy element 5 of arr to position 0 of newArr, element 6 of arr to position 1 of newarr, etc.
To fix this, consider trying something like this:
for (int i = 0; i + middle < arr.length; i++)
newarr[i] = arr[i + middle];
Hope this helps!
When you do
for (int i = middle; i < arr.length; i++)
newarr[i] = arr[i];
You are surely asking for positions in the original array and at the same time looking for them in the new array (which happens to be shorter).
Hi all I want to find out second Largest no in Array accept negative numbers. I have used following code and this display second largest no of only positive no.So please suggest me how to do this.
class ArrayExample {
public static void main(String[] args) {
int secondlargest = 0;
int largest = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter array values: ");
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
if (largest < arr[i]) {
secondlargest = largest;
largest = arr[i];
}
if (secondlargest < arr[i] && largest != arr[i])
secondlargest = arr[i];
}
System.out.println("Second Largest number is: " + secondlargest);
}
}
The problem comes from the fact that you initialize your two variables to 0 in the lines:
int secondlargest = 0;
int largest = 0;
You should instead initialize them to Integer.MIN_VALUE and then it will also work for negative values.
Initialize the variables secondlargest and largest with the smallest negative values.
Use this code:
class ArrayExample {
public static void main(String[] args) {
int secondlargest = Integer.MIN_VALUE;
int largest = Integer.MIN_VALUE;
Scanner input = new Scanner(System.in);
System.out.println("Enter array values: ");
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
if (largest < arr[i]) {
secondlargest = largest;
largest = arr[i];
}
if (secondlargest < arr[i] && largest != arr[i])
secondlargest = arr[i];
}
System.out.println("Second Largest number is: " + secondlargest);
}
}
Initialize largest and secondLargest to Integer.MIN_VALUE instead of zero.
This works for me, for both positive and negative values. Before the loop, you need to initialize the largest and secondlargest variables with very small values, by doing this you can be (almost) sure that all the other values in the array will be greater than them:
int largest = Integer.MIN_VALUE;
int secondlargest = Integer.MIN_VALUE;
Inside the loop:
if (arr[i] > largest) {
secondlargest = largest;
largest = arr[i];
}
else if (arr[i] != largest && arr[i] > secondlargest) {
secondlargest = arr[i];
}
After the loop:
if (secondlargest != Integer.MIN_VALUE)
System.out.println("Second Largest number is: " + secondlargest);
Notice that the last check is required for the (rather unlikely) case where all the elements in the array happen to be Integer.MIN_VALUE.
package com.demo.mum;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* #author cyruses
*
*/
public class SecondLargest {
public static int largest = Integer.MIN_VALUE;
public static int secondLargest = Integer.MIN_VALUE;
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Size of Array:");
int n = Integer.parseInt(br.readLine());
int a[] = new int[n];
System.out.println("Enter the elements on array:");
for (int i = 0; i < a.length; i++) {
a[i] = Integer.parseInt(br.readLine());
}
System.out.println("Elements you entered are:");
for (int i = 0; i < a.length; i++) {
System.out.println("a[" + i + "]" + "=" + a[i]);
}
if (a.length <= 2) {
if (a[0] == a[1]) {
System.out.println("Theres no second largest number in your array");
} else {
System.out.println("SecondLargest:" + secondLargest(a));
}
} else {
System.out.println("SecondLargest:" + secondLargest(a));
}
}
private static int secondLargest(int[] a) {
for (int i = 0; i < a.length; i++) {
if (a[i] > largest) {
secondLargest = largest;
largest = a[i];
} else if (a[i] > secondLargest) {
secondLargest = a[i];
}
}
return secondLargest;
}
}
I think this method may be useful it takes around n+log(n)-2 comparisons
import java.util.ArrayList;
public class SecondLargest {
static ArrayList<ArrayList<Integer>> level = new ArrayList<ArrayList<Integer>>();
public static void main(String[] args) {
int input[]={9,8,7,4,5,6,1,2,3,1,1,21,33,32,1,2,3,12,3,2,1};
ArrayList<Integer> arr= new ArrayList<Integer>();
for(int i=0;i<input.length;i++){
arr.add(input[i]);
}
level.add(arr);
seconLarger(arr);
System.out.println(SecondLarge(level));
}
private static ArrayList<Integer> seconLarger(ArrayList<Integer> arr) {
ArrayList<Integer> tmp= new ArrayList<Integer>();
if (arr.size()==1)
{
return arr;
}
if(arr.size()%2==0)
{
for(int i=0;i<arr.size();i=i+2)
{
if(arr.get(i)>arr.get(i+1))
{
tmp.add(arr.get(i));
}
else
{
tmp.add(arr.get(i+1));
}
}
}
else
{
for(int i=0;i<arr.size()-1;i=i+2)
{
if(arr.get(i)>arr.get(i+1))
{
tmp.add(arr.get(i));
}
else
{
tmp.add(arr.get(i+1));
}
}
tmp.add(arr.get(arr.size()-1));
}
level.add(tmp);
return seconLarger(tmp);
}
private static int SecondLarge(ArrayList<ArrayList<Integer>> li)
{
int li_size=li.size();
int large=li.get(li_size-1).get(0);
int secondlarge=0;
int tmp=0;
for(int i=li_size-2;i>=0;i--)
{
ArrayList<Integer> arr = li.get(i);
if(large==arr.get(tmp))
{
if(tmp+1<arr.size())
{
if(secondlarge<arr.get(tmp+1))
{
secondlarge=arr.get(tmp+1);
}
}
}
else
{
if(secondlarge<arr.get(tmp))
{
secondlarge=arr.get(tmp);
}
tmp=tmp+1;
}
tmp=tmp*2;
}
return secondlarge;
}}
Or here is a gimmicky Java implementation which doesn't rely on Integer.MIN_VALUE
int findSecondHighest(int[] arr){
if(arr == null || arr.length < 2){
throw new IllegalArgumentException();
}
int fh,sh;
if(arr[0]>=arr[1]){
fh = arr[0];
sh = arr[1];
}else{
fh = arr[1];
sh = arr[0];
}
for (int i = 2; i < arr.length; i++) {
if(fh < arr[i]){
sh = fh;
fh = arr[i];
}else if(sh < arr[i]){
sh = arr[i];
}
}
return sh;
}
Instead of initializing the second largest number to min value or zero. You can follow below code to get second largest number.
import java.util.Scanner;
public class SecondLargestNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] a;
int n;
System.out.println("Enter number of elements");
n = scanner.nextInt();
a = new int[n];
for(int i=0; i<n; i++) {
a[i] = scanner.nextInt();
}
int secondLargestNumber = a[0];
int largestNumber = a[0];
int count = 1;
for(int i=1; i<a.length; i++) {
if(a[i] >= largestNumber) {
if(a[i] == largestNumber) {
count++;
} else {
count = 1;
}
secondLargestNumber = largestNumber;
largestNumber = a[i];
} else {
if(secondLargestNumber == largestNumber && count == 1) {
secondLargestNumber = a[i];
} else if(a[i] > secondLargestNumber) {
secondLargestNumber = a[i];
}
}
}
System.out.println("Second Largest Number: " + secondLargestNumber);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter array size = ");
int size=in.nextInt();
int[] n = new int[size];
System.out.println("Enter "+ size +" values ");
for(int i=0;i<n.length;i++)
n[i] = in.nextInt();
int big=n[0],sbig=n[0];
// finding big, second big
for(int i=0;i<n.length;i++){
if(big<n[i]){
sbig=big;
big=n[i];
}else if(sbig<n[i])
sbig=n[i];
}
// finding second big if first element itself big
if(big==n[0]){
sbig=n[1];
for(int i=1;i<n.length;i++){
if(sbig<n[i]){
sbig=n[i];
}
}
}
System.out.println("Big "+ big+" sBig "+ sbig);
in.close();
}