Filling two new arrays from existing array - java

I already have one Array with random numbers between 0-999.
I also have created two new arrays, one with correct the size to hold all numbers 0-499, and one with the correct size for numbers 500-999.
Problem is to then loop through the Array holding all numbers and copying the right numbers 0-499 and 500-999 to the new Arrays.
Anyone know the correct way to do this? Have spent many days now trying to figure this out.
What i got so far:
public static void main(String[] args) {
Scanner scannerObject = new Scanner(System.in);
Random generator = new Random();
System.out.print("How many numbers between 0 - 999?" );
int number= scannerObject.nextInt();
int [] total= new int[number];
for(int index = 0; index < total.length; index++ )
{
total[index] = generator.nextInt(1000);
}
System.out.println("Here are the random numbers:");
for(int index = 0; index < total.length; index++ )
{
System.out.print(total[index]+ " ");
}
int lowNumber=0;
int largeNumber = 0;
for(int index = 0; index < total.length; index++ )
{
if (total[index] < 500)
{
lowNumber++;
}
if (total[index] >= 500)
{
largeNumber++;
}
}
System.out.println();
System.out.println(lowNumber);
System.out.println(largeNumber);
int [] totalLownumber = new int [lowNumber];
int [] totalLargeNumber = new int [largeNumber];
for(int index = 0; index < total.length; index++ )
{ // TODO
}
}

