Random Number Generator of Even and Odd Numbers - java

I need to create an application that generates 25 random integers between 0 and 99 and then outputs those integers on two separate lines one for odd numbers and one for even numbers. I will need to use one array for even numbers and one for odd numbers. This is what I have so far:
public static void main(String[] args) {
//Odd Numbers
int[] oddNums = new int[25];
for (int index = 0; index < oddNums.length; index++) {
oddNums[index] = (int) (Math.random()*99);
}
System.out.print("ODD: ");
for (int index = 0; index < oddNums.length; index++) {
System.out.print(oddNums[index] + " ");
}
//Even Numbers
int[] evenNums = new int[25];
for (int index = 0; index < evenNums.length; index++) {
evenNums[index] = (int) (Math.random()*99);
}
System.out.print("\nEVEN: ");
for (int index = 0; index < evenNums.length; index++) {
System.out.print(evenNums[index] + " ");
}
}
I have set up the program to print out 25 random integers, but I do not know how I am going to get the program to print out only even numbers on one line and odd numbers on another (I am new to java).
Here is a sample output I am getting:
ODD: 28 36 54 98 35 1 59 43 96 69 41 66 37 15 30 17 29 67 56 83 71 4
24 70 38
EVEN: 34 45 36 26 73 84 60 39 21 49 28 98 69 14 32 24 72 29 26 88 77 2
23 58 47
This is wrong since there are both even and odd numbers on both lines.
This is what the output should look like:
ODD: 25 97 23 45 63 91 13 47 93 51 29
EVEN: 22 94 46 74 18 48 32 84 28 92 56
There are only odd numbers on one line and even numbers on another line.
Does anyone know what I need to add here?

A little modification to your program will yield the desired result.
public static void main(String[] args) {
//Odd Numbers
int[] randomNumbers = new int[25];
int[] evenNumbers = new int[25];
int[] oddNumbers = new int[25];
int k = 0, l = 0;
for (int index = 0; index < randomNumbers.length; index++) {
randomNumbers[index] = (int) (Math.random() * 99);
}
for (int i = 0; i < 25; i++) {
if (randomNumbers[i] % 2 == 0) {
evenNumbers[k] = randomNumbers[i];
k++;
} else {
oddNumbers[l] = randomNumbers[i];
l++;
}
}
}

You can generate an even number uniformly at random in [0,100] with the formula n = 2*x where x is uniformly random in [0, 49].
You can similarly generate an uniformly random odd number with n = 2*x+1 where x is uniformly random in [0,49].

You can just generate the 25 number. After generating those ints, you can locate them in the array they belong.
int num;
int oddIndex = -1;
int evenIndex = -1;
for (index = 0; index < 25 ; index++){
num = (int) (Math.random()*99);
if (num % 2 == 1){
oddIndex++;
oddNum[oddIndex] = num;
}
else{
evenIndex++;
evenNum[evenIndex] = num;
}
}
In this case, you're not sure about the sizes of each array. So, I advise you to use ArrayList instead of array. If you use an ArrayList, you won't need to deal with oddIndex and evenIndex.

Firstly,The random function you have written will be generating random numbers between 0 and 99. It will not be considering whether the numbers are odd or even.
If there is no restriction on the number of odd numbers and number of even numbers, just use the random generator once and depending on whether it is odd or even place it in the correct array.
For doing so, use the MOD operator i.e. check for remainder after dividing by 2 to see odd or even

At some point in your code, you need to have something like,
Pseudocode:
if (nextNumber is odd) then
put nextNumber at end of ODD array
else
put nextNumber at end of EVEN array
endif
You should also have a look at util.Random.nextInt() which is preferable for generating random integers.

Here's a solution that uses Java 8 streams:
public class NumberGenerator {
public static void main(String[] args) {
Random random = new Random();
int[] ints = random.ints(25, 0, 99).sorted().toArray();
int[] even = IntStream.of(ints).filter(x -> x % 2 == 0).toArray();
int[] odd = IntStream.of(ints).filter(x -> x % 2 == 1).toArray();
System.out.println(Arrays.toString(even));
System.out.println(Arrays.toString(odd));
}
}
First an array of all random integers are being created. 25 random integers are created and they should all be between 0 and 99.
The evens and odds are filtered out into two separate arrays.
[0, 4, 6, 16, 18, 22, 40, 42, 58, 64, 82, 84, 98]
[7, 27, 29, 31, 35, 55, 73, 75, 75, 79, 83, 91]

