How To create Array Of 100 With Integers From 1-1000? - java

I know how to create an array of 100 with integers from 1-100 which will be just:
int [] array = new int[100]; // Sorted Array of 100
for (int a = 0; a < array.length; a++) {
array[a] = a + 1;
}
But my question is how to create an array of 100 with some sorted integers from 1-1000, inclusive. Any help will be appreciated!

How about this?
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
array[a] = (a + 1) * 10;
}
Simple, if you have no other requirement.
Edit: To make it almost sorted (like every 10th unsorted element), there are many ways. One, using BevynQ's solution, can be:
Random r = new Random();
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if ((a + 1) % 10 != 0) {
array[a] = (a + 1) * 10;
} else {
array[a] = r.nextInt(1000);
}
}

Here is a simple solution using random
Random r = new Random();
int [] array = new int[100];
int last = 0;
for (int a = 0; a < array.length; a++) {
last = last + r.nextInt(10) + 1;
array[a] = last;
}

You can even create an array with data elements of a particular sequence such as prime numbers, factors or some series like fibonacci series.
Example:
class Fibonacci {
public static void main(String args[]) {
int array[] = new int[100];
System.out.println("*****Fibonacci Series*****");
int f1, f2=0, f3=1;
for(int i=1;i<=100;i++) {
array[i] = f3;
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
}
}

You can even make it so how sorted it is can easily be changed by the user. This is a lot more code to write, but works in essence by swaping a certain number of spots in the array. That number can change by the user. I put 0 to 100 before swaping the numbers, but all that matters is it is a well orderd math pattern.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package partlysorted;
import java.util.Scanner;
/**
*
* #author Library computer
*/
public class PartlySorted {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//scanner for user input
Scanner input = new Scanner(System.in);
//intro
System.out.println("Welcome to the partly sorted pogram");
System.out.println("This will make a partly sorted list of integers");
//the numbers
int[] nums = new int[100];
//how unsorted for it to be
int suffels = -1;
//when to show a typo message
boolean firstLoop = true;
while(suffels < 0 || suffels > 100)
{
if(firstLoop)
{
System.out.println("Please enter how sorted sorted you want (0 to 100, no decimals)");
}
else
{
System.out.println("Looks like you made a typo");
System.out.println("Please enter a integer from 0 to 100");
}
suffels = input.nextInt();
firstLoop = false;
}
//fill it sorted first
for(int i = 0; i < nums.length; i++)
{
nums[i] = i;
}
//suffle the array
for(int swaps = 0; swaps < suffels; swaps++)
{
int firstPlace = (int)(Math.random() * 100);
int secondPlace = (int)(Math.random() * 100);
//swap the places
int temp = nums[firstPlace];
nums[firstPlace] = nums[secondPlace];
nums[secondPlace] = temp;
}
//printing it out
for(int n: nums)
{
System.out.println(n);
}
}
}

Related

find probability of n people in a class of x share the same birthday using monte carlo simulation in java

