Random Char in 2D arrays - java

Hi i am new at java coding and am trying to create random numbers(which i have done) and i am trying to assign this random numbers as coordinates into the 2D array and print 'A' at the coordinates. Any help is appreciated.
package training;
import java.util.Random;
public class Training {
public static void main(String[] args) {
char[][] values = new char[10][10];
int foodX[] = new int[15];
for (int i = 1; i < foodX.length + 1; i++) {
int minFood = 0;
int maxFood = 10;
int randNum1 = minFood + (int) (Math.random() * (maxFood - minFood) + 1);
int minFoodY = 0;
int maxFoodY = 10;
int randNum2 = minFoodY + (int) (Math.random() * (maxFoodY - minFoodY) + 1);
for (int j = 1; j < foodX.length + 1; j++) {
values[randNum1][randNum2] = 'A';
}
}
// Assign three elements within it.
// Loop over top-level arrays.
for (int i = 0; i < values.length; i++) {
// Loop and display sub-arrays.
char[] sub = values[i];
for (int x = 0; x < sub.length; x++) {
System.out.print(sub[x] + " ");
}
System.out.println();
}
}
}

Arrays in Java are zero-indexed. What this means is that if you declare an array myArray as follows:
final int[] myArray = new int[10];
then you are creating a 10-element array which contains values in myArray[0], myArray[1], ..., myArray[9]. This also holds true for two-dimensional arrays, such as the values array in your code. However, you have defined randNum1 and randNum2 to return values in the range 1 to 10. When either of those values is set to 10, then values[randNum1][randNum2] will throw an ArrayIndexOutOfBoundsException, because you are trying to reference the array using indices that are out of its range.
In addition to this, you have created an array, foodX, which you do nothing with beyond determining its length. It's better in this case to declare an constant int value for this purpose. Finally, although you have imported the java.util.Random class, you are using Math.random() to generate random variables, which doesn't rely on this. You could alternatively use Random.nextDouble(), which would be useful if using a random number seed, but that's an aside.
Without following any additional considerations and to get your output simply to work as I believe is intended, I would therefore re-write your class in the following way:
package training;
public class Training {
public static void main(String[] args) {
char[][] values = new char[10][10];
int foodSize = 15
for (int i = 1; i <= foodSize; i++) {
int minFood = 0;
int maxFood = 10;
int randNum1 = minFood + (int) (Math.random() * (maxFood - minFood));
int minFoodY = 0;
int maxFoodY = 10;
int randNum2 = minFoodY + (int) (Math.random() * (maxFoodY - minFoodY));
values[randNum1][randNum2] = 'A';
// I've removed the for loop in the line above since it simply does the same thing 15 times and is inefficient
}
// Assign three elements within it.
// Loop over top-level arrays.
for (int i = 0; i < values.length; i++) {
// Loop and display sub-arrays.
char[] sub = values[i];
for (int x = 0; x < sub.length; x++) {
System.out.print(sub[x] + " ");
}
System.out.println();
}
}
}

Related

Sum of digits in random generated arrays

I know this may stand for a silly question but I have got a lot of problems with this.
I will first explain how it should work :
1)Generate random Array with size in range <4,7>
2)Fill it with random elements in range <100, 999>
3)Print the index of three numbers with biggest digit sum
So the question is-how? I know I should implement this:
SumOfDigits += ElementFromArray % 10;
ElementFromArray /= 10;
But i have got no idea where. I tried to add this as a if (i>0) loop inside for loop-but its not working.
Also how at the end im going to print the proper elements? Should I use Arrays.sort(tab) and then System.out.println(tab[tab.length - 1]) (and so on with -2, -3 for 3 last elements)?
import java.util.Arrays;
import java.util.Random;
public class Ex1 {
public static void main(String[] args) {
Random rand = new Random();
int size = rand.nextInt(4) + 4;
int tab[] = new int[size];
for (int i = 0; i < tab.length; i++) {
int elements = rand.nextInt(900) + 100;
tab[i] = elements;
}
System.out.println(Arrays.toString(tab));
}
}
If we aim for a solution using only arrays I would use a 2d array to hold the sum of digits and the index of the corresponding number in the tab array
So first create the array based on the size of the original array
int[][] sums = new int[size][2];
then in the for loop, calculate the sum of the random number and store it and the index
sums[i][0] = elements / 100 + (elements / 10) % 10 + elements % 10;
sums[i][1] = i;
Then sort the sums array using a custom comparator
Arrays.sort(sums, new Comparator<int[]>() {
#Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[0], o1[0]);
}
});
And finally print the index and number of the numbers of the top 3
for (int i = 0; i < 3; i++) {
System.out.printf("%d: %d\n", sums[i][1], tab[sums[i][1]]);
}
Just use while loop: here is a quick and dirty solution:
private static void main10(String[] args) {
Random rand = new Random();
int size = rand.nextInt(4) + 4;
int[] tab = new int[size];
for (int i = 0; i < tab.length; i++) {
int element = rand.nextInt(900) + 100;
tab[i] = element;
}
System.out.println(Arrays.toString(tab));
// calculate digits:
int[] digitsums = new int[size];
for (int i = 0; i < tab.length; i++) {
int element = tab[i];
int sumOfDigits = 0;
while (element > 0) {
sumOfDigits += element % 10;
element /= 10;
}
digitsums[i] = sumOfDigits;
}
System.out.println(Arrays.toString(digitsums));
int[] copyOfdigitsums = Arrays.copyOf(digitsums, digitsums.length);
for (int i = 1; i <= 3; i++) {
int j = getIndexOfLargest(copyOfdigitsums);
System.out.println("index of " + i + "largest is " + j + ", with a digitsum of " + copyOfdigitsums[j]);
copyOfdigitsums[j] = 0;
}
}
static int getIndexOfLargest(int[] digitsums) {
int largest = 0;
int index = 0;
for (int i = 0; i < digitsums.length; i++) {
int d = digitsums[i];
if (largest < d) {
largest = d;
index = i;
}
}
return index;
}