Related

How can I print out 1-50 even numbers only, but the it start a new line every multiples of 10. (JAVA)

I'm a newbie, but I'm willing to learn how to code.
I tried using this code:
int n = 50;
int counter = 0;
System.out.print("Even Numbers from 1 to "+n+" are: ");
for (int i = 1; i <= n; i++) {
counter++;
if (counter == 2) {
System.out.println(i + " ");
counter = 0;
%10== 0
to find all even numbers between 1 to 50 and make a new line at multiples of 10 just follow these steps -
Make one loop which will go 1 to 50
Check if the number is even by checking the remainder after diving it with 2, if YES print that number.
Check if the number is a multiple of 10 by checking the remainder after dividing it by 10, if YES make a new line
The code will look something like this -
int i = 1;
while(i<=50){
if(i%2 == 0) System.out.print(i + " ");
if(i%10 == 0) System.out.println();
i++;
}
Output -
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
It's up to you which looping method you want to use for me While loop looks cleaner.
I hope this solves all your queries.
PFB Snippet:
public class Main
{
public static void main(String[] args) {
for(int i=1;i<=50;i++){
if (i%2 == 0) //Check whether number is even
{
System.out.print(i+" ");
if (i%10 == 0) // Check if it is multiple of 10
{
System.out.print("\n");
}
}
}
}
}
Output:
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
"\n" is a Escape Sequence which means new line

Printing a snake pattern using an array

I'm having trouble with an assignment where we are required to print out this array:
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
My code is somewhat correct but it is not printing 10 and 19 where it should be.
My output:
Choose a number for the rows from 0 to 16.
5
Choose a number for the columns from 0 to 16
5
1 0 10 0 19
2 9 11 18 20
3 8 12 17 21
4 7 13 16 22
5 6 14 15 23
My code:
//snake move with the number
import java.util.Scanner;
public class SnakeMove {
public static void main(String[] args) {
//create Scanner object
Scanner inScan = new Scanner(System.in);
//prompt the user to choose number for the Row from 0 to 16
System.out.println("Choose a number for the rows from 0 to 16.");
//take the input from user with nextInt() method
//use the variable int row
int row = inScan.nextInt();
//prompt the user to choose number for the Col from 0 to 16
System.out.println("Choose a number for the columns from 0 to 16");
//take the input from user with nextInt()
//use the variable int col
int col = inScan.nextInt();
if (row != col) {
System.out.println("Run the program again and choose the same number for Row and Col");
System.exit(0);
}
int[][] arr = move(row, col);
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}//main method
static int[][] move(int row, int col) {
boolean flag = true;
int count = 1;
int[][] array = new int[row][col];
for (int j = 0; j < array[0].length; j++) {
if (flag) {
for (int i = 0; i < array.length; i++) {
//assign the increment value of count
// to specific array cells
array[i][j] = count;
count++;
}
flag = false;
} else {
//row decrement going up
for (int i = array.length - 1; i > 0; i--) {
//assign the increment value of count
// to specific array cells
array[i][j] = count;
count++;
}
flag = true;
}
}//column increment
return array;
}//move method
}//end SnakeMove class
Can anyone detect what is causing the error? Any help would be appreciated.
I believe this is a good alternative and easy to understand. Do comment if you have a simplified version of the same.
Code:
import java.util.Arrays;
import java.util.Scanner;
public class SnakePatternProblem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // *INPUT*
int row = scanner.nextInt();
int col = scanner.nextInt();
int[][] array = new int[row][col];
// Initializing first row of the array with a generalized expression
for (int i = 0; i < col; i++) {
if (i % 2 != 0) array[0][i] = col * (i+1);
else array[0][i] = (col * i) + 1;
}
array[0][0] = 1; // this element is not covered in the above loop.
// Nested loop for incrementing and decrementing as per the first row of elements.
for (int i= 1; i< row; i++){
for (int j=0; j< col; j++){
if(j%2==0) array[i][j] = array[i-1][j] + 1;
else array[i][j] = array[i-1][j] - 1;
}
}
System.out.println(Arrays.deepToString(array)); // *OUTPUT
}
}
Explanation:
Consider first row of 5 x 5 matrix named "arr" with snake pattern:
1 10 11 20 21
The element in the odd column is equivalent to ((currentColumn + 1) * Total_No_Of_columns);
Example: arr[0][1] = (1 + 1)* 5 = 10
The element in the even column is equivalent to (currentColumn * Total_No_Of_columns) + 1;
Example: arra[0][2] = (2 * 5) + 1 = 11;
Important Note: element at first row, first column is Zero
arr[0][0] = 1 -> must be declared
Now, the remaining matrix is incrementing or decrementing loop from the first element in that column.
Elements with even column number gets incremented by 1 in each row from the first element of that column.
1 -> First element of column-0
2 -> (1 + 1)
3 -> (2 + 1).... so on
4
5
Elements with odd column number gets decremented by 1 in each row from the first element of that column.
10 -> First element of column - 1
9 -> (10 - 1)
8 -> (9 - 1).... so on
7
6
This will generate the "snaking" pattern you described.
It could be simplified with ternary but this makes it more readable I think
It would be interesting to find a more clever way about it though, if anyone finds a better way pls comment
public static int[][] genArray(int length) {
int[][] arr = new int[length][length];
int counter = 0;
for (int col = 0; col < arr.length; col++) {
if (col % 2 == 0) {
for (int row = 0; row < arr.length; row++) {
arr[row][col] = counter++;
}
} else {
for (int row = arr.length - 1; row >= 0; row--) {
System.out.println("row: " + row + ", col: " + col);
arr[row][col] = counter++;
}
}
}
}
return arr;
}
You can create such an array as follows:
int m = 5;
int n = 4;
int[][] snakeArr = IntStream.range(0, n)
.mapToObj(i -> IntStream.range(0, m)
// even row - straight order,
// odd row - reverse order
.map(j -> (i % 2 == 0 ? j : m - j - 1) + i * m + 1)
.toArray())
.toArray(int[][]::new);
// output
Arrays.stream(snakeArr)
.map(row -> Arrays.stream(row)
.mapToObj(e -> String.format("%2d", e))
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
Transposing snake array:
int[][] transposedSA = new int[m][n];
IntStream.range(0, m).forEach(i ->
IntStream.range(0, n).forEach(j ->
transposedSA[i][j] = snakeArr[j][i]));
// output
Arrays.stream(transposedSA)
.map(row -> Arrays.stream(row)
.mapToObj(e -> String.format("%2d", e))
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
1 10 11 20
2 9 12 19
3 8 13 18
4 7 14 17
5 6 15 16
An easy way to do it is to create a 2-D array as shown below and then print its transpose.
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
21 22 23 24 25
It is a 2-D array of the dimension, LEN x LEN, where LEN = 5.
The above pattern goes like this:
The pattern starts with a start value of 1.
When the main loop counter is an even number, the counter, which assigns a value to the array, starts with start value and increases by one, LEN times. Finally, it sets start for the next row to start with final_value_of_the_array_value_assignment_counter - 1 + LEN.
When the main loop counter is an odd number, the counter, which assigns a value to the array, starts with start value and decreases by one LEN times. Finally, it sets start for the next row to start with start + 1.
The transpose of the above matrix will look like:
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
In terms of code, we can write it as:
public class Main {
public static void main(String[] args) {
final int LEN = 5;
int[][] arr = new int[LEN][LEN];
int start = 1, j, k, col;
for (int i = 0; i < LEN; i++) {
if (i % 2 == 0) {
k = 1;
for (j = start, col = 0; k <= LEN; j++, k++, col++) {
arr[i][col] = j;
}
start = j - 1 + LEN;
} else {
k = 1;
for (j = start, col = 0; k <= LEN; j--, k++, col++) {
arr[i][col] = j;
}
start++;
}
}
// Print the transpose of the matrix
for (int r = 0; r < LEN; r++) {
for (int c = 0; c < LEN; c++) {
System.out.print(arr[c][r] + "\t");
}
System.out.println();
}
}
}
Output:
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
Change the value of LEN to 10 and you will get the following pattern:
1 20 21 40 41 60 61 80 81 100
2 19 22 39 42 59 62 79 82 99
3 18 23 38 43 58 63 78 83 98
4 17 24 37 44 57 64 77 84 97
5 16 25 36 45 56 65 76 85 96
6 15 26 35 46 55 66 75 86 95
7 14 27 34 47 54 67 74 87 94
8 13 28 33 48 53 68 73 88 93
9 12 29 32 49 52 69 72 89 92
10 11 30 31 50 51 70 71 90 91

Find The Longest Increasing Sequence in a 2 Dimensional Array [duplicate]

This question already has answers here:
How to determine the longest increasing subsequence using dynamic programming?
(20 answers)
Closed 5 years ago.
I've been working on this problem for awhile and couldn't come up with the solution; I hope you can help out..
I'm trying to find the longest increasing sequence of numbers. For example, if I have the following 4X4 array:
[![enter image description here][1]][1]
int [] nums = {
{97 , 47 , 56 , 36},
{35 , 57 , 41 , 13},
{89 , 36 , 98 , 75},
{25 , 45 , 26 , 17}
};
THE EXPECTED RESULT : return 8 and the LIS 17, 26, 36, 41, 47, 56, 57, 97
I don't have the answer to it yet, I'm trying to reach it.
17 (3,3)
26 (3,2)
36 (2,1)
41 (1,2)
47 (0,1)
56 (0,2)
57 (1,1)
97 (0,0)
I hope my example is clear enough..
This is my code; when I try to find the longest increasing path, it doesn't do it backward not diagonally. Can anyone help me please?
public class Solution2 {
static int[] dx = { 1, -1, 0, 0 };
static int[] dy = { 0, 0, 1, -1 };
public static int longestIncreasingPath(int[][] matrix) {
if (matrix.length == 0)
return 0;
int m = matrix.length, n = matrix[0].length;
int[][] dis = new int[m][n];
int ans = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
ans = Math.max(ans, dfs(i, j, m, n, matrix, dis));
}
}
return ans;
}
static int dfs(int x, int y, int m, int n, int[][] matrix, int[][] dis) {
if (dis[x][y] != 0)
return dis[x][y];
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && ny >= 0 && nx < m && ny < n && matrix[nx][ny] > matrix[x][y]) {
dis[x][y] = Math.max(dis[x][y], dfs(nx, ny, m, n, matrix, dis));
}
}
return ++dis[x][y];
}
public static void main(String[] args) {
int arr[][] = {
{ 97, 47, 56, 36 },
{ 35, 57, 41, 13 },
{ 89, 36, 98, 75 },
{ 25, 45, 26, 17 }
};
System.out.println(longestIncreasingPath(arr));
}
}
I assume we are looking for a strictly increasing sequence (this is not clear from the original problem description).
This problem can then be solved by a dynamic programming approach:
1) sort the cells by their value into decreasing order.
2) in decreasing order assign the length of the longest path starting at this cell:
2a) if you cannot reach any of the previously visited cells assign 1
2b) otherwise assign 1 + max(reachable previous cell)
When this is finished, the overall maximum is the length of the longest path. The path itself can also be found by remembering the max cell in step 2b).
In the example this gives:
0,3 2,1
cell 98 97 89 75 57 56 47 45 41 36 36 35 26 25 17 13
length 1 1 1 2 2 3 4 2 5 6 6 7 7 7 8 7
As far as I understand, you try to implement a depth-first search to find the longest path of increasing order. If so, first of all it is better to mark numbers you visited somehow. A convenient solution is an array. As far as the numbers are marked, you can use it to check whether the particular number has already been counted in an increasing sequence. This is as a little hint for you.
If you are still confused about a depth-first search, I would recommend to read the Depth-First Search Wikipedia page to get a better understanding of what the algorithm is all about.
HTH, Evgeniy