As the problem states, i must use monte carlo(randomness) to solve the question given. I am running the simulation 1,000,000 times.
import java.util.*;
public class MonteCarlo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter size of the class: ");
int classSize = sc.nextInt();
System.out.println("Please enter the amount of people who share the same birthday: ");
int birthPpl = sc.nextInt();
System.out.println("calculate the probability that "+birthPpl+" people share the same Birthday in a class size of "+classSize);
sc.close();
int birthdays [] = new int[classSize];
int simulations = 0;
int success=0;
for(int i=0; i<1000000; i++){
simulations++;
if(Collision(birthdays)>=birthPpl){
success++;
}
}
System.out.println(success+" "+simulations);
System.out.println("Answer: "+ (success*100)/simulations + "%");
}
public static int Collision(int birthday[]){
Random rand = new Random();
for(int i=1; i<birthday.length; i++){
birthday[i]= rand.nextInt(365);
}
int count = 0;
for(int i=0; i<birthday.length; i++){
for(int j= i+1; j<birthday.length; j++){
if(birthday[i]==birthday[j]){
count++;
}
}
}
return count;
}
}
As per a couple of psuedo code solutions i have seen online i have tried looping through the size of the class x and inserting in a random birthday. then comparing birthdays , reducing the birthdays i look through by 1 each time. I then check the number of collisions against the amount sof ppl who should a birthday , if it is greater or equal to it than i increase the count. i have been given sample imput 20 and 2 which should give 41 % but my program gives eithe 7 or 8 %
What's the problem, and how can it be fixed?
You could also make use the Random and HashMap classes. Map.merge will take the key, a birthday in this case, then a default value of 1, and continues to add 1 to the existing value which is returned and compared to x. Then success is appropriately updated. The Random class provides a variety of methods to return random numbers and is usually preferred over Math.random.
double success = 0;
int tests = 1_000_000;
// instantiate a Random class for selecting the next birthday
Random r = new Random();
// a map to hold the frequency count of same birthdays
Map<Integer,Integer> birthdays = new HashMap<>();
int n = 23;
int x = 2;
for(int i=0; i< tests; i++) {
for (int j = 0; j < n; j++) {
if (birthdays.merge(r.nextInt(365), 1, Integer::sum) >= x) {
success++;
break;
}
}
// clear the map for the next run
birthdays.clear();
}
Using System.out.printf facilitates formatting the output.
System.out.printf("probability = %4.1f%%%n", (success/tests) * 100);
prints something like the following:
probability = 50.7%
import java.util.Scanner;
public class Birthday {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // class size
int x = sc.nextInt(); // people who share the same birthday
double tests = 1_000_000;
double success = 0;
// fills array of birthdays and breaks out when x amount of people share
// a birthday. then we find the % of successes.
for (int i = 0; i < tests; i++) {
int[] year = new int[365];
for (int j = 0; j < n; j++) {
int birthday = (int) (Math.random() * 365);
year[birthday]++;
if (year[birthday] >= x) {
success++;
break;
}
}
}
System.out.println(Math.round(success * 100 / tests));
}
}

How to create random numbers a specific number of times?

How can i create a random number a specific numbers of time?
public class Feld {
public static void main(String[] args) {
double k = (int)(Math.random()*1000001);
int n = 1000000;
int arr[] = new int[n];
int i = 0;
for(i = 0;i<n;i++){
arr[i] = i;
}
boolean found = false;
i=0;
while (i < arr.length) {
if (arr[i] == k) {
found = true;
break;
}
i++;
}
if (found) {
i++;
System.out.println(i);
}
else {
System.out.println((arr.length + 1));
}
}
}
My problem is, that if i put k into a loop to create it more than one time i'll get an error at:
if (arr[i] == k)
!!I just found out that i made a mistake explaining my problem. The array should be filled with values from 0-1.000.000 and i am supposed to print out the position of a random generated number for a specific amount of times.
If you want to have an array full of random numbers, I suggest using the following:
int n = 1000000;
int arr[] = new int[n];
for(int i = 0; i < n; i++){
arr[i] = (int)(Math.random() * 1000001);
}
That will work and you don't even need the variable k.
Edit:
If you want to print at what position you find a specific value (for example x = 543), you can use the following code:
int x = 543;
int n = 1000000;
int arr[] = new int[n];
for(int i = 0; i < n; i++){
arr[i] = (int)(Math.random() * 1000001);
if(arr[i] == x) {
System.out.println(i);
break;
}
}
Edit2
One possible solution to your new problem looks like this:
public class Feld {
public static void main(String[] args) {
int n = 1000000;
int arr[] = new int[n];
int i = 0;
for(i = 0; i < n; i++){
arr[i] = i; //Filling array with values 0-1000000
}
int number = 20; //Print out position of a random generated number a specific amount of times
int randomNumber = (int)(Math.random()*1000001); //The random number
for(int j = 0; j < number; j++) { //Find number for a specific amount of times
for(int k = 0; k < arr.length; k++) { //Find number in array
if(arr[k] == randomNumber) {
System.out.println(arr[k]); //Print
break; //Number found, don't have to search anymore
}
}
}
}
}
I would write a method that returns an array of random numbers and takes an int argument that defines the length of the array.
One possible solution is this:
public static int[] createRandomArray(int length) {
// create an array of the given length
int[] result = new int[length];
// and use a single for loop that puts random int values into every index
for (int i = 0; i < result.length; i++) {
result[i] = ThreadLocalRandom.current().nextInt();
}
// then simply return the result
return result;
}
Try it as follows
public static void main(String[] args) {
// super primitive time measurement:
// take the moment in time before calling the method
Instant start = Instant.now();
// then call the method
int[] array = createRandomArray(1000000);
// and take the moment in time after the method returned
Instant end = Instant.now();
// then calculate the duration
Duration duration = Duration.between(start, end);
// and print the duration in milliseconds
System.out.printf("Array creation took %d milliseconds\n", duration.toMillis());
}
The result is the following output on my system:
Array creation took 10 milliseconds

