I am trying to create a random array without duplicates.
The assignment is to take an integer array and maximum value from user, fills the array with random numbers between 0 and maximum value, and display random array without duplicates, WITHOUT using any other classes except random and scanner.
This is a sample output:
Please enter the size of the array: 10
Please enter the maximum value: 50
[39,2,17,49,12,19,40,31,42,15]
I need help in removing the duplicates. I am not sure if what I am doing is correct, I am a bit of a beginner but here is what I have so far. Help would be greatly appreciated. Thanks.
public class Fill {
private static int size;
private static int maxVal;
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
// Ask user to enter the size of the array
System.out.print("Please enter the size of the array: ");
size = kb.nextInt();
// Ask user to enter the maximum value allowed
System.out.print("Please enter the maximum value: ");
maxVal = kb.nextInt();
// Call fill() method
int arr[] = fill(size, maxVal);
// Print filled array
System.out.print("[");
for (int i = 0; i < arr.length - 1; i++)
System.out.print(arr[i] + ",");
System.out.print(arr[arr.length - 1] + "]");
}
public static int[] fill(int size, int maxVal) {
int arr[] = new int[size];
Random random = new Random();
// Fills the array with random numbers between 0 and maximum value
if (size <= 0 || maxVal < size - 1) {
System.out.print("Incorrect Parameters. Please Retry");
main(null);
} else {
for (int j = 0; j < size; j++) {
arr[j] = random.nextInt(maxVal);
// Check array for duplicates
for (int k = j + 1; k < size; k++) {
if(arr[j] == arr[k]) {
//create new random array
fill(size, maxVal);
}
}
}
}
return arr;
}
}
I have edited and fixed some issues in your code as below:
public class Fill {
private static int size;
private static int maxVal;
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
// Ask user to enter the size of the array
System.out.print("Please enter the size of the array: ");
size = kb.nextInt();
// Ask user to enter the maximum value allowed
System.out.print("Please enter the maximum value: ");
maxVal = kb.nextInt();
// Call fill() method
int arr[] = fill(size, maxVal);
// Print filled array
System.out.print("[");
for (int i = 0; i < arr.length - 1; i++)
System.out.print(arr[i] + ",");
System.out.print(arr[arr.length - 1] + "]");
}
public static int[] fill(int size, int maxVal) {
int arr[] = new int[size];
Random random = new Random();
// Fills the array with random numbers between 0 and maximum value
if (size <= 0 || maxVal < size ) {
System.out.print("Incorrect Parameters. Please Retry");
main(null);
} else {
for (int j = 0; j < size; j++) {
int newNumber = random.nextInt(maxVal + 1);
// Check array for duplicates
while(alreadyExist(newNumber, arr)){
newNumber = random.nextInt(maxVal + 1);
}
arr[j] = newNumber;
}
}
return arr;
}
static boolean alreadyExist(int a, int[] arr){
for(int i = 0 ; i < arr.length ; i++){
if(arr[i] == a) return true;
}
return false;
}
}
Now it does not return any repetitive value.
Related
I am trying to develop a program to delete all the median values from an array (the middle value if it has an odd number of elements, the two middle values if it has an even number of elements) until there are only two elements left, elements [0] and [1]. For example, if the user inputs 1, 2, 3, 4, 5, the program will return [1, 5]. I put down what I thought logically might help, but my array x isn't copying myArray in the for loops. I am not looking for someone to completely do the code for me, just to point out where I am wrong. Here is my code:
import java.util.*;
public class Deletion
{
public static void main(String[]args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the array length:");
int [] myArray = new int[kb.nextInt()];
int [] x = new int[myArray.length - 1];
int index1 = 0;
int index2 = 0;
int index3 = 0;
if(myArray.length < 3)
{
System.out.println("Please make sure array length is greater than two. Run again.");
System.exit(0);
}
else
{
for(int i = 0; i < myArray.length; i++)
{
System.out.println("Please enter a number for position " + i + ":");
myArray[i] = kb.nextInt();
}
for(int i = 0; i < myArray.length; i++)
{
while(myArray.length > 2)
{
if(myArray.length%2 != 0)
{
index1 = (myArray.length/2);
for(int j = 0, r = 0; j < myArray.length; j++)
{
if(j != index1)
{
x[r++] = myArray[j];
myArray = x;
}
}
x = new int[myArray.length - 1];
}
else
{
index2 = (myArray.length/2);
index3 = (myArray.length/2 - 1);
for(int j = 0, r = 0; j < myArray.length; j++)
{
if(j != index2 && j != index3)
{
x[r++] = myArray[j];
myArray = x;
}
}
x = new int[myArray.length - 1];
}
}
}
}
System.out.println(Arrays.toString(myArray));
}
}
You must create the array and populate it, else it's using the same memory address, hence won't work. Use the following:
myArray = ArrayUtils.clone(x);
When you are doing do “myArray = x”, your are actually merely assigning a reference to the array. Hence, if you make any change to one array, it would be reflected in other arrays as well because both myArray and x are referring to the same location in memory.
Thus, what you need is
myArray = x.clone();
I cleaned up your code a bit. According to what you described, what really matters is pulling in the minimum and maximum values in the array - everything else will be deleted, so you simply need a single traversal through the array to find those two values.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean isValid = false;
int validLength = 0;
System.out.println("Please enter the array length:");
while (!isValid) {
int length = scanner.nextInt();
if (length < 3) {
System.out.println("Please make sure array length is greater than two. Try again.");
}
else {
isValid = true;
validLength = length;
}
}
int minimumValue = Integer.MAX_VALUE, maximumValue = Integer.MIN_VALUE;
for (int i = 0; i < validLength; i++) {
System.out.println("Please enter a number for position " + i + ":");
int nextInt = scanner.nextInt();
if (nextInt < minimumValue) minimumValue = nextInt;
else if (nextInt > maximumValue) maximumValue = nextInt;
}
System.out.println(Arrays.toString(new int[] {minimumValue, maximumValue}));
}
Edit: made another revision as using an array is unnecessary. Just keep track of the minimum and maximum values as they are being entered.
I need help with this program, I need to
Ask the user to input rows and column sizes using scanner
if the column size is greater than 4+5, they need to re-enter it
I need to fill all the array elements with doubles in range of 4.0, 11.0 by using random object
Find the above array and call two methods,
Method one, I need to find and print the largest sum of columns in the 2D array
Method two, I need to find the average of all elements in the array and return the average value.
Here's my code, it sort of accomplishes it, but it's also sort of messed up and I'm confused.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Please enter row size");
int rows = input.nextInt();
System.out.println("Please enter column size");
int columns = input.nextInt();
double n = 4.0;
if (columns < n+5.0){
} else{
System.out.println("The column size is too large, please enter a smaller integer");
}
Random rand = new Random();
int[][] array = new int[rows][columns];
for(int a = 0; a<rows; a++)
for(int b = 0; b<columns; b++)
array[a][b] = rand.nextInt(11-4) + 4;
for(int i = 0; i<rows; i++){
double sum = 0;
int sum2 = 0;
for(int j = 0; j<columns; j++){
sum += array[j][i];
sum2 = sum2 + array[i][j];
System.out.println(Arrays.deepToString(array));
}
double average = sum/array.length;
System.out.println("largest sum of the columns is " + sum);
System.out.println("The average of all elements in the array is " + average);
}
}
}
You can use while loops to check if the input is even a valid integer and then if the columns count is larger than 4 + 5 ( i just assumed 9 ). I made the program flow a bit more structured and made a neat output. Basically you just would have to move the System.out.println out of the Loop like #Codebender pointed out.
package array;
import java.util.Random;
import java.util.Scanner;
public class ArrayUtil {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int columns;
int rows;
Scanner input = new Scanner(System.in);
System.out.println("Please enter row size :");
while (!input.hasNextInt()) {
System.out.println("That is not a valid Number! Try again.");
input.next();
}
rows = input.nextInt();
System.out.println("Please enter column size :");
while (!input.hasNextInt()) {
System.out.println("That is not a valid Number! Try again.");
input.next();
}
columns = input.nextInt();
while (columns > 9) {
System.out.println("The column size is too large, please enter a smaller integer!");
columns = input.nextInt();
}
Random rand = new Random();
int[][] array = new int[rows][columns];
for (int a = 0; a < rows; a++) {
for (int b = 0; b < columns; b++) {
array[a][b] = rand.nextInt(11 - 4) + 4;
}
}
for (int[] arr : array) {
StringBuilder sb = new StringBuilder();
for (int i : arr) {
sb.append("[");
sb.append(i);
sb.append("]");
}
System.out.println("Array :" + sb.toString());
System.out.println("Average : " + average(arr));
System.out.println("Max : " + max(arr));
}
}
public static double average(int[] values) {
double d = 0;
for (double value : values) {
d = value + d;
}
return (d / values.length);
}
public static double max(int[] values) {
double d = 0;
for (double value : values) {
if (value > d) {
d = value;
}
}
return d;
}
}
I'm trying to write a program where on the first line, you enter the number of times you want a for loop to iterate, on the second line, you enter the value of the array, and on the third line, you enter the numbers that you want in the array. My program either does not do what I want it to do, or it crashes on me. This is the code that I have for the program so far:
import java.util.*;
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int n = input.nextInt();
for (int i=0; i<n; i++)
{
int value = input.nextInt();
int[] arr = new int[value];
arr[i] = input.nextInt();
}
}
What can I do? Please help. I've tried everything! Also, it would help if someone could help me with sorting the numbers in ascending order, followed by displaying the middle number in each line, but first thing's first. Thank you.
I believe this is more of what you are after. I output the entries individually but you could combine that easily enough.
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
try
{
System.out.println("Number of times to loop:");
int numEntries = input.nextInt();
int[][] valueArrays = new int[numEntries][];
for (int i=0; i<numEntries; i++)
{
System.out.println("Size of array #"+i+": ");
int arrayLen = input.nextInt();
int[] inputArray = new int[arrayLen];
for (int j = 0; j < arrayLen; j++)
{
System.out.println("Enter value at index "+j+": ");
inputArray[j] = input.nextInt();
}
Arrays.sort(inputArray);
valueArrays[i] = inputArray;
}
for (int l=0; l < valueArrays.length; l++)
{
int[] values = valueArrays[l];
for (int m=0; m < values.length; m++)
{
System.out.println("Value of array #"+l+" saved at index "+m +": " + values[m]);
}
if ((values.length % 2) == 0)
{
int start = values.length/2;
int end = start + 1;
System.out.println("Middle values in array #"+l+" saved at indices " + start + " and " + end);
}
else
{
int start = values.length/2;
System.out.println("Middle value in array #"+l+" saved at index " + start);
}
}
}
finally
{
input.close();
}
}
You're creating a new array on each iteration inside the loop.
You should get int[] arr = new int[value]; out of the loop:
int arraySize = input.nextInt();
int[] arr = new int[arraySize];
for (int i=0; i<arraySize; i++)
{
int value = input.nextInt();
arr[i] = value;
}
If you don't want to limit the user for a size, use an ArrayList instead.
Problem 1:My program either does not do what I want it to do.
Dont initialize array inside for loop as loop wiil create a new array every time you iterate it.
Scanner input = new Scanner (System.in);
System.out.println("Enter no. of elements in array");
int n = input.nextInt();
int[] arr = new int[n];
System.out.println("Array length set to "+n);
for (int i=0; i<n; i++)
{
System.out.println("Enter value for index "+i);
arr[i] = input.nextInt();
System.out.println(arr[i]+" Value saved at index "+i);
}
DEMO1
Problem 2(described in comments below):Sorting arrays and displaying the middle number
class Ideone
{
static int[] countingSort(int[] numbers) {
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max)
max = numbers[i];
}
int[] sortedNumbers = new int[max+1];
for (int i = 0; i < numbers.length; i++) {
sortedNumbers[numbers[i]]++;
}
int insertPosition = 0;
for (int i = 0; i <= max; i++) {
for (int j = 0; j < sortedNumbers[i]; j++) {
numbers[insertPosition] = i;
insertPosition++;
}
}
return numbers;
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner (System.in);
System.out.println("Number of times to loop:");
int n = input.nextInt();
// int[] arr = new int[n];
// System.out.println("Array length set to "+n);
for (int i=1; i<=3; i++)
{
System.out.println("Size of array #"+i+": ");
int alen = input.nextInt();
int[] arr = new int[alen];
System.out.println("Value in array #"+i+": ");
for (int j=0; j<alen; j++){
System.out.println("Enter value at index "+j+": ");
arr[j] = input.nextInt();
}
arr=Ideone.countingSort(arr);
for (int l=0; l<alen; l++)
System.out.println(arr[l]+" Value of array #"+i+" saved at index "+l);
System.out.println("Middle value in array #"+i+" saved at index "+arr[alen/2]);
}
}
}
DEMO2
In this program, I must have user input value for variable (N). In method 1, user will input 10 numbers into an array. In method 2, it will compare variable (N) and save all numbers larger than that variable to (greaterNums) variable. Having some return and sending problems, even though I have read chapter over and over. Someone please point me in the right direction!
Problem 1: greaterNums variable value isn't correct after the arguments in method 2.
Problem 2: greaterNums variable isn't returning to main method to be displayed.
import javax.swing.JOptionPane;
public class Project6Walker
{
public static void main(String[] args)
{
final int ARRAY_SIZE = 10; //Establish array size
int n; //Holds comparable value
String input; //Holds user input
int[] array = new int[ARRAY_SIZE]; //Establishes array
input = JOptionPane.showInputDialog("Enter a number. Must not be a negative number.");
n = Integer.parseInt(input); //Gather value N
while (n < 0) //INPUT VALIDATION for N
{
input = JOptionPane.showInputDialog("Must not be a negative number. Please try again.");
n = Integer.parseInt(input);
}
gatherArrayInformation(array, input); //Calls method 1
compareArrayInformation(array, n); //Calls method 2
JOptionPane.showMessageDialog(null, "The numbers in the array that are "+
"greater than " +n+ " are (greaterNums goes here)."); //Final output of information
/**
This method will prompt the user to enter 10 numbers in the array
that will be compared to the value N
*/
}
public static int[] gatherArrayInformation(int[] array, String input)
{
JOptionPane.showMessageDialog(null, "Enter series of " + array.length + " numbers");
for (int i= 0; i < array.length; i++)
{
input = JOptionPane.showInputDialog("Number " + (i + 1) + ":");
array[i] = Integer.parseInt(input);
while (array[i] < 0)
{
input = JOptionPane.showInputDialog("Number " + (i + 1) + " cannot be negative. Try Again.");
array[i] = Integer.parseInt(input);
}
System.out.print(array[i] + " ");
}
return array;
}
/**
This method will take the 10 numbers from method 1,
and see which numbers are larger than N
#return greaterNums
*/
public static int compareArrayInformation(int[] array, int n)
{
int greaterNums = 0;
for (int i= 1; i < array.length; i++)
{
if (array[i] > n)
greaterNums = array[i];
System.out.println(greaterNums);
}
return greaterNums;
}
}
Problem 2: When you return greaterNums, as your code currently stands, it's just returning the array member with the highest index that was bigger than n.
Array indices start from 0.
public static List<Integer> compareArrayInformation(int[] array, int n)
{
List<Integer> greaterNums = new ArrayList<>();
for (int i = 0; i < array.length; i++) // Count from 0
{
if (array[i] > n) {
int greaterNum = array[i];
System.out.println(greaterNum);
greaterNums.add(greaterNum);
}
}
return greaterNums;
}
And to collect all greater numbers, one better uses no fixed sized array, int[], but a List<Integer>.
Replace your function compareArrayInformation to below
public static int compareArrayInformation(int[] array, int n)
{
int[] greaterNums = new int[10];
for (int i= 0; i < array.length; i++)
{
if (array[i] > n)
{
greaterNums.add(array[i]);
}
}
return greaterNums;
}
and in your main method change the below lines FROM
compareArrayInformation(array, n);
JOptionPane.showMessageDialog(null, "The numbers in the array that are "+
"greater than " +n+ " are (greaterNums goes here).");
TO
int[] greaterNumsArray = compareArrayInformation(array, n);
StringBuffer sBuffer = new StringBuffer("");
for (int i=0; i<greaterNumsArray.length; i++){
sBuffer.append(greaterNumsArray[i]);
}
JOptionPane.showMessageDialog(null, "The numbers in the array that are "+
"greater than " +n+ " are "+sBuffer );
this program will work with i set to 0 not one but it will of course only show THE LAST GREATER NUMBER not nums hope that is what you wanted.
public static int compareArrayInformation(int[] array, int n)
{
int greaterNums = 0;
for (int i= 0; i < array.length; i++)//not one
{
if (array[i] > n)
greaterNums = array[i];
System.out.println(greaterNums);
}
return greaterNums;
}
maybe you want this?
public static int[] compareArrayInformation(int[] array, int n)
{
int[] greaternums=new int[array.length];
int upto=0;
for (int i= 0; i < array.length; i++)//not one
{
if (array[i] > n)
greaternums[upto] = array[i];
System.out.println(array[i]);
upto++;
}
return Arrays.copyOf(greaternums, upto);
}
Ok so this is my code. I'm supposed to gather 10 numbers of input and then sort them in descending order by the number of which they appear.
Ex. {0,0,1,2,2,2]
My output would be "Mode=2 and then have 2 appears 3 times, 0 appears two times, 1 appears once."
My code can gather the 10 integers and find the mode but I'm having issues trying to sort the numbers in that way. This is what I have so far and I'm stuck.
import java.util.*;
class question2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] arrTwo = new int[10];
int x=0;
for (int i = 0; i < 10; i++)
{
System.out.println("Enter number: " + (i + 1));
arrTwo[i] = scan.nextInt();
}
mode(arrTwo);
int temp;
int bs[] = new int[10];
for ( x=0 ; x<=8 ; ++x )
{
if (bs[x]>bs[x+1])
{
temp=bs[x];
bs[x]=bs[x+1];
bs[x+1]=temp;
x=-1;
}
}
for(int i = 0; i <= bs.length-1; i++)
{
for(int index=0; index <= 99 ; index++)
{
if (i == i)
{
bs[i] +=1;
}
}
System.out.println("The number " + i + " is generated " +arrTwo[i] + " times");
}
}
public static void mode(int[] array)
{
int modeTrack[] = new int[10];
int max =0; int number =0;
for (int i = 0; i < array.length; i++)
{
modeTrack[array[i]] += 1;
}
int maxIndex = 0;
for (int i = 1; i < modeTrack.length; i++)
{
int newNum = modeTrack[i];
if (newNum > modeTrack[maxIndex])
{
maxIndex = i;
}
}System.out.println("The mode is: "+maxIndex);
}
My output isn't listing my numbers, just 0-9 and the generated times is just going from 1-9 with no basis or order.
this code:
int bs[] = new int[10];
for ( x=0 ; x<=8 ; ++x ){
if (bs[x]>bs[x+1]) {
temp=bs[x];
bs[x]=bs[x+1];
bs[x+1]=temp;
x=-1;
}
}
does nothing. On initialization bs is filled with zeroes bs[x-1] is never greater than bs[x] because all values are the same.
also
if (i == i){
is always true