2 of the approaches you can take are as follows:
You can go through the initial array, count the elements you have, and use the counter values to define the size of the arrays you need. You then go over the original array once again and copy the elements to their respective array. You can use the counter values once again (you would need to reset them first) to allow you to keep track in which array location will the current number need to go. This should be similar to what you are doing.
Consider using a variable length data structure such as a List (ArrayList in Java). This would allow you to go over your original array and assign the numbers to their respective list (let's call them largeNumberList and lowNumberList). Since these collections have a dynamic size, you would only need to traverse the array once and assign as you go along.
The latter approach is usually what is used more often, however, since it would seem that this question is related to homework, I would recommend you try both approaches and compare them.

Try this:
int lowIndex = 0;
int largeIndex = 0;
for(int index = 0; index < total.length; index++ ) {
if (total[index] < 500) {
totalLowNumber[lowIndex++] = total[index];
} else {
totalLargeNumber[largeIndex++] = total[index];
}

Related

Java: Print out each number in an array without printing its an repeats of that number?

Im trying to print out an array but only print out the distinct numbers in that array.
For example: if the array has {5,5,3,6,3,5,2,1}
then it would print {5,3,6,2,1}
each time i do it either i only print the non repeating numbers, in this example {6,2,1} or i print them all. then i didnt it the way the assignment suggested
the assignment wants me to check the array before i place a value into it to see if its there first. If not then add it but if so dont.
now i just keep getting out of bounds error or it just prints everything.
any ideas on what i should do
import java.util.Scanner;
public class DistinctNums {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value;
int count = 0;
int[] distinct = new int[6];
System.out.println("Enter Six Random Numbers: ");
for (int i = 0; i < 6; i++)
{
value = input.nextInt(); //places users input into a variable
for (int j = 0; i < distinct.length; j++) {
if (value != distinct[j]) //check to see if its in the array by making sure its not equal to anything in the array
{
distinct[count] = value; // if its not equal then place it in array
count++; // increase counter for the array
}
}
}
// Displays the number of distinct numbers and the
// distinct numbers separated by exactly one space
System.out.println("The number of distinct numbers is " + count);
System.out.print("The distinct numbers are");
for (int i = 0; i < distinct.length; i++)
{
System.out.println(distinct[i] + " ");
}
System.out.println("\n");
}
}
Always remember - if you want a single copy of elements then you need to use set.
Set is a collection of distinct objects.
In Java, you have something called HashSet. And if you want the order to be maintained then use LinkedHashSet.
int [] intputArray = {5,5,3,6,3,5,2,1};
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
//add all the elements into set
for(int number:intputArray) {
set.add(number);
}
for(int element:set) {
System.out.print(element+" ");
}
You can make this using help array with lenght of 10 if the order is not important.
int [] intputArray = {5,5,3,6,3,5,2,1};
int [] helpArray = new int[10];
for(int i = 0; i < intputArray.length ; i++){
helpArray[intputArray[i]]++;
}
for(int i = 0; i < helpArray.length ; i++){
if(helpArray[i] > 0){
System.out.print(i + " ");
}
}

Generate random numbers without duplicates using arrays only

I want to fill an array of size X with random integers from 0 to X with no duplicates. The catch is I must only use arrays to store the collections of int, no ArrayLists. How do I go about implementing this?
I don't understand why I can't seem to get this. But this is my most recent bit of code that fills the list but allows for duplicates.
System.out.print("Zero up to but excluding ");
int limit = scanner.nextInt();
// create index the size of the limit
int [] index = new int[limit];
for(int fill=0;fill<limit;fill+=1){
index[fill] = (limit);
}
int randomNumber = 0;
Random rand = new Random();
int [] randoms = new int[limit];
boolean flag = true;
// CODE TO NOT PRINT DOUBLES
for (int z=0;z<limit;z+=1){
randomNumber = rand.nextInt(limit);
int i=0;
while (i<limit){
if (index[i] == randomNumber){
flag = true;
}
else {
flag = false;
break;
}
i+=1;
}
if (flag == false){
randoms[z] = randomNumber;
index[z] = randomNumber;
}
}
System.out.println("Randoms: "+java.util.Arrays.toString(randoms));
Here's one way to do it:
Create an array of length N
Fill it from 0 to N-1
Run a for loop and swap randomly 2 indices
Code:
// Step 1
int N = 10;
int[] array = new int[N];
// Step 2
for(int i=0; i < N; i++)
array[i] = i;
// Step 3
for(int i=0; i < N; i++) {
int randIndex = (int) (Math.random() * N);
int tmp = array[i];
array[i] = array[randIndex];
array[randIndex] = tmp;
}
Why not rephrase the problem to shuffling an array of integers. First fill the array monotonically with the numbers 0 to X. Then use the Random() function to select one of the X numbers to exchange with the number in position 0. Repeat as many times as you may like. Done.
Here is your bug:
while (i<limit){
if (index[i] == randomNumber){
flag = true;
}
else {flag = false;break;} <--- rest of the array is skipped
i+=1;
}
after you generated a new number, you start to check for equality , however once you find that randomNumber!=index[i] (else statement) you break out of the while. look this: actual array is 3,4,5,1 your new number is 5, you compare it to 3 just to find out that they different so flag is set to false and break out happens.
Consider using another array filled with elements in order from 0 to X. Then, with this array, shuffle the elements around. How do you go about this? Use a loop to traverse through every single element of the array, and for each iteration, choose a random number from 0 to array.length - 1 and switch the elements at the index you're currently on and the random index. This is how it would look like,
In your main, you would have an array initialized by doing this,
int[] arr = new int[10];//10 can be interchangeable with any other number
for(int i = 0; i < arr.length; i++){
arr[i] = i;
}
shuffleArray(arr);
And the shuffle method would look like this,
public int[] shuffleArray(int[] arr){
Random rand = new Random();
for(int i = 0; i < arr.length; i++){
int r = rand.nextInt(arr.length);//generate a random number from 0 to X
int k = arr[i];
arr[i] = arr[r];
arr[r] = k;
}
}

Count characters in a multidimensional array, Java

Below is my code:
public int maxTurns = 0;
public String[][] bombBoard = new String[9][9];
...
public void loadBombs()
{
//loadArray();
Random randomGen = new Random();
for (int u=1; u<=9; u++)
{
int randomRow = randomGen.nextInt(9);
int randomCol= randomGen.nextInt(9);
bombBoard[randomRow][randomCol] = "#";
}
//counting #'s -- setting variable
for (int d = 0; d < bombBoard[bombRow].length; d++)
{
for (int e = 0; e < bombBoard[bombCol].length; e++)
{
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
{
maxTurns++;
}
}
}
All I want to do is count the amount of (#)'s in the multidimensional array and assign it to a variable called maxTurns.
Probably very simple, just having a super hard time with it tonight. Too much time away from Java >.<
This line is equating the character # with the entire dth row or eth row. Does not make sense really because an array row cannot equal to a single character.
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
Instead, access a single cell like this
if (bombBoard[d][e].equals("#"))
And initialize maxTurns before counting i.e. before your for loop:
maxTurns = 0;
You need to change the if codition
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
to
if (bombBoard[d][e].equals("#"))
You are using 2D Array, and do array[i][j] can populate its value for a gavin position.
do you want to count from the whole array or certain parts of the array only?
From the code snippet you gave above, I can't really tell how you iterate the array since I'm not sure what is
bombBoard[bombRow].length and bombBoard[bombCol].length
But if you want to iterate the whole array, think you should just use:
for (int d = 0; d < 9; d++) // as you declared earlier, the size of array is 9
{
for (int e = 0; e < 9; e++) // as you declared earlier, the size of array is 9
{
if (bombBoard[d][e].equals("#"))
{
maxTurns++;
}
}
}

ArrayIndexOutOfBoundsException when looping

I'm pretty much a noob to programming but i have researched all over the place and cant find an answer. im using eclipse and every time i run my program it says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at computer.guess(game1player2.java:24)
at game1player2.main(game1player2.java:39)
Here's my code:
import java.util.Scanner;
class computer{
int g = 0;
int[] compguess = new int[g];
void guess(){
int rand;
while(0 < 1){
int i;
rand = (int) Math.ceil(Math.random()*10);
for (i = 1; i < compguess.length; i++){
if(rand == compguess[i]){
break;
}
}
if(i > compguess.length){
g++;
rand = compguess[g];
System.out.println(compguess[compguess.length]);
}
}
}
}
public class game1player2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
computer computer1 = new computer();
for(int a = 0; a < 2; a++){
computer1.guess();
for(int n = 0; n <= computer1.compguess.length; n++)
System.out.println(computer1.compguess[n]);
}
{
input.close();
}
}
}
i am now really confused, i am trying to make a computer generate a random number 1-10, but if it is already in the array generates another one.
int g = 0;
int[] compguess = new int[g];
Your array is size 0, so you have no valid entries.
Since you initialized g as zero, your array compguess has a length of zero. Next when you enter your for loop you assign 1 to i which will allow you to enter into the if condition at the end of guess which will try to access element compguess[1] but this cannot exist because the array is of size zero.
You will run into problems if you do not correct the following.
Change: for(int n = 0; n <= computer1.compguess.length; n++)
To: for(int n = 0; n < computer1.compguess.length; n++)
If your array length is 8 then the last item in the array will be index 7, but the <= tells the loop to grab item index 8.
Your compguess has a length of 0, and you are starting your for loop with i = 1, wich is already greater than 0.
compguess is a zero-length array. If you try to index it, you will fall out of the array and hence the ArrayIndexOutOfBoundsException
If your intent is to make the array longer and add a new item to the end of it, you can't do that. I'm guessing that this is what you were trying to do here:
rand = compguess[g];
First of all, if the language did allow it, you'd want to write it the other way:
compguess[g] = rand;
because you're trying to put a value into a new element of the array, not read from the array. This would actually work in some languages (JavaScript, Perl, others). In Java, however, when you create an array object with something like new int[], the size is fixed. You can't make it longer or shorter.
You probably want to use an ArrayList, which does let you create an array that you can make longer. See this tutorial.

Where does this program get its numbers from, and why is this caused by increasing 1 array size? (Java)

This program simply is supposed to eliminate duplicates from an array. However, the second for loop in the eliminate method was throwing an out of bounds exception. I was looking and couldnt see how that could be, so I figured I would increase the array size by 1 so that I would get it to work with the only downside being an extra 0 tacked onto the end.
To my surprise, when I increased tracker[]'s size from 10 to 11, the program prints out every number from 0 to 9 even if I dont imput most of those numbers. Where do those numbers come from, and why am I having this problem?
import java.util.*;
class nodupes
{
public static void main(String[] args)
{
int[] dataset = new int[10];
//getting the numbers
for (int i = 0; i <= 9 ; i++)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a one digit number");
dataset[i] = input.nextInt();
}
int[] answer = (eliminateduplicates(dataset));
System.out.println(Arrays.toString(answer));
}
public static int[] eliminateduplicates(int[] numbers)
{
boolean[] tracker = new boolean[11];
int arraysize = 1;
for(int k = 0; k <= 9; k++)
{
if(tracker[numbers[k]] == false)
{
arraysize++;
tracker[numbers[k]] = true;
}
}
int[] singles = new int[arraysize];
for(int l = 0; l <= arraysize; l++)
{
if(tracker[l] == true)
{
singles[l] = l;
}
}
return singles;
}
}
The exception was occuring at this part
if(tracker[l] == true)
but only when trackers size was 10. At 11 it just prints [0,1,2,3,4,5,6,7,8,9]
EDIT: The arraysize = 1 was a hold over from debugging, originally it was at 0
EDIT: Fixed it up, but now there is a 0 at the end, even though the array should be getting completely filled.
public static int[] eliminateduplicates(int[] numbers)
{
boolean[] tracker = new boolean[10];
int arraysize = 0;
for(int k = 0; k < numbers.length; k++)
{
if(tracker[numbers[k]] == false)
{
arraysize++;
tracker[numbers[k]] = true;
}
}
int[] singles = new int[arraysize];
int counter = 0;
for(int l = 0; l < arraysize; l++)
{
if(tracker[l] == true)
{
singles[counter] = l;
counter++;
}
}
return singles;
}
Since arrays start at 0, your arraysize will be one larger than the number of unique numbers, so your final loop goes through one too many times. In other words "l" (letter l -- try using a different variable name) will get to 11 if you have 10 unique numbers and tracker only has item 0-10, thus an out of bounds exception. Try changing the declaration to
int arraysize = 0;
Once again defeated by <=
for(int l = 0; l <= arraysize; l++)
An array size of 10 means 0-9, this loop will go 0-10
For where the numbers are coming from,
singles[l] = l;
is assigning the count values into singles fields, so singles[1] is assigned 1, etc.
Edit like 20 because I should really be asleep. Realizing I probably just did your homework for you so I removed the code.
arraySize should start at 0, because you start with no numbers and begin to add to this size as you find duplicates. Assuming there was only 1 number repeated ten times, you would've created an array of size 2 to store 1 number. int arraysize = 0;
Your first for loop should loop through numbers, so it makes sense to use the length of numbers in the loop constraint. for( int i = 0; i < numbers.length; i ++)
For the second for loop: you need to traverse the entire tracker array, so might as well use the length for that (tracker.length). Fewer magic numbers is always a good thing. You also need another variables to keep track of your place in the singles array. If numbers was an array of 10 9s, then only tracker[9] would be true, but this should be placed in singles[0]. Again, bad job from me of explaining but it's hard without diagrams.
Derp derp, I feel like being nice/going to bed, so voila, the code I used (it worked the one time I tried to test it):
public static int[] eliminateduplicates(int[] numbers)
{
boolean[] tracker = new boolean[10];
int arraysize = 0;
for(int k = 0; k < numbers.length; k++)
{
if(tracker[numbers[k]] == false)
{
arraysize++;
tracker[numbers[k]] = true;
}
}
int[] singles = new int[arraysize];
for(int l = 0, count = 0; l < tracker.length; l++)
{
if(tracker[l] == true)
{
singles[count++] = l;
}
}
return singles;
}
I feel you are doing too much of processing for getting a no duplicate, if you dont have the restriction of not using Collections then you can try this
public class NoDupes {
public static void main(String[] args) {
Integer[] dataset = new Integer[10];
for (int i = 0; i < 10; i++) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a one digit number");
dataset[i] = input.nextInt();
}
Integer[] arr = eliminateduplicates(dataset);
for (Integer integer : arr) {
System.out.println(integer);
}
}
public static Integer[] eliminateduplicates(Integer[] numbers) {
return new HashSet<Integer>(Arrays.asList(numbers)).toArray(new Integer[]{});
}
}
To answer your question your final loop is going one index more than the size.
The range of valid indexes in an array in Java is [0, SIZE), ie. from 0 up to arraysize-1.
The reason you're getting the exception is because in your loop you're iterating from 0 to arraysize inclusively, 1 index too far:
for(int l = 0; l <= arraysize; l++)
Therefore when you get to if(tracker[l] == true) in the last iteration, l will equal arraysize and tracker[l] will be outside the bounds of the array. You can easily fix this by changing <= to < in your for loop condition.
The reason that the problem goes away when the size of your array is changed from 10 to 11 has to do with arraysize being incremented up to 10 in the for loop above the one causing the problems. This time, singles[10] is a valid element in the array since the range of indexes in your array is now [0, 11).
EDIT: Actually arraysize has the potential to be incremented to 11, I thought it was initialised to 0 in which case it would only get to 10. Either way the above is still valid; the last index you try and access in your array must be 1 less than the length of your array in order to avoid the exception you're getting, since arrays are zero-based. So yeah, long story short, <= should be <.

Categories