Random Shuffling an array of integers in Java [duplicate]

This question already has answers here:
Random shuffling of an array
(31 answers)
Closed 6 years ago.
This is my first time with arrays.
I should prompt the user to enter 5 array values and then display them in random order.
I am quite confused, since it's my first time doing this.
Anyway, my code is here.
import java.util.*;
public class Test {
public static void main(String[] args) {
int myArray[] = new int[5];
System.out.println("Please enter 5 numbers: ");
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length - 1; i--) {
int j = (int) (Math.random() * (i + 1));
myArray[i] = input.nextInt();
System.out.println("The numbers are: ");
System.out.println(myArray[0]);
System.out.println(myArray[1]);
System.out.println(myArray[2]);
System.out.println(myArray[3]);
System.out.println(myArray[4]);
int temp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = temp;
System.out.println("The numbers, shuffled, are: ");
System.out.println(myArray[0]);
System.out.println(myArray[1]);
System.out.println(myArray[2]);
System.out.println(myArray[3]);
System.out.println(myArray[4]);
}
}
}
Thank you everyone for your support.
A - Explanation
Let's say you take the input values in order as {'1','2','3','4','5'}. What shuffling is corrupting the order randomly, so you have to change the position of elements randomly.
In the demo code,
swapArrayElement swaps the elements those that positions are passed as parameters.
getRandom returns a random value between 0 and the range which passed to the method as a parameter.
shuffleArray shuffles the array by changing the positions of elements randomly. Please notify that there is an additional boolean isShuffled[] array and it is boolean because we have to keep the track of positions whether they are shuffled or not.
isArrayShuffled method, checks that if all positions are shuffled or not.
B - Demo Code
import java.util.Scanner;
public class Test {
public static final int ARRAY_LENGTH = 5;
public static void main(String[] args) {
int myArray[] = new int[ARRAY_LENGTH];
Scanner input = new Scanner(System.in);
System.out.println("Please enter 5 numbers: ");
for(int i = 0; i < myArray.length; i++)
myArray[i] = input.nextInt();
System.out.println("\nThe numbers are: ");
printIntArray(myArray);
shuffleArray(myArray);
System.out.println("\nThe numbers, shuffled, are: ");
printIntArray(myArray);
input.close(); // no memory leaks!
}
// method for printing array
public static void printIntArray(int[] array) {
for(int i = 0; i < array.length; i++)
System.out.printf("%2d ", array[i]);
System.out.printf("%n"); // use %n for os-agnostic new-line
}
// method for shuffling array
public static void shuffleArray(int[] array) {
int range = array.length;
boolean isShuffled[] = new boolean[range]; // store which positions are shuffled
while(!isArrayShuffled(isShuffled)) {
int positionSrc = getRandom(range);
int positionDst = getRandom(range);
swapArrayElement(array, positionSrc, positionDst);
isShuffled[positionSrc] = true;
isShuffled[positionDst] = true;
}
}
public static int getRandom(int maxRange) {
return (int)(Math.random()*maxRange);
}
public static void swapArrayElement(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static boolean isArrayShuffled(boolean[] isShuffled) {
for(int i = 0; i < isShuffled.length; i++)
if(isShuffled[i] == false)
return false;
return true;
}
}
C - Demo Output
Please enter 5 numbers:
1 2 3 4 5
The numbers are:
1 2 3 4 5
The numbers, shuffled, are:
4 2 5 1 3
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void shuffle(int[] arr) {
Random rnd = ThreadLocalRandom.current();
for (int i = arr.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
int t = arr[index];
arr[index] = arr[i];
arr[i] = t;
}
}
public static void main(String[] args) {
int myArray[] = new int[5];
System.out.println("Please enter 5 numbers: ");
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length; i++) {
System.out.println("Enter " + (i + 1) + ". number: ");
myArray[i] = input.nextInt();
}
System.out.println("The numbers are: ");
for (int j2 = 0; j2 < myArray.length; j2++) {
System.out.println(myArray[j2]);
}
shuffle(myArray);
System.out.println("The numbers, shuffled, are: ");
for (int j2 = 0; j2 < myArray.length; j2++) {
System.out.println(myArray[j2]);
}
}
}

Radix sort implementation

