I have to pass two arrays
1) that are filled with 1000 int's between 0-100
2) that contains ten bins to sort the 1000 numbers.
How do I create the counter to sort numbers into ten bins such as 0-9, 10-19, 20-29, 30-39, 40-49,50-59 and so on to 90-99...
Would it be with an if/else that sorts them? If so, how do I add values into each bin? Would it be something like this?
This is what I have so far:
//initialize array of 1000 elements
int[] numbers = new int[1000];
int i = 0;
//initialize array of 10 bins
int[] bins = new int[10];
void setup() {
// Populate array with random number
for (int i = 0; i < numbers.length; i++) {
numbers[i] = ceil(random(0,99));
}
}
//function that sorts random numbers into bins
void counter(int[] numbers, int[] bins) {
}
If you want every number from numbers in the right bin then I would use an array of 10 ArrayLists as the datastructure for your bins.
int[] numbers = new int[1000];
ArrayList[] bins = new ArrayList[10];
void setup() {
for(int i = 0; i<bins.length; i++) {
bins[i] = new ArrayList();
}
for (int i = 0; i < numbers.length; i++) {
numbers[i] = floor(random(0,100));
}
}
void counter(int[] numbers, ArrayList[] bins) {
for (int i = 0; i < numbers.length; i++) {
bins[floor(float(numbers[i])/10.0)].add(numbers[i]);
}
}
You then get a bin with (for example the first bin consisting of numbers with values 0-9):
int sizeBin = bins[0].size();
for(int i=0; i<sizeBin; i++) {
println(bins[0].get(i));
}
If you want the count of numbers in a bin you can get it with (again an example with the bin 0-9)
bins[0].size();
the simplest way a can think of is to use a for loop to cycle through the numbers[] and then a series of if statements to evaluate whether the number is <= 9 , <= 19 etc
void counter(int[] numbers, int[] bins){
int count = 0;
int length = numbers.length;
for(int i = 0; i< length; i++){
if(numbers[i] <= 9){
bins[count] = numbers[i];
count++;
}
//and the same for 10-19 etc...
}
something like this maybe? not very eloquent but since the array is only 1000 elements it should suffice
Related
I am a beginner in coding. I have to write a code that will divide array with random numbers into two different arrays. One array will contain odd numbers, the other one even numbers. But something is wrong, and i don't really know what to do.
According to the console the problem is in the place where there is a lot of exclamation marks. when i change those lines to System.out.println("x") it works perfectly fine.
public void P_N () {
int I_E = 0; // amount of even numbers
int I_O = 0; // amount of odd numbers
for (int i = 0; i < tab2.length; i++) { // tab2 is a array with random numbers
if (tab2[i] % 2 == 0)
I_E = I_E + 1;
else
I_O = I_O+1;
}
int [] tab_E = new int[I_E]; // array with even numbers
int [] tab_O = new int [I_O]; // array with odd numbers
for (int i = 0; i < tab2.length; i++){
if (tab2[i] % 2 == 0){
tab_E[i] = tab2[i]; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
for (int i = 0; i < tab2.length; i++){
if (tab2[i] % 2 != 0){
tab_O[i] = tab2[i]; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
for (int i = 0; i< tab_E.length; i++) {
System.out.println("Even array: " + tab_E[i]);
System.out.println("------------------------------------------------");
}
for (int i = 0; i< tab_O.length; i++) {
System.out.println("Odd array: " + tab_O[i]);
}
}
Problem is in going out of bounds for arrays tab_E and tab_O, when variable i is more tab_E.length. Just create another variable, for example "j". And iterate throug your array using it. Like I'v written below
int j = 0;
for (int i = 0; i < tab2.length; i++) {
if (tab2[i] % 2 == 0) {
tab_E[j++] = tab2[i];
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
j = 0;
for (int i = 0; i < tab2.length; i++) {
if (tab2[i] % 2 != 0) {
tab_O[j++] = tab2[i];
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
I would rather use 2 ArrayLists one for even numbers and another one is for odd numbers and later convert it into array using toArray() method.
public void P_N(){
ArrayList<Integer> evenNumberList = new ArrayList<Integer>();
ArrayList<Integer> oddNumberList = new ArrayList<Integer>();
for (int i = 0; i < tab2.length; i++) { // tab2 is a array with random numbers
if (tab2[i] % 2 == 0) {
evenNumberList.add(tab2[i]);
} else {
oddNumberList.add(tab2[i]);
}
}
int[] evenNumberArray = evenNumberList.toArray();
int[] oddNumberArray = oddNumberList.toArray();
}
This will take some extra space but makes your application more efficient, I hope this helps.
You have initialized the even/odd number arrays with a quantity of the even/odd numbers accordingly:
int [] tab_E = new int[I_E]; // array with even numbers
int [] tab_O = new int [I_O]; // array with odd numbers
Ii is reasonable to assume that the sizes of even or odd number arrays are might be much smaller than the size of the original source array.
But in this even number filtering loop (as well as in the odd filtering loop) you use source array index values to address target array positions, end eventually face the ArrayIndexOutOfBoundsException.
for (int i = 0; i < tab2.length; i++)
{
if (tab2[i] % 2 == 0)
{
tab_E[i] = tab2[i]; //here the same i value is used to address non existing index in tab_E array
}
}
A quick fix might be the following:
int tab_E_index = 0;
for (int i = 0; i < tab2.length; i++){
if (tab2[i] % 2 == 0){
tab_E[tab_E_index] = tab2[i]; //i value gets incremented every loop iteration
tab_E_index++; //tab_E_index value get incremented only when even number is added to the tab_E array
}
}
Please don't just copy/paste it, but try to understand what caused the issue on the first place. Good luck and happy coding.
I'm looking to create a dynamic amount of arrays of random integers and then put them into an array list. Later I want to use each of these arrays separately to test for quick sort functionality. I'm having problems with adding the object List[] into the ArrayList.
//Create dynamic amount of random arrays
public static ArrayList<int[]> Randomizer(int arrays, int size, int seed){
ArrayList<int[]> Tests = new ArrayList<int[]>(arrays);
int[] List = new int[size];
for (int j = 0; j < arrays; j++){
Random r = new Random(seed+j);
for(int i = 0; i < size; i++){
List[i] = r.nextInt(5*size);//Multiplier for how big the numbers get
System.out.print(List[i] + ",");
}
System.out.println();
Tests.add(j, List);
}
return Tests;
}
public static void main(String[] args) {
int tests = 5;
int size = 4;
ArrayList<int[]> Test = Randomizer(tests,size,10); //1st = Number of Tests
//2nd = Number of Digits
//3rd = seed for Randomizer
for(int i = 0; i < Test.size(); i++){
System.out.println(Test.get(i));
}
}
}
The problem with your code was that you were storing the same array 5 times into the ArrayList, so when printing during generation it printed correct numbers, but later you couldn't get them out. Each iteration of the for loop was overwriting the values generated earlier.
Here is the corrected code:
private static ArrayList<int[]> randomizer(int arrays, int size, int seed){
ArrayList<int[]> tests = new ArrayList<>(arrays);
for (int j = 0; j < arrays; j++) {
int[] list = new int[size];
Random r = new Random(seed + j);
for(int i = 0; i < size; i++) {
list[i] = r.nextInt(5 * size); // Multiplier for how big the numbers get
}
tests.add(j, list);
}
return tests;
}
public static void main(String[] args) {
int tests = 5;
int size = 4;
ArrayList<int[]> arrays = randomizer(tests, size, 10);
for (int i = 0; i < arrays.size(); i++){
int[] ints = arrays.get(i);
for (int j = 0; j < ints.length; j++) {
System.out.print(ints[j] + ",");
}
System.out.println();
}
}
Basically you needed to move the int[] list = new int[size]; line inside the for loop, so that you are actually creating new arrays instead of using the same one each time.
You can now replace the printing loop in the main() method with whatever you like, like your quick sort tests. Let me know if anything still doesn't work.
The user will type in the number for i (variant), then the number for j (elements for every variant), and finally the maximum value possible (maxElem).
Using the inputed values, the task is to generate nonrepeating random numbers (nonrepeating in a variant, meaning for i, but the numbers may repeat during the entire array).
For example, a successful output giving the input 3 (i), 5 (j), 9 (maxElem), would be:
4|8|1|7|9
3|8|2|4|5
2|6|4|8|5
As you may notice, the number 4 repeats itself during the entire array for 3 times (allowable). But, for i=0, number 4 is unique.
Please, guide me what would be the changes to this code:
static Scanner sc = new Scanner(System.in);
static int maxElem;
public static void main(String[] args) {
int[][] greatLoto;
System.out.println("Of how many variants will the ticket consist? ");
int variants = sc.nextInt();
System.out.println("Of how many elements will the variants consist? ");
int elements = sc.nextInt();
System.out.println("Which value should be considered the maximum value? ");
maxElem = sc.nextInt() + 1;
greatLoto = new int[variants][elements];
System.out.println("Initial values: ");
show(greatLoto);
System.out.println("Modifying values...");
modified(greatLoto);
System.out.println("Newest values: ");
show(greatLoto);
}
private static void show(int[][] greatLoto) {
for (int i = 0; i < greatLoto.length; i++) {
for (int j = 0; j < greatLoto[i].length; j++) {
System.out.print("|" + greatLoto[i][j] + "|");
}
System.out.println("");
}
System.out.println("");
}
private static void modified(int[][] greatLoto) {
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < greatLoto.length; i++) {
for (int j = 0; j < greatLoto[i].length; j++) {
while (Arrays.asList(greatLoto[i]).contains(r)) {
r = new Random(System.currentTimeMillis());
}
greatLoto[i][j] = r.nextInt(maxElem);;
}
System.out.println("");
}
}
This is more of a comment but too long: don't use random.next() because it forces you to check for uniqueness. Instead fill a list with the valid values and shuffle it:
List<Integer> values = new ArrayList<> ();
for (int i = 1; i <= max; i++) values.add(i);
Collections.shuffle(values);
Then you can simply iterate over the values and take the j first numbers.
Note that if j is significantly greater than i using the random approach would probably be more efficient.
The most minimal change would be:
private static void modified(int[][] greatLoto) {
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < greatLoto.length; i++) {
for (int j = 0; j < greatLoto[i].length; j++) {
do {
greatLoto[i][j] = r.nextInt(maxElem);
} while (Arrays.asList(greatLoto[i]).contains(greatLoto[i][j]));
}
System.out.println("");
}
}
But there are more elegant (but difficult to code) ways to generate unique random numbers without discarding duplicates.
You need three loops:
Loop_1: Builds an array of size j and uses Loop_1B for every field of this array.
Loop_1B: Generate an int with r.nextInt(maxElem)+1; (it has to be +1 because nextInt() is covering the 0 inclusively and the specified value exclusively). Afterwards check if the number is already used in the array, if yes, run this loop again.
Loop_2: Repeats Loop_1 i times.
So, I generate a 100 numbers between the range of 0 and 9. I store these 100 numbers in an array called 'array'. Then I have the array called 'count'. It has 10 elements, and I wanted to check the following: for each element in 'array' if it equals to 0-9 then count[0-9] increments by 1, count[0] = how many times number 0 appears and so on count[1] = 1, count[2] = 2... . I just keep getting the output of around 20k numbers and i suppose? the sum of each element?, no idea why. I was wondering if there is something major wrong with my for loop?
import java.util.*;
class RandomInt {
public static void main(String[] args) {
int size = 100;
int max = 10;
int[] array = new int[size];
int[] count = new int[max]; //count[0,0,0,0,0,0,0,0,0,0]
int loop = 0;
Random generator = new Random();
for (int i = 0; i < size; i++) {
array[i] = generator.nextInt(max); // Generates 100 random numbers between 0 and 9 and stores them in array[]
System.out.print(array[i]);
for (int x = 0; x < size; x++) {// loop through 10 elements in count
for(int j = 0; j < 10; j++){ //loop through 100 elements in array
if (array[x] == j) {// loop through each 100 elements of array[x] and if element array[x] = value
count[j] += 1; // then count[x] = x + 1
System.out.print(count[j]);
}
}
}
}
System.out.println("0 appears " + count[0] + " times.");
}
}
Your Login is Perfect only mistake which i found u made is with the brackets........!
Generate the numbers using first loop and then count the number of occurrence using different for loop.
Here is your code's modified version which generates 10 numbers and counts the individual number occurrence count.....
public class RandomInt {
public static void main(String[] args) {
int size = 10;
int max = 10;
int[] array = new int[size];
int[] count = new int[max]; //count[0,0,0,0,0,0,0,0,0,0]
int loop = 0;
Random generator = new Random();
for (int i = 0; i < size; i++)
{
array[i] = generator.nextInt(max); // Generates 100 random numbers between 0 and 9 and stores them in array[]
System.out.print(array[i]+" ");
}
for (int x = 0; x < size; x++)
{// loop through 10 elements in count
for(int j = 0; j < 10; j++)
{ //loop through 100 elements in array
if (array[x] == j)
{// loop through each 100 elements of array[x] and if element array[x] = value
count[j] += 1; // then count[x] = x + 1
//System.out.print(count[j]);
}
}
}
System.out.println("3 appears " + count[3] + " times.");
}
}
There's a simpler way to do this without nested loops, so forgive me for suggesting this as a fix rather than finding the issue in the loop.
for(int i=0; i<size; i++){
int num = generator.nextInt(max);
array[i] = num;
count[num]++;
}
One loop, incrementing the count for each number as it appears. You may need to ensure all the entries in count start at 0, but even then an additional loop through 10 entries is MUCH faster.
To increment your counter, you don't need to have two nested for loops. Instead, you can use the value of array[x] as your counter.
for (int i = 0; i < size; i++) {
count[array[i]]++
}
You've nested your counting loop inside of your random number generating loop. Move the counting part outside.
Edit: The reason you're getting like 20k or whatever instances of zero is because when you set array[0] with a random value, you also check how many instances of 0 are in array[1] to array[99].
You probably shouldn't do your count until you have finished assigning your numbers, but here is how you could. Note that you want the value at array[i] to be your index to count.
for (int i = 0; i < size; i++) {
array[i] = generator.nextInt(max); // Generates random numbers
count[array[i]]++;
}
System.out.println(Arrays.toString(array));
System.out.println(Arrays.toString(count));
I am in a cs 2010 class. Haven't ever worked on coding before or anything of the sort. I have an okay teacher but he has a very thick accent that is hard to understand. He recently gave us a project to complete over a few days. I have been having problems getting the last part of the project done.
The project asks you to generate 10,000 random numbers between 0-9999 and arrange them in an array of 10,000 numbers without repeating any of them. As you can see, this is basically asking you to make the array put the numbers 0-9999 in an array in order of least to greatest. My problem is the non-repeating numbers. I have been working on the code for over 4 hours trying to figure out how to make it not repeat and have had no luck. I have searched online for at least an hour and all other hints or solutions have not helped. This is the code I have so far, can anyone please help me?
package array.sorter.project;
import java.util.Arrays;
import java.util.Random;
public class Sorting {
public static void main(String args[]){
int[] randomNumbers = new int[10000];
Random rand = new Random();{
for (int i = 1; i < randomNumbers.length; i++) {
int n = rand.nextInt(10000);
randomNumbers[i] = n;}
for (int i = 0; i < randomNumbers.length; i++) {
int smallestNo = randomNumbers[i];
int posWithSmallest = i;
for (int j = i+1; j < randomNumbers.length; j++) {
int val = randomNumbers[j];
if (val < smallestNo) {
smallestNo = val;
posWithSmallest = j;
}
}
int tmp = randomNumbers[i];
randomNumbers[i] = smallestNo;
randomNumbers[posWithSmallest] = tmp;
}
Arrays.sort(randomNumbers);
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Position " + i + " : " + randomNumbers[i]);
}
}
}
}
Instead of randomly generating 10000 numbers from 0 to 9999, generate 0...9999 in ascending order and shuffle the array. Make sure that your shuffling is unbiased, e.g. that there are n! ways it can complete (if you're not sure, desk check it with n = 3 to see if it is unbiased)
You can not generate 10000 random integers in range 0-9999 without duplicates, there are only 10000 of then, so you need all.
What you can do is to rearrange, shuffle them.
So:
import java.util.Collections;
import java.util.Arrays;
...
int[] ten_thousand = new int[10000];
for (int i=0; i < 10000; i+=1) ten_thousand[i] = i;
return Collections.shuffle(Arrays.asList(ten_thousand));
Know your weapons :)
If you do not want to use shuffle
private static int[] generateRandom(int count) {
int[] randomNumbers = new int[count];
Set<Integer> checker = new HashSet<Integer>();
Random rand = new Random();
for (int i = 0; i < count;) {
int nextInt = rand.nextInt(count);
if (!checker.contains(nextInt)) {
randomNumbers[i++] = nextInt;
checker.add(nextInt);
}
}
return randomNumbers;
}
I've written a O(n) algorithm to solve this problem inspired by the book Programming Pearls, 2nd Edition.the code is below,i will explain it later:
/**
* randomly select k numbers in [0,n),and sort them in random order.(k<=n)
*/
public static int[] getRandomArray(int n, int k) {
if (k > n) {
k = n;
}
int[] rets = new int[k]; // store the random ordered number
int[] array = new int[n];// original array that array[i] is i
for (int i = 0; i < n; i++)
array[i] = i;
Random random = new Random();
for (int j = 0; j < k; j++) {
// generate a random number between [j,n) as index
int index = j + random.nextInt(n - j);
// swap array[j] and array[index],so array[0..j] are all non-repeat
// random number
int temp = array[index];
array[index] = array[j];
array[j] = temp;
// store it in rets
rets[j] = temp;
}
return rets;
}
explain:
to generate non-repeating 10,000 random numbers between 0-9999
can be considered to arrange number 0-9999 in random order。
1,the k number are stored in array,within which x in position x.
2,for the number j,random select a index from [j,n),that's index,
3,swap the position of j from j to index,(e.q. to swap the number at index to position j)
4,loop j from 0 to k,