i'm trying to solve the problem of rotation of the row of the 2 dimensional array and i given below the input output details
after input of the 1
5 2
1 2 3 4 5
i'm getting the output:-3 4 5 0 0
but the expected output is 3 4 5 1 2
package geeksforgeeks.basic;
import java.util.Scanner;
public class RotationOfAnArray
{
public static void main( String[] args )
{
Scanner sc = new Scanner( System.in );
//initializing the variables and the matrix
int i, j, n, k, l, f, p;
//taking the input
n = sc.nextInt();
int[][] arr1 = new int[100][100];
for( i = 0; i < n; i++ )
{
k = sc.nextInt();
l = sc.nextInt();
for( j = 0; j < k; j++ )
{
arr1[i][j] = sc.nextInt();
}
//in the above section taking the input of the elements of the array of the matrix
for( f = 0; f < l; f++ )
{
p = arr1[0][0];
for( j = 0; j < arr1.length - 1; j++ )
{
arr1[i][j] = arr1[i][j + 1];
}
//here the row of the particular matrix is not rotated
arr1[i][arr1.length - 1] = p;
}
for( j = 0; j < k; j++ )
{
System.out.print( arr1[0][j] + " " );
}
}
}
}
The problem with your code is you are initializing your array size as 100,and when later when you are trying to replace the last element by arr1[i][arr1.length-1]=p; it replaces last 99th index ,not 4th index. If you will iterate over complete array you can see those value sitting at last. My suggestion is initialise the array with the size of your need.
import java.util.Scanner;
public class RotationOfAnArray {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
//initializing the variables and the matrix
int i,j,n,k,l,f,p;
//taking the input
n=sc.nextInt();
int[][] arr1;
for(i=0;i<n;i++){
k=sc.nextInt();
//********Initialise array here instead.******
arr1=new int[k][k];
l=sc.nextInt();
for(j=0;j<k;j++){
arr1[i][j]=sc.nextInt();
}
//in the above section taking the input of the elements of the array of the matrix
for(f=0;f<l;f++) {
p=arr1[0][0];
for(j=0;j<arr1.length-1;j++) {
arr1[i][j]=arr1[i][j+1];
}
//here the row of the particular matrix is not rotated
arr1[i][arr1.length-1]=p;
}
for(j=0;j<k;j++) {
System.out.print(arr1[0][j]+" ");
}
}
}
}
I believe the issue was that you were overwriting the array as you were iterating through it, here is an example using a one dimensional array.
Scanner sc=new Scanner(System.in);
//initializing the variables and the matrix
int n,k,l;
//taking the input
n=sc.nextInt();//TestCases
k=sc.nextInt();//ArrayLength
l=sc.nextInt();//Rotations
int[] arr=new int[k];
for(int i=0;i<k;i++){
arr[i]=sc.nextInt();
}//in the above section taking the input of the elements of the array of the matrix
//Rotating the array
int[] backupArr = new int[k];//Backup is made as not to overwrite array
for(int i=0;i<arr.length;i++) {
backupArr[((i+arr.length-l)%arr.length)]=arr[i];//Modulo is used to keep index within constraints of array
}
arr=backupArr;//array is set to rotated instance
for(int a : arr)System.out.print(a);
Related
I'm trying to figure out how to turn this type of input from scanner:
3
a b c
d e f
g h i
into this array:
String[][] arr = {{a,b,c}, {d,e,f}, {g,h i}}
The first row specifies the dimensions of the array, and the lines after are the matrix.
This is the code that I have so far:
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
scan.nextLine();
String[][] matrix = new String[num][num];
I know I'll probably need a loop that separates each entry in the row by spaces and then add it into the first row in the array, then check for a new line repeat with each row, but I can't figure out how to implement this code.
I've made the program in Python, but I can't figure out how to do this in Java.
The below code answers your question, namely processes the input as indicated in your question which is first obtaining the [square] matrix dimension followed by separate lines where each line contains all the elements for a single row of the matrix where the elements are separated by spaces.
import java.util.Arrays;
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Number of elements in each row and each column of matrix.
int num = scan.nextInt();
String[][] matrix = new String[num][num];
scan.nextLine(); // Ignore return value.
for (int row = 0; row < num; row++) {
// Enter elements for single row of matrix, delimited by spaces.
String line = scan.nextLine();
String[] elements = line.split("\\s+");
for (int column = 0; column < num; column++) {
matrix[row][column] = elements[column]; // Note: user entered values not checked.
}
}
System.out.println(Arrays.deepToString(matrix));
}
}
Output for a sample run of the above code, using the sample values from your question:
3
a b c
d e f
g h i
[[a, b, c], [d, e, f], [g, h, i]]
Firstly, since we are taking int rather than strings, the matrix 2d-array should be one of int.
The rest should be almost identical structurally to your python code as far as I can imagine:
...
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
int[][] matrix = new int[num][num];
scan.nextLine();
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
matrix[i][j] = scan.nextInt();
}
scan.nextLine();
}
...
You can solve this problem by looping through the rows and columns in a 2D array.
import java.util.*;
class Test {
public static void main(String[] args) {
int row = 3, column = 3;
String[][] matrix = new String[row][column];
read(matrix, row, column);
print(matrix, row, column);
}
public static void read(String[][] matrix, int row, int column) {
Scanner scanner = new Scanner(System.in);
String input;
for(int i = 0 ; i < row ; ++i) {
for(int j = 0 ; j < column ; ++j) {
input = scanner.nextLine();
matrix[i][j] = input;
}
}
}
public static void print(String[][] matrix, int row, int column) {
for(int i = 0 ; i < row; ++i) {
for(int j = 0 ; j < column ; ++j) {
String result = String.format("MATRIX [%d][%d]: %s", i, j, matrix[i][j]);
System.out.println(result);
}
}
}
}
I am new to java programming and i am trying to sort arrays using Arrays.sort() function. After using Arrays.sort(array),I am printing the final sorted array.
For example:
Input : 1 3 2 4
Output comes as : 0 0 0 0.
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
public class TestClass {
public static final int MAX_SIZE = 20;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n,temp,count;
int[] array = new int[MAX_SIZE];
n = input.nextInt();
for(int i = 0 ; i < n ; ++i) {
array[i] = input.nextInt();
}
Arrays.sort(array);
for(int i = 0 ; i < n ; ++i) {
System.out.print(array[i]+" ");
}
}
}
You have initialized you array to hold 20 integers but you input only 5. Hence the first 15 elements will be 0 followed by the numbers you have inputted once the array is sorted.
To fix the issue you can initialize the array with n instead of MAX_SIZE as shown below:-
n = input.nextInt();
int[] array = new int[n];
Set the size of the array to match what your input should be, not to the maximum allowed size:
public class TestClass {
public static final int MAX_SIZE = 20;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n, temp, count;
n = input.nextInt();
if (n > MAX_SIZE) {
//handle error somehow
}
int[] array = new int[n];
for (int i = 0; i < n; ++i) {
array[i] = input.nextInt();
}
Arrays.sort(array);
for (int i = 0; i < n; ++i) {
System.out.print(array[i] + " ");
}
}
}
When you initialize an array in Java it gets default value of 0 for primitive int:
int[] array = new int[MAX_SIZE];
The fact that you are not seeing your desired input of 1,2,3,4 is a separate problem with your Scanner code.
This is the output i need (
Input Array: 1 2 3 4 5 6 7
Random Output: 7 2 3 6 1 5 4)
this is what i get
Input size of the Array
5
Input Value
1
Input Value
2
Input Value
3
Input Value
4
Input Value
5
Random Output: 2
Random Output: 0
Random Output: 0
Random Output: 0
Random Output: 0
The problem is with line 23 and im not sure how to fix it
import java.util.Random;
import java.util.Scanner;
public class problem_2 {
public static void main(String args[]){
Random r = new Random();
Scanner m = new Scanner(System.in);
System.out.println("Input size of the Array");
int size = m.nextInt();
int a[] = new int[size];
int b[] = new int[size];
for(int i = 0;i<a.length;i++) {
System.out.println("Input Value " +(i+1));
a[i] = m.nextInt();
}
int cell = 0;
int x = r.nextInt(size);
int value = a[x];
while(cell<size) {
for(int i =0; i<= size;i++) {
if (b[i]==value) {
cell++;
}
if(cell==0) {
b[cell] = value;
cell++;
}
System.out.println("Random Output: "+b[i]);
}
}
}
}
The problem is your code is going one too many indexes in the following for loop:
for(int i =0; i<= size;i++)
That's because you have to remember an array with say 5 elements has indexes 0-4. So while the size is the number of elements in the array the largest index is always (the number of elements) - 1.
So you should write the for loop like so:
for(int i = 0; i < size;i++)
Even then your code doesn't quite randomize correctly. The easiest way to randomize an array would be to swap out each element with another random element, like this:
//Randomize the array
for(int i = 0; i < size;i++) {
//lets get a random index in the array
int randIndex = (int)(Math.random()*size);
//then we will store the index we are swapping because its going to be overwritten
int temp = a[i];
//set our index equal to the random one
a[i] = a[randIndex];
//put our index's original value into the random index, so its not lost
a[randIndex] = temp;
}
thanks everyone for the help but i didnt learn any of the things in the others so
i found a easier way to do it
import java.util.Random;
import java.util.Scanner;
public class random{
public static void main(String args[]){
Random r = new Random();
Scanner m = new Scanner(System.in);
System.out.println("Input size of the Array");
int size = m.nextInt();
int a[] = new int[size];
int b[] = new int[size];
for(int i = 0;i<a.length;i++) {
System.out.println("Input Value ");
a[i] = m.nextInt();
}
int cell = 0;
while(cell<size) {
int n = r.nextInt(size);
int value = a[n];
int count = 0;
for(int i =0; i< size;i++) {
if (b[i]== value) {
count++;
}
}
if(count==0) {
b[cell] = value;
cell++;
}
}
System.out.println ("\n");
System.out.println("Input Array: ");
for (int i = 0; i<size; i++){
System.out.print(a[i] + " ");
}
System.out.println ("\n");
System.out.println("Random Output: ");
for (int i = 0; i<size; i++){
System.out.print(b[i] + " ");
}
}
}
What I need to do is ask the user to input values for two arrays and then output them separately and also output a merged array that is in ascending order.
For example, if the user inputs 2,5,8,0 for the first array and 6,7,0 for the second array, then the merged array should output 2,5,6,7,8.
The output for my first two arrays work perfectly but the merged array always outputs a zero. I also added a restart boolean to see if the user wants to try it again. Please help me as I am stuck.
I understand the though process but not sure how to implement this into my code. Here is my code:
//import packages
import java.util.Scanner;
import java.lang.Math;
import java.util.Arrays;
public class Main4{
public static void main(String[] args){
boolean doItAgain = true;//add boolean value to use when restarting progam
Scanner scan = new Scanner (System.in);//initialize new scanner
while(doItAgain){
//initialize variables
int first [] = new int[10000];//initialize to maximum of 10,000 integers
int second [] = new int[10000];//initialize to maximum of 10,000 integers
int input1;
int input2;
int counter1 = 0;//counter variable for first string
int counter2 = 0;//counter variable for second string
System.out.println("");
System.out.println("Welcome To my Merge Array Program 2.0!");
System.out.println("Enter the values for the first array, up to 10000 values, enter zero or a negative number to quit"); //asks user for first array input
//loop to go through each index
for (int a = 0; a<10000; a++)
{
input1 = scan.nextInt();//stores input as input1
first [a] = input1;
counter1++;
if (input1<=0)
break;//breaks out of loop if input1 value is 0 or below
}
int first2 []= new int [counter1-1];
for(int b = 0; b<first2.length; b++) {
first2 [b] = first[b];
}
System.out.println("Enter the values for the second array, up to 10000 values, enter zero or a negative number to quit"); //asks user for second array input
for (int j = 0; j<10000; j++)
{
input2 = scan.nextInt();//stores input as input2
second [j] = input2;
counter2++;
if (input2<=0)
break;//breaks out of loop if input1 value is 0 or below
}
int second2 []= new int [counter2-1];
for(int c = 0; c<second2.length; c++) {
second2 [c] = second[c];
}
System.out.println("First Array:");//output first array values in the order of their input
for (int p=0; p<first2.length; p++) {
System.out.print(first2[p] + " ");
}
System.out.println("\nSecond Array:");//output second array values in the order of their input
for (int p2=0; p2<second2.length;p2++) {
System.out.print(second2[p2] + " ");
}
boolean valid = true;
for (int e = 0; e<first2.length-1; e++) {
if(first2[e]>first2[e+1]) {
valid = false;
}
}
for (int e2 = 0; e2<second2.length-1;e2++) {
if(second2[e2]>second2[e2+1]) {
valid = false;
}
}
int[] array = new int[first2.length + second2.length];
//fill array 3 with arrays 1 & 2
for(int k = 0; k <first2.length;k++){
array[k] = first2[k];
}
for (int l = 0; l<second2.length; l++){
array[first2.length + l] = second2[l];
}
//sort array 3
for (int i = 0; i<first2.length + 1; i++){
for (int j = i+1; j<first2.length + 1; j++){
if(array[i] > array[j]){
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
//output sorted merged array
System.out.println("\nMerged Array: ");
for(int p3 = 0; p3<array.length; p3++) {
System.out.print(array[p3] + " ");
}
//Asks user if they want to restart program. Used boolean value to initialize doItAgain variable
System.out.println("");
System.out.println("");
System.out.println("Thanks for using this program! Do you want to do it again? (Y or N)");
if(scan.next().toLowerCase().equals("y")){
doItAgain = true;
break;
}
else{
doItAgain = false;
System.out.println("If you change your mind and want to run it again, type runMain.");//output closing statement if user says N to restart
break;
}
}
}
}
You are not merging your arrays. Your 1st array is, for instance [1 2] and your second array is, for instance [3 4]. Your final array is going to be initialized with size 4 (first2.length + second2.length), but all it's elements will be zero.
In this line here, I suggest you use arraycopy() to fill your final array:
int[] array = new int[first2.length + second2.length];
System.arraycopy(first2, 0, array, 0, first2.length);
System.arraycopy(second2, 0, array, first2.length, second2.length);
This will copy the first2 array to the starting position of your final array and then copy your second2 array to the position of your final array where first2 ended. You will end up with [1 2 3 4] and can then sort the elements (though in this case, they're already sorted.
For more information on arraycopy() consult this page here:
https://www.tutorialspoint.com/java/lang/system_arraycopy.htm
EDIT: BTW, you have an error right here, which is what is preventing you from printing the full sorted array:
//output sorted merged array
System.out.println("\nMerged Array: ");
for(int p3 = 0; p3<array.length; p3++) {
System.out.print(array[p3] + " ");
} //right here, you need to close this curly bracket
EDIT2: Since you can't use arraycopy(), you can use for loops to fill in the final array:
for(int k = 0; k <first2.length;k++){
array[k] = first2[k];
}
for (int l = 0; l<second2.length;l++){
array[first2.length + l] = second2[l];
}
A link to the assignment:
http://i.imgur.com/fc86hG9.png
I'm having a bit of trouble discerning how to take a series of numbers and apply them to an array without a loop. Not only that, but I'm having a bit of trouble comparing them. What I have written so far is:
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
int userInputs[] = new int[5];
int lotteryNumbers [] = new int[5];
int matchedNumbers =0;
char repeatLottery = '\0';
Scanner in = new Scanner (System.in);
do{
System.out.println("Enter your 5 single-digit lottery numbers.\n (Use the spacebar to separate digits): ");
for(int i = 0; i <5; i++ )
userInputs[i] = in.nextInt();
System.out.println("Your inputs: ");
printArray(userInputs);
System.out.println("\nLottery Numbers: ");
readIn(lotteryNumbers);
for(int i=0; i<5; i++) {
System.out.print(lotteryNumbers[i] + " ");
}
matchedNumbers = compareArr(userInputs, lotteryNumbers);
System.out.println("\n\nYou matched " + matchedNumbers + " numbers");
System.out.println("\nDo you wish to play again?(Enter Y or N): ");
repeatLottery = in.next().charAt(0);
}
while (repeatLottery == 'Y' || repeatLottery == 'y');
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
public static void readIn(int[] List) {
for(int j=0; j<List.length; j++) {
List[j] = (int) (Math.random()*10);
}
}
public static int compareArr (int[] list1, int[] list2) {
int same = 0;
for (int i = 0; i <= list1.length-1; i++) {
for(int j = 0; j <= list2.length-1; j++) {
if (list1[i] == list2[j]) {
same++;
}
}
}
return same;
}
}
As you'll notice, I commented out the input line because I'm not quite sure how to handle it. If I have them in an array, I should be able to compare them fairly easily I think. This is our first assignment handling arrays, and I think it seems a bit in-depth for only having one class-period on it; So, please forgive my ignorance. :P
Edit:
I added a new method at the end to compare the digits, but the problem is it compares them in-general and not from position to position. That seems to be the major issue now.
your question isn't 100% clear but i will try my best.
1- i don't see any problems with reading input from user
int[] userInput = new int[5]; // maybe here you had a mistake
int[] lotterryArray = new int[5]; // and here you were declaring your arrays in a wrong way
Scanner scanner = new Scanner(system.in);
for ( int i = 0 ; i < 5 ; i++)
{
userInput[i] = scanner.nextInt();
} // this will populate your array try to print it to make sure
Edit : important in the link you shared about the assignment the compare need to check the value and location so if there are two 5 one in input one in loterry array they need to be in the same location check the assignment again
// to compare
int result = 0 ; // this will be the number of matched digits
for ( int i = 0 ; i < 5 ; i++)
{
if ( userInput[i] == loterryArray[i] )
result++
}
// in this comparsion if the digits are equale in value and location result will be incremented