I am trying to make radix sort function that calculates the number of digits of integer numbers using the radix sort as a base, and then sort the numbers from least significant to most significant.
I am using an array that holds random integers.
How can I make this method works well?
I am using this code:
public static void sort( int[] a, int radix)
{
int i, m = a[0], exp = 1, n = a.length;
int[] b = new int[10];
for (i = 1; i < n; i++)
if (a[i] > m)
m = a[i];
while (m / exp > 0)
{
int[] bucket = new int[10];
for (i = 0; i < n; i++)
bucket[(a[i] / exp) % 10]++;
for (i = 1; i < 10; i++)
bucket[i] += bucket[i - 1];
for (i = n - 1; i >= 0; i--)
b[--bucket[(a[i] / exp) % 10]] = a[i];
for (i = 0; i < n; i++)
a[i] = b[i];
exp *= 10;
}
}
Try
int[] b = new int[a.length];
or since n = a.length
int[] b = new int[n];
I am just pointing out the most obvious problems and leave the details to you.
Each bucket will have to hold a list of numbers so using just an int as a bucket is not going to work. Use something like this instead:
List<Integer>[] bucket = new List<Integer>[10];
The array used to collect the elements in the new order needs to be the same size as the original array. You just have made it 10 long.
Statement in last for loop
a[i] = b[i];
tells that size of b must be equal to or greater than a. Hence go for #rcgldr answer. Also the value of radix passed to your function is lying unused. You can also make your function a tad faster by swapping array pointers instead of copying the elements i.e. avoiding the last for loop.
int swap[] = a;
a = b;
b = swap;
then finally after all the loops are over, return the array a
return a;
Above is your program for sorting in ascending order. I am giving below the program to sort in descending order. The only change that was required was to start adding frequencies from the end of the base array( in this case Z ) to index zero.
public static int[] DSC(int A[], int radix, int base)
{
int length = A.length ;
int B[] = new int[length] ;
int div = 1 ;
int swap[] ;
int i ;
while(radix > 0)
{
int Z[] = new int[base] ;
i = 0 ;
while(i < length)
{
Z[( A[i] / div ) % base]++ ;
i++ ;
}
i = base ;
while(i > 1)
{
i--;
Z[i-1] += Z[i] ;
}
i = length ;
while(i > 0)
{
i-- ;
B[--Z[( A[i] / div ) % base]] = A[i];
}
swap = A;
A = B;
B = swap;
div *= base;
radix--;
}
return A;
}
For non-negative integers, using binary instead of decimal, might be more efficient & intuitive for machine.
Here is an implementation I wrote, with test case:
RadixSort.java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* Radix sort.
*
* #author eric
* #date 3/12/20 12:05 PM
*/
public class RadixSort {
/**
* Sort given array, the array will be modified.
*
* #param data array of integer of non-negative integers,
* #throws IllegalArgumentException if input contain negative integer,
*/
public static void sort(int[] data) {
int numSys = 2;
int bits = validAndfindHighestBit(data); // find highest bit,
// create queues,
List<List<Integer>> queues = new ArrayList<>(numSys);
for (int i = 0; i < numSys; i++) queues.add(new LinkedList<>());
// sort bit by bit, low to high,
for (int i = 0; i < bits; i++) {
// re-init queues,
for (int j = 0; j < numSys; j++) queues.get(j).clear();
// array -> queues,
for (int x : data) {
int bit = (x >> i) & 1; // get the i-th bit,
queues.get(bit).add(x);
}
// queues -> array,
int t = 0;
for (List<Integer> queue : queues) {
for (int x : queue) data[t++] = x;
}
}
}
/**
* Valid input number, and find highest bit that has 1.
*
* #param data
* #return
* #throws IllegalArgumentException if input contain negative integer,
*/
private static int validAndfindHighestBit(int[] data) {
// find max number,
int max = 0;
for (int x : data) {
if (x < 0) throw new IllegalArgumentException("negative integers are not supported");
if (x > max) max = x;
}
System.out.printf("max number: %d, ", max);
// find highest bit,
int highestBit = 0;
while (max != 0) {
highestBit++;
max >>= 1;
}
System.out.printf("highest bit: %d\n", highestBit);
return highestBit;
}
}
RadixSortTest.java
(Test case via TestNG)
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import static org.testng.Assert.*;
/**
* RadixSort test.
*/
public class RadixSortTest {
#Test
public void testSort() {
int[] data;
// generated un-sorted random array,
do data = genRandomArr(); while (data.length > 1 && isSorted(data));
System.out.printf("input arr:\t%s\n", Arrays.toString(data));
if (data.length > 1) Assert.assertFalse(isSorted(data));
// sort
RadixSort.sort(data);
System.out.printf("output arr:\t%s\n", Arrays.toString(data));
Assert.assertTrue(isSorted(data));
}
// corner case,
#Test
public void testSort_corner() {
int[] dataEmpty = new int[0]; // empty array,
RadixSort.sort(dataEmpty);
Assert.assertTrue(isSorted(dataEmpty));
int[] dataSingle = new int[]{5}; // single element,
RadixSort.sort(dataSingle);
Assert.assertTrue(isSorted(dataSingle));
}
// invalid input,
#Test(expectedExceptions = IllegalArgumentException.class)
public void testSort_invalid() {
int[] dataSingle = new int[]{1, -1}; // negative number,
RadixSort.sort(dataSingle);
}
/**
* generate random array, of size 10, in range [0, 1024),
*
* #return
*/
public static int[] genRandomArr() {
return genRandomArr(10, 100);
}
/**
* generate random array,
*
* #param size array size, default to 10,
* #param bound upper bound, default to 100,
* #return
*/
public static int[] genRandomArr(int size, int bound) {
if (size <= 0) size = 10;
if (bound <= 0) bound = 100;
ThreadLocalRandom rd = ThreadLocalRandom.current();
int[] arr = new int[size];
for (int i = 0; i < arr.length; i++) arr[i] = rd.nextInt(bound);
return arr;
}
// check whether array is sorted,
private static boolean isSorted(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) return false;
}
return true;
}
}

