Populate an array within a specific range - java

I wanna populate an array with integers within 2000-3000.
public static void main(String[] args) {
int[] nums = new int[1000];
for (int y = 0; y < nums.length; y++) {
for (int i = 2000; i < 3000; i++) {
nums[y] = i;
}
}
System.out.println(Arrays.toString(nums));
}
I got an array with full of 2999.
What's the problem? Thank you in advance!

you're populating the same cell again and again. Your array size is 1000, but your range is 1001: 3000 - 2000 + 1 = 1001
public static void main(String[] args) {
int[] nums = new int[1001];
for(int y=0;y<nums.length;y++) {
nums[y]= y + 2000;
}
System.out.println(Arrays.toString(nums));
}

What about Java 8 solution?
IntStream.range(2000, 3001).toArray(); // [2000, 2001, ... 3000]

You dont need nested loop to do that just do
int[] nums = new int[1000];
for(int i=2000; i<3000; i++) {
nums[i-2000]=i;
}
System.out.println(Arrays.toString(nums));
you get 2999 because your loop ends i<3000 , just change it to i<=3000 and also increase the array length to
int[] nums = new int[1001];
DEMO

It helps if you can translate your code into human language.
Breaking down your code, you have two loops. One is:
int[] nums = new int[1000];
for (int y = 0; y < nums.length; y++) {
// Stuff
}
}
Your idea in the first loop is to iterate through the whole length of the array.
"For each index in the array..."
Then, you have another loop inside the array iterator:
for (int i = 2000; i < 3000; i++) {
nums[y] = i;
}
Here, you are trying to put a number from 2000 to 2999 into index y of the array.
"In index y of the array, put values 2000 to 2999."
The previous values are overwritten for every value you put. This ultimately ends up as:
"Put 2999 in index y of the array."
Putting them together:
"For each index y in the array, put 2999."
Check TDG's answer for the proper way of writing the code.

Another way with 1 loop.As mentioned by #silentprogrammer , you need to increase array size by 1.
public static void main(String[] args) {
int var=2000;
int[] nums = new int[1001];
for (int y = 0; y < nums.length; y++) {
nums[y]=var++;
}
System.out.println(Arrays.toString(nums));
}

Related

Read 10 digits in a Java array and print them out in reverse

I have some problems with an exercise I can do to learn coding with arrays.
It's basically my questions title. It's supposed to give me 9,8,7,6,...,0 but it just prints out 0,0,0,0,0,...
Can anyone see what I do wrong here?
public static void main(String[] args) {
// TODO code application logic here
int intArray[] = new int[9];
for (int i = intArray.length -1; i>=0; i--);{
System.out.println(java.util.Arrays.toString(intArray));
}
}
You create array with lenght 9, but you don't set any values in it, so integer instantiated with zeros by default.
You want this:
int intArray[] = new int[]{1,2,3,4,5,6,7,8,9};
and cycle is wrong as well, reverse print should be like this:
int intArray[] = new int[]{1,2,3,4,5,6,7,8,9};
for (int i = intArray.length -1; i>=0; i--){
System.out.println(intArray[i]);
}
What you did - printed whole array. In my example I print i element of array on every iteration.
And there were extra semicolon after for(...)
UPDATE: there are another ways to get array filled with 10 digits. One more option is another for cycle:
int intArray[] = new int[10];
for (int i = 0; i < intArray.length; i++) {
intArray[i] = i;
}
for (int i = intArray.length -1; i>=0; i--){
System.out.println(intArray[i]);
}
Brings the same result, and can be more handy if you have really big array
Your code have two error .
You need to set the value of array
Remove the semicolon immediately from for loop ,so your loop run the statement.
Run below code
public static void main(String[] args) {
//need to initalized your array
int intArray[] = new int[]{1,2,3,4,5,6,7,8,9};
for (int i = intArray.length -1; i>=0; i--){
System.out.println(intArray[i]);
}
}

Check an integer variable against integers already stored in an array

