Printing 2d array in app gives blank screen - java

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

Related

Ordering a vector of randomly generated numbers

I´m trying to solve a question but i can´t find why my code is not working for this problem. I have generated a random vector of 100 elements and im trying to order them into another. Somehow, my new generated vector is filled with the last index value of the random vector.
int[] vetorAleatory = new int[100];
for (int i = 0; i < vetorAleatory.length; i++) {
vetorAleatory[i] = new Random().nextInt(1000);
}
int[] vetorByOrder = new int[100];
int newVetorPosition = 0;
for (int i = 0; i < 100; i++) {
for (int x = 0; x < 100; x++) {
vetorByOrder[newVetorPosition] = 2000;
if (vetorAleatory[i] < vetorByOrder[newVetorPosition]) {
boolean newEntry = true;
for (int y = 0; y < newVetorPosition; y++) {
if (vetorByOrder[y] == vetorByOrder[newVetorPosition]) {
newEntry = false;
break;
}
}
if (newEntry == true) {
vetorByOrder[newVetorPosition] = vetorAleatory[x];
}
}
if (x == 99) {
newVetorPosition++;
}
}
}
for (int i = 0;i<100;i++) {
System.out.print(vetorAleatory[i] + ", " + vetorByOrder[i] + System.lineSeparator());
}
First you do not need 3 loops to sort an array. You need only 2 and in case of quick search, it is even less than that. You can check this example Array sort and search, or you can use built in Arrays.sort method in Java

Random Char in 2D arrays

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

Inserting number into random array