How can i generate all subsets of a variable length set?

I am trying to write a program that generates all the subsets of an entered set in java. I think i nearly have it working.
I have to use arrays (not data structures)
The entered array will never be greater than 20
Right now when i run my code this is what i get:
Please enter the size of A: 3
Please enter A: 1 2 3
Please enter the number N: 3
Subsets:
{ }
{ 1 }
{ 1 2 }
{ 1 2 3 }
{ 2 3 }
{ 2 3 }
{ 2 }
{ 1 2 }
this is the correct number of subsets (2^size) but as you can see it prints a few duplicates and not some of the subsets.
Any ideas where I am going wrong in my code?
import java.util.Scanner;
public class subSetGenerator
{
// Fill an array with 0's and 1's
public static int [] fillArray(int [] set, int size)
{
int[] answer;
answer = new int[20];
// Initialize all elements to 1
for (int i = 0; i < answer.length; i++)
answer[i] = 1;
for (int a = 0; a < set.length; a++)
if (set[a] > 0)
answer[a] = 0;
return answer;
} // end fill array
// Generate a mask
public static void maskMaker(int [] binarySet, int [] set, int n, int size)
{
int carry;
int count = 0;
boolean done = false;
if (binarySet[0] == 0)
carry = 0;
else
carry = 1;
int answer = (int) Math.pow(2, size);
for (int i = 0; i < answer - 1; i++)
{
if (count == answer - 1)
{
done = true;
break;
}
if (i == size)
i = 0;
if (binarySet[i] == 1 && carry == 1)
{
binarySet[i] = 0;
carry = 0;
count++;
} // end if
else
{
binarySet[i] = 1;
carry = 1;
count++;
//break;
} // end else
//print the set
System.out.print("{ ");
for (int k = 0; k < size; k++)
if (binarySet[k] == 1)
System.out.print(set[k] + " ");
System.out.println("}");
} // end for
} // maskMaker
public static void main (String args [])
{
Scanner scan = new Scanner(System.in);
int[] set;
set = new int[20];
int size = 0;
int n = 0;
// take input for A and B set
System.out.print("Please enter the size of A: ");
size = scan.nextInt();
if (size > 0)
{
System.out.print("Please enter A: ");
for (int i = 0; i < size; i++)
set[i] = scan.nextInt();
} // end if
System.out.print("Please enter the number N: ");
n = scan.nextInt();
//System.out.println("Subsets with sum " + n + ": ");
System.out.println("Subsets: ");
System.out.println("{ }");
maskMaker(fillArray(set, size), set, n, size);
} // end main
} // end class
The value of i always goes from 0 to N-1 and then back to 0. This is not useful to generate every binary mask you need only one time. If you think about it, you need to move i only when you have generate all possible masks up to i-1.
There is a much easier way to do this if you remember every number is already internally represented in binary in the computer and everytime you increment it Java is doing the adding and carrying by itself. Look for bitwise operators.

Categories