Set large array of numbers to designated length per line

int size = 50;
// Generates non-duplicated random numbers
int[] values = new int[51];
int[] list = new int[size];
for( int i = 0; i < 51; i++ )
values[i] = i;
Random rand = new Random();
int listSize = 0;
int myList = 0;
while( true )
{
int value = rand.nextInt(51);
if( values[ value ] == 0 )
continue; // number already used
list[ myList++ ] = value;
values[ value ] = 0;
if( myList == size || myList == 50 )
break;
}
// Displays non-duplicated random generated numbers
for(int element : list)
System.out.print(element + " ");
I would like to set a large array of numbers to a designated length per line to make all the numbers appear as though they're in a block with the left and right sides even like so:
> 1 2 3 4 5 6 7 8 9 10
> 11 12 13 14 15 16 17 18 19 20
> 21 22 23 24 25 26 27 28 29 30
> 31 32 33 34 35 36 37 38 39 40
> 41 42 43 44 45 46 47 48 49 50
How do I accomplish this using an enhanced for loop? Thanks for your help!
Add a new line after read 10 value
for(int i=0; i<list.length; i++){
System.out.printf(" %-2d",list[i]); //Format left justified
if ((i+1)%10==0){
System.out.println(); // Add a new line after 10
}
}

Subtract elements in an array

