package selectionsortintro;
public class SelectionSortIntro {
public static void main(String[] args) {
int nums[] = { 22, 30, 15, 1, 7, 87, 65, 24, 22, 0 };
// print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
System.out.println("\n---------------------------------");
selectionSort(nums);
// print out sorted list
System.out.println("After sorting using the Selection Sort," + " the array is:");
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
}
public static void selectionSort(int data[]) {
int smallest;
for (int i = 0; i < data.length - 1; i++) {
smallest = i;
// see if there is a smaller number further in the array
for (int index = i + 1; index < data.length; index++) {
if (data[index] < data[smallest]) {
swap(data, smallest, index);
}
}
}
}
public static void swap(int array2[], int first, int second) {
int hold = array2[first];
array2[first] = array2[second];
array2[second] = hold;
}
}
I want to add a random amount of random integers into the array, so the selection sort algorithm will sort them out. The only problem is, I don't know how to store the array with random numbers and not be a fixed amount. If that's confusing, when you make the array it's like :
int[] randomNumbers = new int[20];
Where 20 is the amount of numbers generated. Well I want to have the user be the judge of how many numbers are randomly generated into the array. So I'm thinking maybe use ArrayList? But then, I get confused as to how I can use it to add the random numbers into itself. If anyone can help me that'd be awesome
EDIT: So I got input using scanner, but I really would prefer JOptionPane as the input dialog looks a lot nicer, but if scanner is the only way that's fine. So now that that's done, I just need to actually FILL the array with random integers, does anyone know how to do that?
Here's what I came up with, I get an error with my code, if anyone could help that'd be awesome.
Scanner input = new Scanner(System.in);
Scanner s = new Scanner(System.in);
System.out.println("enter number of elements");
int n = s.nextInt();
int nums[]=new int[n];
Random randomGenerator = new Random();
//print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
nums[n] = randomGenerator.nextInt(1001);
}
Here's an example using a traditional array and a JOptionPane:
import javax.swing.*;
import java.util.Random;
public class Random_int_array {
public static void main(String[] args) {
JFrame frame = new JFrame("Total number of integers");
int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));
int[] array = new int[iTotalCount];
Random randomGenerator = new Random();
for(int i=0; i < iTotalCount; i++){
array[i] = randomGenerator.nextInt(1001);
}
// Now you can do whatever processing you would like to do
// For the sake of this answer, I will just print the numbers
for(int i=0; i < array.length; i++){
System.out.println(array[i]);
}
// We should explicitly call exit because we used a form/window
System.exit(0);
}
}
And here's an example of using an ArrayList with JOptionPane instead of a regular int[] array;
import javax.swing.*;
import java.util.Random;
import java.util.ArrayList;
public class Random_int_array {
public static void main(String[] args) {
JFrame frame = new JFrame("Total number of integers");
int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));
// Can also be written as: ArrayList<Integer> array = new ArrayList<>();
// in newer versions of Java.
ArrayList<Integer> array = new ArrayList<Integer>();
Random randomGenerator = new Random();
for(int i=0; i < iTotalCount; i++){
array.add(randomGenerator.nextInt(1001));
}
// Now you can do whatever processing you would like to do
// For the sake of this answer, I will just print the numbers
for(int i=0; i < array.size(); i++){
System.out.println(array.get(i));
}
// We should explicitly call exit because we used a form/window
System.exit(0);
}
}
Note: ArrayLists cannot use primitive data types, so you must specify it as using an Integer rather than an int.
Adding an option to set the size of the array based off of user input is a bit more tricky
The easiest way to code it is to pass in command line arguments and read them in your args variable in your main method
Another way to read input is the Scanner class
Whichever way you choose, you may end up with a String variable you need to convert to an int with
String input = args[0]; //or use Scanner
int size = Integer.parseInt(input);
Three different methods of generating random integers, from easiest to implement to hardest
To generate a random int [0, max)
(int)(Math.random() * max)
or use
Random r = new Random();
r.nextInt(max);
A more complicated way to generate a more random number instead of Java's pseudo-random generators would be to query random.org for data. Do note that this may take a bit longer to set up and code, as well as relying on third party servers (no matter how reliable they may be)
You can use the random int to initialize the input array with a random length, then fill in the values with random numbers with a for loop
Related
I need to write a program which should read a few numbers from an int, then save the values in array and to calculate the modulo of the numbers I read in.
I made this so far, but I have no idea how to store int in array, or how to calculate modulo of an array. Hope someone can help.
public class modulo {
public static void main (String[] args) {
int counter = 0;
int r = 0;
int modus;
int numbers;
int[] n;
Out.print("How many numbers you want to calculate: ");
r = In.readInt ();
Out.print("With which number you want to calculate the modulo: ");
modus = In.readInt ();
while (counter != r) {
counter++;
Out.print("Put the " + counter + ".number: ");
numbers = In.readInt ();
}
First of all, you need to new your array, otherwise you'd get NullPointerException. Since you already know your array size, this is what you will write after you've read r from the input:
int[] n = new n[r]
Then, you need a for loop to read from the input and save it to the array.
As for your next question, here is the answer.
How can I implement a modulus on a list of numbers?
Arrays are not dynamic, meaning, once given a size it will stay that size. For example "int[] arr = {1, 2, 3, 4, 5, 6}; or int[] arr = new int[5];"
For this particular example you may want to do the second declaration of array that I gave you as an example because this allows you to later declare the size of the array(after you get your input from how many numbers you want to calculate"
after this you ask with which number you want to calculate the array to. This can be done using a for loop and then doing something like:
for(int i = 0; i < arr.lenght; i++){
new_arr[i]= arr[i]%mod; //this stores each operation into a new array.
}
hope this helps!
I do this, still the same
public class modulo {
public static void main (String[] args) {
int counter = 0;
int zahlen = 0;
int modus;
int numbers;
int[] n = new int[zahlen];
int [] new_arr = new int [0];
Out.print("Wie viele Zahlen moechten Sie berechnen: ");
zahlen = In.readInt ();
Out.print("Mit welcher Zahl moechten Sie Modulo berechnen: ");
modus = In.readInt ();
while (counter != zahlen) {
counter++;
Out.print("Geben sie die " + counter + ".Zahl ein: ");
numbers = In.readInt ();
}
for(int i = 0; i < n.length; i++){
new_arr[i]= n[i]%modus;
Out.print(new_arr);
}
}
}
I need to know how to eliminate duplicate numbers in the same array. I only know creating arrays, getting data from user and print it out. Following shows my progress:
import java.util.Scanner;
public class DuplicateElimination {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int [] x = new int [10];
for (int i = 0; i < 10; i++){
System.out.println("Enter a number");
x[i] = scn.nextInt();
}
for (int i = 0 ; i<10 ; i++)
System.out.print(x[i] + " ");
}
}
The real statement is
Write a method that returns a new array by eliminating the duplicate values in the
array using the following method header:
public static int[] eliminateDuplicates(int[] list)
Write a test program that reads in ten integers, invokes the method, and displays the
result.
You can use java set data structure to eliminate duplicates. Add each element into the set. it will eliminates duplicates
Set<Integer> set=new HashSet<Integer>();
set.add(1);
Just after the statement:
x[i] = scn.nextInt();
You could loop accross the array like:
boolean isNumberFound = false;
for (int j =0; j<i; j++) {
if (lastNumberScanned == x[j]) {
isNumberFound = true;
break;
}
}
if (!isNumberFound)
x[i] = lastNumberScanned;
If you dont want to stick with Arrays, then i would suggest you using Set data structure like:
Set<Integer> myset = new HashSet<>();
myset.add(scn.nextInt());
I have an array a[5][5] and several values. I want to randomly assign values based on random percentages I create. For example one value is 6 and 25% of the elements in the array should have the value 6. With what I have so far: I created the random percentages and I'm able to randomly assign values for different elements in the array. My problem is: more than 25% of the elements have 6. My question is: How do I make sure that when assigning elements with 6, exactly 25% of the elements in the array a[5][5] have that value? I'm new to programming and tried several loops and ifs but nothing is working out for me. Please push me towards the right direction.
25% of 25 is about 6. It is not accurate. Here is a possible solution.
import java.util.Random;
import java.util.Scanner;
public class Matrix25 {
public static void main(String[] args) {
int[][] Matrix = new int[5][5];
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number you want to fill the array to 25%: ");
int number = scanner.nextInt();
int percentage=25;
generateMatrix(Matrix,number,percentage);
printMatrix(Matrix);
}
public static void generateMatrix(int Matrix[][],int num, int perc) {
int n;
int max=Matrix.length*Matrix[0].length;
int[] numbers = new int[max];
Random rnd = new Random();
int m = (int)(max * (perc/100.0));
int x=num>m?m-1:m;
for(int i=0;i<max;i++)
numbers[i]=(i<x)?num:i+1;
for(int i=0;i<Matrix.length;i++)
for(int j=0;j<Matrix[i].length;j++) {
n=rnd.nextInt(max);
Matrix[i][j]=numbers[n];
numbers[n]=numbers[max-1];
max--;
}
}
public static void printMatrix(int Matrix[][]) {
for(int i=0;i<Matrix.length;i++) {
for(int j=0;j<Matrix[i].length;j++)
System.out.printf("%3d\t",Matrix[i][j]);
System.out.print("\n");
}
}
}
I would do it like this
import java.util.Random;
import java.util.Scanner;
class Random2darray {
/**
* #param args
*/
public static void main(String[] args) {
// Create array; you specified 5x5 but you probably shouldn't hard code like this
int[][] numbers = new int[5][5];
//Create a scanner to get user input
Scanner scanner = new Scanner(System.in);
//I am not doing anything to make sure they give a decimal so the program won't work
//right if you are not giving a decimal
System.out.println("How much do you want to fill? Enter a decimal.");
//Get a double
double populatePercentage = scanner.nextDouble();
System.out.println("What number do you want to fill with?");
//Get an int
int fillNumber = scanner.nextInt();
//Don't hardcode like this
int fillTimes = numberOfTimesToFill(25, populatePercentage);
//This is declared outside of the loops because otherwise it will be
//reset each time the loop runs
int count = 0;
//Create a random number generator; default seed is current time which is good enough for this
Random rand = new Random();
//Fill the array with numbers
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
//Check if you have filled with given number enough times
if(count < fillTimes){
numbers[i][j] = fillNumber;
//Increment count by 1; this is how you are keeping track
count++;
}else{
//Otherwise pick a random number generator
//This will pick a random int between 0 - 50 inclusive
int randomNumber = rand.nextInt(51);
//This will make sure that you are not generating random numbers that are the same
//as the number you are filling with; This says if it is the same generate a new number
while(randomNumber == fillNumber){
randomNumber = rand.nextInt(51);
}
//Once we know its random fill the spot in the array
numbers[i][j] = randomNumber;
}
}
}
//Print the array out
printArray(numbers);
}
private static void printArray(int[][] numbers) {
//Just loop through and print every number
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
//Print with formatting: this says print a digit (%d) followed by a
//tab(\t) and then specifies what number I want to print
System.out.printf("%d\t", numbers[i][j]);
}
//Print a new line after each row
System.out.printf("\n");
}
}
private static int numberOfTimesToFill(int elements, double populatePercentage) {
System.out.println((int)(populatePercentage * elements));
//Cast to an int to truncate the decimal part of the number because you can't have
//a fraction of an element
return (int)(populatePercentage * elements);
}
}
I have commented the code to explain what everything does. However it does not protect against bad user input and it hardcodes the size of the array, you should always try to avoid hardcoding. In this example I did it (and marked where) to be more clear. Also as was mentioned in the comments above, for your situation where you want exactly 25% of 25 is not possible. This is because .25 * 25 = 6.25 and you can't have .25 of an element.
Java Arrays: Finding Unique Numbers In A Group of 10 Inputted Numbers
I have a problem that I have looked into Doestovsky's question but from his question, I need to know on how to make the part on finding duplicates into a function of it's own:
java.util.Scanner input = new java.util.Scanner(System.in);
int[] numbers = new int[10];
boolean[] usedBefore = new boolean[10];
// Insert all numbers
for (int i = 0; i < numbers.length; i++) {
// Read number from console
numbers[i] = input.nextInt();
// Check if number was inserted before
usedBefore[i] = false;
for(int k = 0; k < i; k++) {
if(numbers[k] == numbers[i]) {
usedBefore[i] = true;
break;
}
}
}
// Print all numbers that were not inserted before
for(int j = 0; j < numbers.length; j++) {
if(!usedBefore[i]) {
System.out.print(String.valueOf(numbers[j])+" ");
}
}
I have tried this part of this code and it worked but I need this to take the part that find duplicates into a function of it's own that is powered by arrays.
Credits to ThimoKl for creating this code.
Let's try something else, using Treeset, and let's get rid of that for for
import java.util.*;
public class duplicate {
private static TreeSet<Integer> numbers = new TreeSet<Integer>();
private static TreeSet<Integer> duplicates = new TreeSet<Integer>();
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int n=0;
int numberOfIntToRead=10;
for (int i = 0; i < numberOfIntToRead; i++) {
// Read number from console
n=input.nextInt();
// Check if number was inserted before
checkIfDuplicate(n);
}
// Print all numbers that were not inserted more than one time
for (Integer j : numbers) {
System.out.print(j+" ");
}
}
public static void checkIfDuplicate(int n){
if(!numbers.contains(n) && !duplicates.contains(n)){
numbers.add(n);
}else{
numbers.remove(n);
duplicates.add(n);
}
}
}
But if you really want to use arrays an not a Collection of any sort, then you need to declare your arrays as class members, that way you can put the "for" that checks for duplicates in a function a give it your i, and this way you can also put the "for" that does the printing in a function. and give to it numbers.length. That should do the trick.
You can make use of a Set to make finding duplicates easy:
List<Integer> dups = new ArrayList<>();
Set<Integer> set = new HashSet<>();
for (int i : numbers)
if (!set.add(i))
dups.add(i);
This works because Set#add() returns false if it doesn't change as a result if being called, which happens eggnog the set already contains the number - ie it's a dup.
Im working on an assignment for a beginners Java course, and Im having a problem with printing out an array the way that its asking for. The problem is as follows:
"Write a program that asks the user "How many numbers do you want to enter?" With that value, create an array that is big enough to hold that amount of numbers (integers). Now ask the user to enter each number and store these numbers into the array. When all the numbers have been entered, display the numbers in reverse order from the order in which they were entered."
I have everything except the last part, displaying the numbers in reverse order.
Any help on this would be appreciated.
Heres What I have so far:
import java.util.Scanner;
public class ArraysNickGoldberg
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("How many numbers do you want to enter?");
final int NUMBER_OF_ELEMENTS = input.nextInt();
int[] myList = new int[NUMBER_OF_ELEMENTS];
for( int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
System.out.println("Enter a new number: ");
myList[i] = input.nextInt();
}
for( int i = 0; i < NUMBER_OF_ELEMENTS; i++){
System.out.print(myList[i] + " ");
}
}
}
try
for( int i = NUMBER_OF_ELEMENTS - 1; i >= 0; i--){
System.out.print(myList[i] + " ");
}
You may also want to look at
Java Array Sort
to print it in reverse order, you just need to simply reverse your for loop :)
so instead of
for(int i=0; i< NUMBER_OF_ELEMENTS; i++){
}
use this instead:
for(int i=NUMBER_OF_ELEMENTS - 1; i >= 0; i--){ //remember to minus 1 or else you'll get index of out of bound
}