The program below generates 10 pairs of random numbers of a certain size and stores them in an ArrayList named test -
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
public class randomGenerate
{
static ArrayList<String> tcase=new ArrayList<String>();
static ArrayList<int[]> test=new ArrayList<int[]>();
public static void main(String args[])
{
tcase.add("1");
tcase.add("2");
tcase.add("3");
tcase.add("4");
tcase.add("5");
tcase.add("6");
randomSelection(10,2);
for(int i=0;i<test.size();i++)
{
System.out.println(Arrays.toString(test.get(i)));
}
}
static int randomNo(int max,int min)
{
Random obj = new Random();
int n = max - min + 1;
int i = obj.nextInt(n);
int randomNum = min + i;
return randomNum;
}
static void randomSelection(int limit, int pairSize)
{
int max = Integer.parseInt(Collections.max(tcase));
int min = Integer.parseInt(Collections.min(tcase));
System.out.println(max+" "+min);
int ar[]=new int[pairSize];
for(int i = 0;i < limit;i++)
{
for(int j = 0;j < pairSize;j++)
{
ar[j]=randomNo(max,min);
System.out.print(ar[j]);
}
test.add(ar);
System.out.println();
}
}
}
My problem is that while printing the contents of the arrayList "test" only the last value is displayed. Why is it not displaying all the values.
output - (for example)
23
65
45
63
12
23
52
52
16
12
[1, 2]
[1, 2]
[1, 2]
[1, 2]
[1, 2]
[1, 2]
[1, 2]
[1, 2]
[1, 2]
[1, 2]
You're always modifying and adding the same array to the list at each iteration.
Think of a situation like this :
You need to create a new array at each iteration :
for(int i = 0;i < limit;i++){
int ar[]=new int[pairSize]; //create a new one at each iteration
for(int j = 0;j < pairSize;j++){
ar[j]=randomNo(max,min);
System.out.print(ar[j]);
}
test.add(ar);
System.out.println();
}
The problem is that you are adding the array ar to the ArrayList test each iteration in randomSelection(), so when you modify ar in the next iteration, you are modifying it inside the ArrayList, to solve this try:
Way 1:
Create a new array each iteration
int ar[];
for (int i = 0; i < limit; i++) {
ar = new int[pairSize]; // Initialize inside 'for'
for (int j = 0; j < pairSize; j++) {
ar[j] = randomNo(max, min);
System.out.print(ar[j]);
}
test.add(ar);
}
Way 2:
Create a copy of the array ar and add it to test:
int ar[] = new int[pairSize];
for (int i = 0; i < limit; i++) {
for (int j = 0; j < pairSize; j++) {
ar[j] = randomNo(max, min);
System.out.print(ar[j]);
}
test.add(ar.clone()); // Create a copy
}
Related
I am trying to create a 3x3 matrix that has the numbers 1 to 9 generated at different locations each time you run the code. the method I came up with does not work and I can't find out why it doesn't work, so if anyone could point out the reason why it does not work it would be really really appreciated.
and if anyone knows how to solve this problem in any other way please let me know.
Here's the method I created:
public static int[][] randgen() {
Random rand = new Random();
int[][] a = new int[3][3];
int x;
for(int i = 0; i<a.length; i++) {
for (int j = 0; j < a.length; j++) {
a[i][j] = rand.nextInt(8) +1;
do {
x = 1;
for(int k = 0; k<i; k++) {
for(int l = 0; l<j; l++) {
if(a[k][l] == a[i][j]) {
x++;
}
}
}
if(x!=1) {
a[i][j] = rand.nextInt(8) +1;
}
} while (x!=1); //this while loop I'm using as a way to find duplicates and keep changing up the number until I reach an integer with no duplicates, and this is the part of the program that is failing and I can't understand why
}
}
}
I've tried creating a sorted algorithm and then making a function to shuffle some of the elements which also did not work.
The only thing that worked for me is creating an ArrayList and then printing it out in a way that it looks like an array
Another variation...
Populate the list with the numbers 1 to 9 but then pick a random spot from it to fill the next slot of your array. Each time you pick a random spot from the list you remove it.
Might look like:
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
import java.util.Arrays;
class Main {
public static void main(String[] args) {
Random rand = new Random();
int[][] a = new int[3][3];
int counter = 1;
int totalSpots = a.length * a[0].length; // assumes RECTANGULAR array
List<Integer> numbers = new ArrayList<Integer>();
while (counter <= totalSpots) {
numbers.add(counter);
counter++;
}
for(int row = 0;row < a.length; row++) {
for(int col = 0; col < a[0].length; col++) {
int index = rand.nextInt(numbers.size());
a[row][col] = numbers.get(index);
numbers.remove(index);
}
}
for(int[] row : a) {
System.out.println(Arrays.toString(row));
}
}
}
Sample output:
[5, 3, 6]
[9, 4, 8]
[2, 7, 1]
If we change the size of the array:
int[][] a = new int[5][4];
It sill works:
[7, 3, 6, 11]
[19, 20, 1, 4]
[13, 12, 17, 2]
[5, 18, 9, 16]
[14, 15, 10, 8]
So I am completely stumped. I need to create a multi-dimensional array n×n and have it be filled in a particular way. I have been able to create the 2d array per n×n but have no idea how to fill it. Below I have included the task worded exactly as given to me:
Given the number n, not greater than 100. Create the matrix of size n×n and fill it by the following rule. Numbers 0 should be stored on the primary diagonal. The two diagonals, adjacent to the primary one, should contain numbers 1. The next two diagonals - numbers 2, etc.
Sample Input 1:
5
Sample Output 1:
0 1 2 3 4
1 0 1 2 3
2 1 0 1 2
3 2 1 0 1
4 3 2 1 0
Here is my code so far. Any direction would be GREAT!!
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[][] array = new int[n][n];
for (int i = 0; i < array.length; i++) {
System.out.println(Arrays.toString(array[i]));
}
}
}
import java.util.Arrays;
import java.util.Scanner;
public class FillTheMatrixByTheNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.close();
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = Math.abs(j - i);
}
}
for (int i = 0; i < n; i++) {
String str = Arrays.toString(matrix[i]);
str = str.replace("[", "")
.replace(",", "")
.replace("]", "");
System.out.println(str);
}
}
}
Here's how I would approach your problem:
I would use nested for loops, one to iterate over the rows, and one to iterate over the columns. In my example, i is iterating over rows, and j is iterating over columns. Now that I know I'm hitting each cell of the matrix once and only once, I just have to figure out a way to calculate the cell's value from i and j. In this case, the cell's value is the column number minus the row number, or j - i, except there's no negatives, which can easily be solved with an absolute value (Math.abs(int)). Below is how I would do it:
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[][] array = new int[n][n];
for (int i = 0; i < n; i++) { //iterate over rows
for (int j = 0; j < n; j++) { //iterate over columns
array[i][j] = Math.abs(j - i); //calculate cell's value
}
}
for (int i = 0; i < n; i++) {
System.out.println(Arrays.toString(array[i]));
}
}
}
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[][] array = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
array[i][j] = Math.abs(j - i);
System.out.print(array[i][j] + " ");
}
System.out.println("");
}
}
}
You can subtract a column index from a row index or vice versa and take abs value from a result. This way you get a cell value:
int n = 5;
int[][] arr = IntStream.range(0, n)
.mapToObj(i -> IntStream.range(0, n)
.map(j -> Math.abs(i - j))
.toArray())
.toArray(int[][]::new);
// output
Arrays.stream(arr).map(Arrays::toString).forEach(System.out::println);
[0, 1, 2, 3, 4]
[1, 0, 1, 2, 3]
[2, 1, 0, 1, 2]
[3, 2, 1, 0, 1]
[4, 3, 2, 1, 0]
I want to copy the old array to the new one and I want to add the empty elements to the new array
import java.util.Arrays;
public class testArray2D {
public static void main(String[] args) {
int[][] a = {{1, 2, 3}};
// make a one bigger
int add = 3;
a = Arrays.copyOf(a, a.length + add);
for (int i = 1; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = 1;
}
}
for (int i[] : a) {
System.out.println(Arrays.toString(i));
}
}
}
The expected output is
1 2 3
1 1 1
1 1 1
1 1 1
Why I can't run this?
You need to initialize the new array elements.
import java.util.Arrays;
public class testArray2D {
public static void main(String[] args) {
int[][] a = {{1, 2, 3}};
// make a one bigger
int add = 3;
a = Arrays.copyOf(a, a.length + add);
for (int i = 1; i < a.length; ++i) {
if(a[i] == null) {
a[i] = new int[3];
}
for (int j = 0; j < a[i].length; ++j) {
a[i][j] = 1;
}
}
for (int i[] : a) {
System.out.println(Arrays.toString(i));
}
}
}
If you want to copy existing array to a new array having size larger than the existing array, I would suggest the following.
int[][] source_arr = {{1, 2, 3}};
int add = 3;
int[][] dest_arr = new int[source_arr[0].length+add][source_arr[0].length];
for (int i = 0; i < source_arr.length; i++) {
System.arraycopy(source_arr[i], 0, dest_arr [i], 0, source_arr[i].length);
}
why isn't this code working?
I'm supposed to write a function which removes the odd numbers from an array. here is my code but I don't know where it went wrong. It's giving me an error.
public class Test{
public static int [] removeOdd(int[] input){
int c = 0;
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
c++;
}
}
int [] a = new int[c];
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
a[i] = input[i];
}
}
return a;
}
public static void main(String [] args){
int [] mixedArray = {21, 33, 44, 66, 11, 1, 88, 45, 10, 9};
for (int i = 0; i < mixedArray.length; i++) {
System.out.print(mixedArray[i] + " ");
}
System.out.println();
int [] noOdd = Test.removeOdd(mixedArray);
for (int i = 0; i < noOdd.length; i++) {
System.out.print(noOdd[i] + " ");
}
}
Thanks in advance :)
You need another index variable to access the items of a and not use i:
public static int [] removeOdd(int[] input){
int c = 0;
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
c++;
}
}
int [] a = new int[c];
int k = 0;
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
a[k] = input[i];
k++;
}
}
return a;
}
The index variable i iterates through input and its values do not match and will exceed the permitted values of the indexes of a so I have used k.
The problem is here:
int [] a = new int[c];
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
a[i] = input[i];
}
}
This loop will iterate through the whole input array, and try to insert just the even ones into a, but a is smaller than input, because you allocated space equal to the amount of just the even numbers in input.
In your test case, your a will have size 4, but will try to access the position 6, giving you an out of bound exception.
The problem is that you are trying to insert at a[i] which you could visualise like this:
index: 0 1 2 3 4
input: [1 2 3 4 5]
a: [ 2 4 ]
However, your a array is smaller than your input array, because you have reduced the size to account for the lack of odd numbers. You actually want to do this:
index: 0 1 2 3 4
input [1 2 3 4 5]
a [2 4]
Notice how the index of both even numbers has changed. You were trying to keep it the same.
One way to solve this would be to keep a separate counter variable which tracks where you're up when inserting into a.
int[] a = new int[c];
int sizeOfA = 0;
for (int i = 0; i < input.length; i++)
{
if (input[i] % 2 == 0)
{
a[sizeOfA] = input[i];
sizeOfA++;
}
}
You can simplify the method removeOdd using Streams:
import java.util.Arrays;
public class Test {
public static int[] removeOdd(int[] input) {
return Arrays.stream(input).filter(i -> i % 2 == 0).toArray();
}
public static void main(String[] args) {
int[] mixedArray = { 21, 33, 44, 66, 11, 1, 88, 45, 10, 9 };
for (int i = 0; i < mixedArray.length; i++) {
System.out.print(mixedArray[i] + " ");
}
System.out.println();
int[] noOdd = Test.removeOdd(mixedArray);
for (int i = 0; i < noOdd.length; i++) {
System.out.print(noOdd[i] + " ");
}
}
}
I got an 100 random elements array, each element is in range of 0-10, and i need to count each integer how many times it was typed (e.g. 1,2,2,3,8,8,4...)
OUTPUT:
1 - 1
2 - 2
3 - 1
8 - 2
4 - 1
My code so far is:
import java.util.Random;
public class Asses1 {
public static void main(String[] args) {
getNumbers();
}
private static int randInt() {
int max = 10;
int min = 0;
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static int[] getNumbers() {
int number = 100;
int[] array = new int[number];
for (int i = 0; i < array.length; i++) {
System.out.println(randInt());
}
System.out.println(number+" random numbers were displayed");
return array;
}
}
Add this method, which will do the counting:
public static void count(int[] x) {
int[] c=new int[11];
for(int i=0; i<x.length; i++)
c[x[i]]++;
for(int i=0; i<c.length; i++)
System.out.println(i+" - "+c[i]);
}
and change the main into this so that you call the previous method:
public static void main(String[] args) {
count(getNumbers());
}
Also, change the for loop in getNumbers into this in order to fill array with the generated numbers, not just printing them:
for (int i = 0; i < array.length; i++) {
array[i] = randInt();
System.out.println(array[i]);
}
Here is how it can be done in java 8
// Retrieve the random generated numbers
int[] numbers = getNumbers();
// Create an array of counters of size 11 as your values go from 0 to 10
// which means 11 different possible values.
int[] counters = new int[11];
// Iterate over the generated numbers and for each number increment
// the counter that matches with the number
Arrays.stream(numbers).forEach(value -> counters[value]++);
// Print the content of my array of counters
System.out.println(Arrays.toString(counters));
Output:
[12, 11, 7, 6, 9, 12, 8, 8, 10, 9, 8]
NB: Your method getNumbers is not correct you should fix it as next:
public static int[] getNumbers() {
int number = 100;
int[] array = new int[number];
for (int i = 0; i < array.length; i++) {
array[i] = randInt();
}
System.out.println(number+" random numbers were displayed");
return array;
}
int[] array2 = new int[11];
for (int i = 0; i < array.length; i++){
array2[randInt()]++
}
for (int i = 0; i < array.length; i++)
System.out.println(String.valueOf(i) + " - " + String.valueOf(array2[i]));
What I have done is:
Create an helping array array2 for storing number of occurences of each number.
When generating numbers increment number of occurences in helping array.
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
int temp;
for (int i = 0; i < array.length; i++) {
temp=randInt();
if(map.containsKey(temp)){
map.put(temp, map.get(temp)+1);
}else{
map.put(temp, 1);
}
}