I have an array with this values 80 82 84 90 94 is it possible to subtract the values so the output could be 0 2 2 6 4?
I´ve edited the question:Now I want to use this in an android cursor adapter but I´m getting index out of bounds when it reaches the calculation of the difference.
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
double weight = cursor.getDouble(cursor
.getColumnIndex(DbHelper.ENTRY_USER_WEIGHT));
int count=cursor.getCount();
Double[] input = new Double[count];
// Obtaining the number of records
System.out.println("number of records "+input.length);
// Array for storing differences
double[] difference= new double[count ];
difference [0] = 0; // First record difference is 0 only
int i;
// Looping number of records times
for( i=0; i<count-1 ;i++)
{
input[i]=weight;
System.out.println("i value"+i);
System. out.println(""+input[i]);
// Difference = next record - current record
difference [i]= input [i+1] - input[i];
// System.out.println ("Difference between "+input [i+1]+ " and "+input[i] + " is : " +difference[i]);
}
// Setting the input array.
int input[]= {80, 82, 84, 90, 94};
// Obtaining the number of records
int noOfRecords = input.length;
// Array for storing differences
double[] difference= new double[noOfRecords ];
difference [0] = 0; // First record difference is 0 only
// Looping number of records times
for( int i=0; i < noOfRecords -1 ;i++)
{
// Difference = next record - current record
difference [i+1]= input [i+1] - input[i];
System.out.println ("Difference between "+input [i+1]+ " and "+input[i] + " is : " +difference[i+1]);
}
System.out.println("My final difference array Output is : "+java.util.Arrays.toString( difference ));
OUTPUT:
Difference between 82 and 80 is : 2.0
Difference between 84 and 82 is : 2.0
Difference between 90 and 84 is : 6.0
Difference between 94 and 90 is : 4.0
My final difference array Output is : [0.0, 2.0, 2.0, 6.0, 4.0]
If you replace double[] difference = new double[noOfRecords ]; by
int [] difference = new int [noOfRecords];
You get an output exactly as you wanted :
Difference between 82 and 80 is : 2
Difference between 84 and 82 is : 2
Difference between 90 and 84 is : 6
Difference between 94 and 90 is : 4
My difference array Output is : [0, 2, 2, 6, 4]
Logic:
for array Arr[] = {80 82 84 90 94}
Required output = {0,2,2,6,4}
Sol:
output[0] = 0;
for( i=1;i<cursor.getCount();i++)
{
output[i] = Arr[i]-Arr[i-1];
}
Note that the output array elements are obtained by subtracting current index element with the element at previous index.
Example 82-80 =2, 84-82=2, 90-84=6 and 94-90=4
You can subtract a number from its next number.
int[] numbers={80, 82, 84, 90, 94};
for (int i = 0; i < numbers.length; i++) {
if(i < numbers.length - 1)
System.out.println(numbers[i + 1] - numbers[i]);
}
}
Output-
2
2
6
4

Categories