Disclaimer: Still very new to code and have only basic skills with java. Trying to learn as much as i can on my own and from others. Not currently studying at uni.
Hello everyone.
I am trying to create an array with a small capacity (5 integers) to store a randomly generated integer in each array element. The randomly generated integer is in a set range (0-75) which ive no issue with.
What i cant figure out how to do is how to Generate a new integer, then check it against the current existing integers in each array element, before storing it and moving on to the next.
What i tried was this:
public class ItemSet
{
public static void main(String []args)
{
int[] itemSet;
itemSet = new int[5];
itemSet[0] = 0; /* to initialise the array elements. Im not sure if i actually have to do this or not */
itemSet[1] = 0;
itemSet[2] = 0;
itemSet[3] = 0;
itemSet[4] = 0;
int count = 1;
int assignItem = 0;
int countTwo = 1;
while (count > 5) {
while (countTwo == 1) {
assignItem = (int)(Math.random()*76);
// here is where i get totally lost
if (assignItem.compareTo(itemSet)) {
countTwo = 1;
} else {
itemSet[(count--)] = assignItem;
countTwo = 0;
}
}
count = count++;
}
}
}
Ive been looking at this so long my head is starting to hurt. I'd appreciate any advice you can give me. :) Thank you in advance. xx
Edit: Couldnt find the solution i needed in any of the "how can i test if an array contains a certain value" type questions, because i need to be able to have the number randomise again before it stores itself in the array element if it does happen to be the same as another previously generated integer.
You are doing too much to just fill an array. To fill an array, try using a "for" loop like so:
public class ItemSet {
public static void main(String []args) {
int[] itemSet;
itemSet = new int[5];
int count = 1;
int assignItem = 0;
int countTwo = 1;
for (int i = 0; i < itemSet.length; i++) {
itemSet[i] = (int) (Math.random() * 76);
}
}
}
To print the values stored in the array, try using an enhanced-for loop:
for (int element : itemSet) {
System.out.println(element);
}
To check the values BEFORE storing the next integer, (say to see ensure that the new stored value would be unique) you could use a nested for loop that starts at the value beneath the outer loop and walks backwards, comparing each value that came before to the value that was just stored, and if they are the same, it will decrement the outer counter which will then override the data on the next loop:
import java.util.Arrays; // you need this to use Arrays.toString()
public class ItemSet {
public static void main(String []args) {
int[] itemSet;
itemSet = new int[5];
int count = 1;
int assignItem = 0;
int countTwo = 1;
for (int i = 0; i < itemSet.length; i++) {
itemSet[i] = (int) (Math.random() * 76);
for (int j = i - 1; j >= 0; j--) {
if (itemSet[j] == itemSet[i]) {
System.out.println("Comparing " + itemSet[j] +
" and " + itemSet[i]);
i--;
break; // not really needed but illustrates a way to exit a loop immediately
}
}
}
// this is a handy way to print all the data in an array quickly
System.out.println(Arrays.toString(itemSet));
}
}
public static void main (String[] args){
//you dont need to initialize the array with zeros
int[] itemSet = new int[5];
int counter = 0;
while(counter < itemSet.length){
int random = (int)(Math.random() * 76);
//checks if the array already contains the random number
if(!Arrays.asList(itemSet).contains(random)){
itemSet[counter] = random;
counter++;
}
}
//print the array
for(int i : itemSet) System.out.println(i);
}
There are many ways you could solve this problem, I would suggest using a helping method that looks for duplicates in your array. This would be a working example:
public static void main(String[] args) {
int[] itemSet;
itemSet = new int[5];
int assignItem;
for (int i = 0; i < 5; i++) {
assignItem = (int)(Math.random()*76);
if(!duplicate(assignItem,itemSet,i)){
itemSet[i] = assignItem;
}
}
}
private static boolean duplicate(int assignItem, int[] itemSet, int i) {
for (int j = 0; j < i; j++) {
if (assignItem == itemSet[j])
return true;
}
return false;
}
The most straight forward way would be checking through the array for existing value before inserting the current random value.
Generate a random value
Check if value exists in array
If already exist in array, generate another value
If not exist in array, set value to current element
In codes:
public static void main(String[] args){
int idx = 0;
int[] myArray = new int[5];
Random rnd = new Random();
int val = rnd.nextInt(76);
do{
if(numExistInArray(val, myArray))
val = rnd.nextInt(76); //if val exist in array, generate another number
else
myArray[idx++] = val; //if val not exist in array, fill array
}while(idx != myArray.length); //do not exit loop till all numbers are filled
}
public static boolean numExistInArray(int val, int[] array){
for(int x=0; x<array.length; x++)
if(array[x] == val)
return true;
return false;
}
I had a hard time understanding what youre asking for but ill give it a go anyway hoping this is what you want:
for (int count = 0; count < 5 ; count++) {
assignItem = (int)(Math.random()*76);
if (assignItem==itemSet[count]&&itemSet[count]!=0) {
//If true do this
}
else {
itemSet[count] = assignItem;
}
}
Checking if the generated number is equal to a position and if the position is empty (0) if its not equal (a new number) then it will assign value to your array.
If you know your set range (which is 0-75) and space isn't an issue, I would suggest maintaining a pool of unused integers. This would guarantee each value is unique, and would avoid iterating over your array of integers to check for duplicates:
public static void main(String[] args) {
List<Integer> unusedNumbers = new ArrayList();
// Populate list with values
for (int i = 0; i <= 75; i++) unusedNumbers.add(i);
int[] itemSet = new int[5];
for (int i = 0; i < 5; i++) {
int randomIndex = (int) (Math.random() * unusedNumbers.size());
int randomInt = unusedNumbers.remove(randomIndex);
itemSet[i] = randomInt;
}
}