Printing 2d array in app gives blank screen

i made 2d array that contains names and task.
the function give random task to the users.
when i try to print the array that contain the users and the random tasks i get a blank screen.
public String[][] start() {
int[] taken = new int[this.numberOfRowsT()];
String[][] h = new String[numberOfRowsN()][(numberOfRowsT()) / (numberOfRowsN()) + 1];
int a = 1;
int x;
for(int b = 0; b < this.numberOfRowsN(); b++){
h[b][0] = this.getUsersByID(b+1).toString();
}
while (a != this.numberOfRowsT()) {
x = (int) Math.random() * ((this.numberOfRowsT()) + 1);
for (int j = 0; j < taken.length; j++) {
if (x == taken[j]) {
j = -1;
x = (int) Math.random() * ((this.numberOfRowsT()) + 1);
}
}
taken[a] = x; // acceptable num from here
h[((a % this.numberOfRowsN()) + 1)][this.numberOfRowsN() % a] = this.getTaskByID(x).toString();
a++;
}
return h;
}
public void onClick(View v) {
String[][] h = mydb.start();
for (int i = 0; i < mydb.numberOfRowsN(); i++) {
for (int j = 0; j < mydb.numberOfRowsT() /
mydb.numberOfRowsN(); j++)
if (h[i][j] != null)
l.append(h[i][j]);
l.append("\n"); // Append newline after every row
}
}
});
}
Here:
String[][] h = mydb.start();
I guess you want to use that 2D array to collect all the strings to print.
Thing is: you only declare and fill that array.
But it is a local variable, and it goes out of scope as soon as onClick() has run.
Thus: if you want to print things, then you need to do something with the data you collected. Either put into some UI element, or at least log it, or send to System.out.printn() (that of course only works when you have a console, and isn't a viable thing for an Android app).

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;
}
}

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).

Adding and removing elements in an array: An exercise

I am looking to fill an array a with the numbers 1 through 10 and take a random number from that array and add it to an array b and remove that element from array a. I would like to know the most efficient way of doing this. EDIT: (The exercise requires that I not have repeated values in the arrays and that the permutation is random each time the method is called.) Here is my method so far:
public int[] nextPermutation() {
int capOne = 10;
int capTwo = 10;
int aSize = 0;
int bSize = 0;
int[] a = new int[capOne];
int[] b = new int[capTwo];
int upperBound = 11;
Random generator = new Random();
//fill initial array with 1 - 10
for (int i = aSize; i < 10; i++) {
a[i] = i + 1;
//companion variable for sizing array
aSize++;
}
//Create a random integer and add it to array b
//Remove same integer from array a
//Repeat and remove another random integer from the remaining integers in array a and add it to b
permuted = b;
return permuted;
}
I may be approaching this in an inefficient if not completely incorrect manner. If so, I'm sure you won't hesitate to tell me. Any help on this is greatly appreciated.
You can:
//randomly choose element
int index = (int) (Math.random() * aSize);
int dataFromA = a[index];
//"remove" it from A
aSize--;
for(int i = index; i<aSize; i++) {
a[i] = a[i+1];
}
//"add" it to b
b[bSize] = dataFromA;
bSize++;
Only interesting part is removing from A, where you have to reduce the size before the cycle (or you can i < aSize-1, then decrement size)
I guess you have to use arrays since this is an excersice, but using List for this would be better.
Here is a program producing random permutations, using swap. Well, I'm not sure which can produce a better result, but swap should be faster than add/remove to/from an array:
public int[] nextPermutation() {
int cap = 10;
int[] a = new int[cap];
Random generator = new Random();
//fill initial array with 1 - 10
for (int i = 0; i < cap; i++) {
a[i] = i + 1;
}
for (int i = 0; i < cap; i++) {
int j = generator.nextInt(cap);
int x = a[j];
a[j] = a[i];
a[i] = x;
}
// You can reduce the size of the output array:
// int output[] = new int[5];
// System.arraycopy(a, 0, output, 0, 5);
// return output;
return a;
}

Categories

Resources