I need some help inserting the number 8 into an array that gives me random values. The array must be in order. For example if I had an array of (1,5,10,15), I have to insert the number 8 between 5 and 10. I am having a problem on how I can figure our a way to find the index where 8 will be placed because the array is random, it can be anything. Here is my code so far :
public class TrickyInsert {
public static void main(String[] args) {
int[] mysteryArr = generateRandArr();
//print out starting state of mysteryArr:
System.out.print("start:\t");
for ( int a : mysteryArr ) {
System.out.print( a + ", ");
}
System.out.println();
//code starts below
// insert value '8' in the appropriate place in mysteryArr[]
int[] tmp = new int[mysteryArr.length + 1];
int b = mysteryArr.length;
for(int i = 0; i < mysteryArr.length; i++) {
tmp[i] = mysteryArr[i];
}
tmp[b] = 8;
for(int i =b ; i<mysteryArr.length; i++) {
tmp[i+1] = mysteryArr[i];
}
mysteryArr = tmp;
any tips? thanks!
Simply add the number then use Arrays.sort method,
int b = mysteryArr.length;
int[] tmp = new int[b + 1];
for(int i = 0; i < b; i++) {
tmp[i] = mysteryArr[i];
}
tmp[b] = 8;
mysteryArr = Arrays.sort(tmp);
In your example the random array is sorted. If this is the case, just insert 8 and sort again.
Simply copy the array over, add 8, and sort again.
int[] a = generateRandArr();
int[] b = Arrays.copyOf(a, a.length + 1);
b[a.length] = 8;
Arrays.sort(b);
int findPosition(int a, int[] inputArr)
{
for(int i = 0; i < inputArr.length; ++i)
if(inputArr[i] < a)
return i;
return -1;
}
int[] tmpArr = new int[mysteryArr.length + 1];
int a = 8; // or any other number
int x = findPosition(a, mysteryArr);
if(x == -1)
int i = 0;
for(; i < mysteryArr.length; ++i)
tmpArr[i] = mysteryArr[i];
tmpArr[i] = a;
else
for(int i = 0; i < mysteryArr.length + 1; ++i)
if(i < x)
tmpArr[i] = mysteryArr[i];
else if(i == x)
tmpArr = a;
else
tmpArr[i] = mysteryArr[i - 1];
I will suggest using binary search to find the appropriate index. Once you locate the index, you can use
System.arraycopy(Object src, int srcIndex, Obj dest, int destIndex, int length)
to copy the left half to your new array (with length one more than the existing one) and then the new element and finally the right half. This will stop the need to sort the whole array every time you insert an element.
Also, the following portion does not do anything.
for(int i =b ; i<mysteryArr.length; i++) {
tmp[i+1] = mysteryArr[i];
}
since int b = mysteryArr.length;, after setting int i =b ;, i<mysteryArr.length; will be false and hence the line inside this for loop will never execute.

I need to make permutations with an array using the ArrayList Class. I can't figure out what's wrong

so im taking an ap comp sci class in school, and in the class we're learning about the basics of java. For this assignment we have to make permutations by taking numbers from one one-dimensional array, and putting in another, then deleting that number so it can't be picked again. The numbers in the array can't repeat. We have to use the ArrayList Class too. And I can't figure out what's wrong!
This is the method that creates the permutations:
public static ArrayList<Integer> createPerm()
{
ArrayList<Integer> list = new ArrayList<Integer>(10);
Integer x = 1, remove = 0;
for (Integer i = 0; i < 10; i++)
{
list.add(x);
x++;
}
ArrayList<Integer> perm = new ArrayList<Integer>(10);
for(Integer i = 0; i < 10; i++)
{
Integer r = (int)(Math.random() * 10) + 1;
for (Integer j = 0; j <= list.size() - 1; j++)
{
if (list.get(j) == r)
{
remove = j + 1;
list.remove(remove);
perm.add(r);
}
}
}
return perm;
}
I think that you (and I also:)) got a lttle bit confused because you are using Integer-objects as index and as list elements.
That is no problem with the List.get method, because there is only one get method which is expecting an int and Java converts the Integer to int.
The problem is in your usage of list.remove(). There are two methods, one expects an object and one an int.
So if you pass an Integer object, the remove(Object) method is called. But you pass the index, not the r-matching object, so the remove method fails sometimes, because it is random if the element is in your list if remove was called before. And if the method not fails, you have removed the element with the value of your index(+1), not the one who matches r.
for(Integer i = 0; i < 10; i++)
{
Integer r = (int)(Math.random() * 10) + 1;
for (Integer j = 0; j <= list.size() - 1; j++)
{
if (list.get(j) == r)
{
remove = j + 1;
list.remove(remove);//the main error is here you found 4
//on index 2 and removes 3 (because of +1)
perm.add(r);
}
}
}
The next thing is, that random can deliver the same number more than once,
so you should not loop only 10 times. Loop until the list is empty.
I have corrected the code as below, the original lines are commented before the correction.
//for (Integer i = 0; i < 10; i++) {
while (!list.isEmpty()) {
Integer r = (int) (Math.random() * 10) + 1;
for (Integer j = 0; j <= list.size() - 1; j++) {
//if (list.get(j) == r) {
if (list.get(j).equals(r)) {
//remove = j + 1;
remove = list.get(j);
list.remove(remove);
perm.add(r);
}
}
}
And here I put the code somewhat more clearly, so that it is easier to read
public static ArrayList<Integer> createPerm() {
ArrayList<Integer> list = new ArrayList<Integer>(10);
for (int i = 0; i < 10; i++) {
list.add(i+1);
}
ArrayList<Integer> perm = new ArrayList<Integer>(10);
while (!list.isEmpty()) {
int r = (int) (Math.random() * 10) + 1;
for (int j = 0; j < list.size(); j++) {
if (list.get(j).intValue() == r) {
perm.add(list.remove(j));
}
}
}
return perm;
}

Create an int array of int arrays that contains all possible sums that add up to a given number

I'm completely new in Java. I am writing an Android game, and I need to generate an array of int arrays that contains all possible sums (excluding combinations that contains number 2 or is bigger than 8 numbers) that add up to a given number.
For example:
ganeratePatterns(5) must return array
[patternNumber][summandNumber] = value
[0][0] = 5
[1][0] = 1
[1][1] = 1
[1][2] = 1
[1][3] = 1
[1][4] = 1
[2][0] = 3
[2][1] = 1
[2][2] = 1
[3][0] = 4
[3][1] = 1
I already try to do this like there Getting all possible sums that add up to a given number
but it's very difficult to me to make it like this http://introcs.cs.princeton.edu/java/23recursion/Partition.java.html
Solution
int n = 10;
int dimension = 0;
//First we need to count number of posible combinations to create a 2dimensionarray
for(List<Integer> sumt : new SumIterator(n)) {
if(!sumt.contains(2) && sumt.size() < 9) {
dimension++;
}
}
int[][] combinationPattern = new int[dimension][];
int foo = 0;
for(List<Integer> sum : new SumIterator(n)) {
if(!sum.contains(2) && sum.size() < 9) {
System.out.println(sum);
combinationPattern[foo] = toIntArray(sum);
foo++;
}
}
It's work not 100% correctly, and very pretty, but it is enough for my game
I have used SumIterator class from here SumIterator.class
I have to changed this code for(int j = n-1; j > n/2; j--) { to this for(int j = n-1; j >= n/2; j--) { because old version doesn't return all combinations (like [5,5] for 10)
And I used toIntArray function. I have founded hare on StackOverflow, but forget a link so here it's source:
public static int[] toIntArray(final Collection<Integer> data){
int[] result;
// null result for null input
if(data == null){
result = null;
// empty array for empty collection
} else if(data.isEmpty()){
result = new int[0];
} else{
final Collection<Integer> effective;
// if data contains null make defensive copy
// and remove null values
if(data.contains(null)){
effective = new ArrayList<Integer>(data);
while(effective.remove(null)){}
// otherwise use original collection
}else{
effective = data;
}
result = new int[effective.size()];
int offset = 0;
// store values
for(final Integer i : effective){
result[offset++] = i.intValue();
}
}
return result;
}
This is not the most beautiful code, but it does what you would like, having modified the code you referenced. It is also quite fast. It could be made faster by staying away from recursion (using a stack), and completely avoiding String-to-integer conversion. I may come back and edit those changes in. Running on my pretty outdated laptop, it printed the partitions of 50 (all 204226 of them) in under 5 seconds.
When partition(N) exits in this code, partitions will hold the partitions of N.
First, it builds an ArrayList of string representations of the sums in space-delimited format (example: " 1 1 1").
It then creates a two-dimensional array of ints which can hold all of the results.
It splits each String in the ArrayList into an array of Strings which each contain only a single number.
For each String, it creates an array of ints by parsing each number into an array.
This int array is then added to the two-dimensional array of ints.
Let me know if you have any questions!
import java.util.ArrayList;
public class Partition
{
static ArrayList<String> list = new ArrayList<String>();
static int[][] partitions;
public static void partition(int n)
{
partition(n, n, "");
partitions = new int[list.size()][0];
for (int i = 0; i < list.size(); i++)
{
String s = list.get(i);
String[] stringAsArray = s.trim().split(" ");
int[] intArray = new int[stringAsArray.length];
for (int j = 0; j < stringAsArray.length; j++)
{
intArray[j] = Integer.parseInt(stringAsArray[j]);
}
partitions[i] = intArray;
}
}
public static void partition(int n, int max, String prefix)
{
if(prefix.trim().split(" ").length > 8 || (prefix + " ").contains(" 2 "))
{
return;
}
if (n == 0)
{
list.add(prefix);
return;
}
for (int i = Math.min(max, n); i >= 1; i--)
{
partition(n - i, i, prefix + " " + i);
}
}
public static void main(String[] args)
{
int N = 50;
partition(N);
/**
* Demonstrates that the above code works as intended.
*/
for (int i = 0; i < partitions.length; i++)
{
int[] currentArray = partitions[i];
for (int j = 0; j < currentArray.length; j++)
{
System.out.print(currentArray[j] + " ");
}
System.out.println();
}
}
}

Categories

Resources