Java sorting program, getting a confusing output

public static void main(String[] args) throws Exception {
// declarations
int i, z, x, greatest;
int[] array = { 2, 3, 4, 55, 6 };
int[] copyarray = { 0, 0, 0, 0, 0 };
int zz;
greatest = array[0];
for (zz = 0; zz < 5; zz++) {
for (x = 0; x < 5; x++) {
if (array[x] > greatest) {
greatest = array[x];
}
}
copyarray[zz] = greatest; // this will contain the sorted array
// part of the nested loop
for (z = 0; z < 5; z++) {
if (greatest == array[z]) {
array[z] = 0;
}
}
}
// not part of the nested loop
for (i = 0; i < 5; i++) {
System.out.println("sorted array: " + copyarray);
}
}
Output:
sorted array: [I#1a16869
sorted array: [I#1a16869
sorted array: [I#1a16869
sorted array: [I#1a16869
sorted array: [I#1a16869
This is just a basic little program and I'm trying to get the logic right. I can't improve it or make it into a class or method because I'm not even getting the output right.
If you are trying to use your own algorithm, i would suggest you try using IDE and debug the code.
If you want to use algorithm that JDK provides, you could use:
Arrays.sort(array);
Regarding the output, you are trying to print array and array is an object without toString implementation in java. Hence you should change your print statement to :
System.out.println("sorted array: "+Arrays.toString(copyarray));//without surrounding for loop to get what its after each step of sorting elements.
Or if you want to keep your for loop then you could use index based access to array like:
System.out.print(copyarray[i] + " ");
Actually, none of the answers here are right.
The heart of the problem is that you are not re-initializing the variable greatest for each iteration. It is set to array[0]; in the beginning and it is never changed again. This should go inside the loop.
public static void main(String[] args) throws Exception {
// declarations
int i, z, x, greatest;
int[] array = { 2, 3, 4, 55, 6 };
int[] copyarray = { 0, 0, 0, 0, 0 };
int zz;
// greatest = array[0]; <---- Don't do it here
for (zz = 0; zz < 5; zz++) {
greatest = array[0]; // <--- Initialize greatest here and not before the loop
for (x = 0; x < 5; x++) {
if (array[x] > greatest) {
greatest = array[x];
}
}
copyarray[zz] = greatest; // this will contain the sorted array
// part of the nested loop
for (z = 0; z < 5; z++) {
if (greatest == array[z]) {
array[z] = 0;
}
}
}
// not part of the nested loop
for (i = 0; i < 5; i++) {
System.out.println("sorted array: " + copyarray[i]);
}
}
As a side note, you are printing the array incorrectly, you should use copyarray[i] and not copyarray.
Whit these two changes, here's the output:
sorted array: 55
sorted array: 6
sorted array: 4
sorted array: 3
sorted array: 2
You are printing the reference not the value
use:
for(int i = 0; i < copyarray.length; i++ ) {
System.out.println("Value : " + copyarray[i]);
}
i would also recommend using Arrays.sort(array);
just write
private int[] values = { 9,2,5,3,1,7,0 };
public void printSorted() {
Arrays.sort(values);
for(int i = 0; i < values.length; i++) {
System.out.println("Value: " + values[i]);
}
}

Set value for all values in an array

So basically I have an Array and I want to use the same IF-statement for all values without having to copy-paste the IF-statement so many times. E.g.
if(NewArray[] < 10){
NewArray[] = NewArray + 1;
}
Is this in any way possible?
Thanks in advance.
You have to use a for loop. This code will solve your problem.
public static void main(String[] args) {
int newArray[] = new int[10];
for(int i = 0; i < newArray.length ; i ++){
newArray[i] = i;
}
/* DISPLAY YOUR ARRAY */
for(int integer : newArray){
System.out.println(integer);
}
}

array with non repeating numbers from a range in ascending order, java

Im trying to generate an array with 1000 integers of non-repeating numbers in ascending order from 0 to 10,000
So far what I have is:
public static void InitArray(int[] arr) { // InitArray method
int i, a_num; // int declared
Random my_rand_obj = new Random(); // random numbers
for (i = 0; i <= arr.length-1; i++) // for loop
{
a_num = my_rand_obj.nextInt(10000); // acquiring random numbers from 0 - 10000
arr[i] = a_num; // numbers being put into array (previoulsy declared of size 1000)
}
}
public static void ShowArray(int[] arr) { // ShowArray method
int i; // int declared
for (i = 0; i <= arr.length-1; i++) { // for loop
System.out.print(arr[i] + " "); // show current array content
}
System.out.println(); // empty line
}
public static void Sort(int[] arr) { // SortArray method
int i, min, j; // int decalred
for (i = 0; i < arr.length-1; i++) { // for loop
min = i; // min is i
for (j = i + 1; j < arr.length; j++) { // nested for loop
if (arr[j] < arr[min]) { // if statement
min = j; // j is the new minimum
}
}
int swap = arr[min]; // swap "method"
arr[min] = arr[i];
arr[i] = swap;
}
}
Is there any way to check the numbers are not repeating? Is there a function besides the random generator that will let me generate numbers without repeating? Thanks for any help
You can declare array of size 10,000
and init the array in away that each cell in the array will holds the value of it's index:
int [] arr= new int[10000];
for (int i=0 i < arr.length; i++){
arr[i] = i
}
Now you can shuffle the array using java Collections.
and take the first 1000 items from the array and sort then using java sort.
This will do I believe..
HashSet hs = new HashSet();
for(int i=0;i< arr.length;i++)
hs.add(arr[i]);
List<Integer> integers=new ArrayList<>(hs);
Collections.sort(integers);
A very simple solution is to generate the numbers cleverly. I have a solution. Though it may not have an even distribution, it's as simple as it can get. So, here goes:
public static int[] randomSortedArray (int minLimit, int maxLimit, int size) {
int range = (maxLimit - minLimit) / size;
int[] array = new int[size];
Random rand = new Random();
for (int i = 0; i < array.length; i++ ) {
array[i] = minLimit + rand.nextInt(range) + range * i;
}
return array;
}
So, in your case, call the method as:
int randomSortedArray = randomSortedArray(0, 10_000, 1_000);
It's very simple and doesn't require any sorting algorithm. It simply runs a single loop which makes it run in linear time (i.e. it is of time complexity = O(1)).
As a result, you get a randomly generated, "pre-sorted" int[] (int array) in unbelievable time!
Post a comment if you need an explanation of the algorithm (though it's fairly simple).

Categories

Resources