How to input integer 2d array fast - java

I have to input 5 int arrays, in less than 3 sec, means execution time should be less than 3,and i was using Scanner class or that,but it is making the execution time more,so is there any other possible way,i have to get input as
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
And have to input 1 2 3 in one line ?how would i do it..?
i was taking initially string as input ,and then using split(" ") method for separating it,then parsing it using wrapper classes? any other way to do it?

Try the following snippet, I guess its what you may be looking for inputting 2d array without splitting the string using Scanner..
int[][] array = new int[5][2];
Scanner scan = new Scanner(System.in);
int i=0;
int k=0;
while(scan.hasNextInt()){
array[i][k] = scan.nextInt();
k++;
if(k == 2) {
k = 0;
i++;
}
if(i == array.length){
break;
}
}
for(int p=0; p < array.length; p++) {
for(int j=0;j < 2; j++) {
System.out.print(array[p][j] + " ");
}
}

Related

inserting integer digits as elements

Sudoku with Java Arrays
I am building a 9x9 2D array and trying to fill it by inputting a random 9 digits integer for each row. I want to insert each digit of that number as an element along the rows [0][0-8],[1][0-8]... I tried to convert the integer into a string and insert each character but I can't seem to figure it out.
System.out.println("Please insert 9 lines of 9 digits (1-9)");
int Choise = scan.nextInt();
char c =(char)Choise;
int soduko[][] = new int[9][9];
for (int i = 0; i< soduko.length; i++){
for(int j =0; j< soduko.length; j++){
soduko[i][j]=c;
}
}
i have tried another way that still uses the number as an int, by taking the remainder of that number to the last cell in the row, and dividing the number by 10 each time in the loop. although its not working when i try to divide by 10 to get the next remainder.
System.out.println("Please insert 9 lines of 9 digits (1-9)");
Choise = scan.nextInt();
for (int i =0; i <= soduko.length -1; i++){
for(int j = soduko.length -1; j > 0; j--){
int ChoiseDigit = Choise % 10;
soduko[0][j] = ChoiseDigit;
Choise = (int)(Choise / 10);
}
}
Building on your string conversion idea, you might benefit from using the split() method, which splits up a string based on a string you pass as an argument, and then returns an array of the split-up strings. So when you do split(""), the string is split up into single characters. Then you can parseInt to turn each string into an int. I would also recommend putting the scanner input in the loop, to make sure the user has to input a string 9 times.
System.out.println("Please insert 9 lines of 9 digits (1-9)");
int soduko[][] = new int[9][9];
for (int i = 0; i< soduko.length; i++){
//reading a string of input 9 times and splitting them by "" into 1-character strings
String Choise[] = scan.nextLine().split("");
for(int j =0; j< soduko[i].length; j++){
//Integer.parseInt converts each string to an int so we can save it to the 2d array
soduko[i][j]= Integer.parseInt(Choise[j]);
}
}

Specific output pattern of array in java

I've figured out how to create an array in which the output look like this:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
if the user enters a 4 indicating a 4x4 array.
My question is how could I manipulate this code in a way that it would out put the array in this order
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13
where every other row is "backwards"
`import java.util.Scanner;
import java.util.Arrays;
import java.util.Arrays;
public class Question2 {
public static void main(String[] args) {
//Title
System.out.println("[----------------------]");
System.out.println("[ Array Pattern ]");
System.out.println("[----------------------]");
System.out.println("");
//declare scanner
Scanner keyboard = new Scanner (System.in);
//Prompt user to enter a digit greater than or equal to 3
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3):");
//read user input
int num = keyboard.nextInt();
//place constraints on int num so that if it is less than 3, the program does not execute
while(num<3 )
{
System.out.println("Lets's try this again....");
System.out.println("How many rows/colums do you want your array to have? (Must be at least 3):");
num = keyboard.nextInt();
}
//2D array with number of rows and columns entered by user
int[][] array = new int [num][num];
int inc=1;
for(int i=0;i<array.length;i++)
for(int j=0;j<array.length;j++)
{
array[i][j]=inc;
inc++;
}
//replace all square brackets in array display & format into order
//replace all commas in array display
String a = Arrays.toString(array);
a = Arrays.deepToString(array).replace("], [", "\n").replaceAll("[\\[\\],]", "");
System.out.println(a);`
This loop will do it:
int reverse = 0;
for(int i=0;i<array.length;i++)
for(int j=0;j<array.length;j++)
{
if(i%2 == 0){
if(j == 0){
inc = reverse;
if(i > 0 )inc = inc + num + 1;
}
array[i][j]=inc;
inc++;
}
else{
if(j == 0)reverse = inc + num - 1;
array[i][j]=reverse;
reverse--;
}
}
Every other row it place numbers in a descending order.
Also to print out the numbers with tabs between them use:
String a = Arrays.toString(array);
a = Arrays.deepToString(array).replace("], [", "\n").replace(", ", "\t").replaceAll("[\\[\\],]", "");
System.out.println(a);
This will stop a table forming diagonally.
What you could do is reverse the order of the for loop on every other line, so that it decrements instead:
for(int i=0;i<array.length;i++)
{
if(i%2 == 0){
for(int j=0;j<array.length;j++)
{
array[i][j]=inc;
inc++;
}
}
else{
for(int j=num-1;j>=0;j--)
{
array[i][j]=inc;
inc++;
}
}
}
I don't really know how to format the columns the way you wrote the code (with Arrays.deepToString) but if you instead loop through it manually you could pad the string:
String [][]stringConvertedTable= new String[num][num];
for(int i=0; i<num; i++) {
for(int j=0; j<num; j++) {
stringConvertedTable[i][j]= Integer.toString(array[i][j]);
System.out.print(stringConvertedTable[i][j] + "\t");
}
System.out.println("");
}
It's not the most elegant way to do it though...

Negative Arrays and Error Messages

//MY TASK IS TWO MERGE TO ARRAYS INTO ASCENDING ORDER.Your program will accept each array as input from the keyboard. You do not know ahead of time how many values will be entered, but you can assume each array will have a maximum length of 10,000 elements. To stop entering values enter zero or a negative number. You should disregard any non-positive numbers input and not store these in the array.
The elements of the two input arrays should be in increasing order. In other words, each array element must have a value that is greater than or equal to the previous element value. An array may contain repeated elements.
import java.util.Scanner;
import java.lang.Math;
class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int one[]= new int[10000];
int two[]= new int[10000];
int lengthShort=0;
int lengthLong=0;
int a =0;
int b =0;
System.out.println("Enter the values for the first array, "
+ "up to 10000 values, enter a negative number to quit");
for(int i=0; i<one.length && scan.hasNext(); i++){
one[i] = scan.nextInt();
a++;
if(one[i]<0){
one[i]=0;
break;
}
}
int length1 = a-1;
System.out.println("Enter the values for the second array, "
+ "up to 10000 values, enter a negative number to quit");
for(int i=0; i<two.length && scan.hasNext(); i++){
two[i] = scan.nextInt();
b++;
if(two[i]<0){
two[i]=0;
break;
}
}
int lengthTwo = b-1;
int mergeOne[] = new int[length1];
for (int i = 0; i<mergeOne.length; i++){
mergeOne[i]=one[i];
}
int mergeTwo[] = new int[lengthTwo];
for (int i = 0; i<mergeTwo.length; i++){
mergeTwo[i]=two[i];
}
System.out.println("First Array:");
for(int i=0; i<mergeOne.length; i++){
System.out.print(mergeOne[i] + " ");
}
System.out.println("\nSecond Array:");
for(int i=0; i<mergeTwo.length; i++){
System.out.print(mergeTwo[i] + " ");
}
if(mergeOne.length<=mergeTwo.length){
lengthLong = mergeTwo.length;
lengthShort = mergeOne.length;
}
else if(mergeOne.length>=mergeTwo.length){
lengthShort = mergeTwo.length;
lengthLong = mergeOne.length;
}
int merged[] = new int[length1 + lengthTwo];
for(int i = 0; i<lengthShort; i++){
if(i==0){
if(mergeOne[i]<=mergeTwo[i]){
merged[i] = mergeOne[i];
merged[i+1] = mergeTwo[i];
}
else if(mergeTwo[i]<=mergeOne[i]){
merged[i] = mergeTwo[i];
merged[i+1]= mergeOne[i];
}
}
else if(i>0){
if(mergeOne[i]<=mergeTwo[i]){
merged[i+i] = mergeOne[i];
merged[i+i+1] = mergeTwo[i];
}
else if(mergeTwo[i]<=mergeOne[i]){
merged[i+i] = mergeTwo[i];
merged[i+i+1]= mergeOne[i];
}
}
}
if(mergeOne.length<mergeTwo.length){
for(int k=lengthShort; k<lengthLong; k++){
merged[k]=mergeTwo[k];
}
}
if(mergeOne.length>mergeTwo.length){
for(int k=lengthShort; k<lengthLong; k++){
merged[k]=mergeOne[k];
}
}
for(int i = 0; i<merged.length; i++){
if((i+1)==merged.length)
break;
if(merged[i]>merged[i+1]){
int temp = merged[i+1];
merged[i+1]=merged[i];
merged[i]= temp;
}
}
System.out.println("\nMerged array in order is: ");
for(int i = 0; i<merged.length; i++){
System.out.print(merged[i] + " ");
}
}
}
//My code compiles in drjava but I have two issues:
1) It doesn't order the numbers in ascending order
2) When I run it through the site I have to submit this on it gives me the message as follows:
Runtime Error
Exception in thread "main" java.lang.NegativeArraySizeException
at Main.main(Main.java:281)
at Ideone.assertRegex(Main.java:94)
at Ideone.test(Main.java:42)
at Ideone.main(Main.java:29)
You'll need to rethink your merge algorithm. Suppose you input arrays are
1 5 10 50 100 500
2 4 6 8 10 12 14 16
You'll need to repeatedly decide which element is smaller to put into the output. So after selecting N elements, your output will look like
1 2 4 5 6 8 10 10 12 14
And you will need to have indexes pointing at the place in the input arrays you'll need to look at next:
1 5 10 50 100 500
^^
2 4 6 8 10 12 14 16
^^
As you can see, the indexes could be at very different places in the input arrays. However, your code does a lot of this:
if(mergeOne[i]<=mergeTwo[i]){
which means it's only comparing elements from the input that are in the same location. This doesn't work, and trying to swap elements in the output after the fact isn't good enough to get the job done.
Basically, instead of having one index and comparing the elements of the two input arrays at the same index, you'll need two indexes. I'll let you take it from there, but I think you can figure it out.
(And I have no idea why you're getting NegativeArraySizeException.)

printing a 2d array java

The program I need to write is a square 2d array made of numbers, like this
0 1 2
3 4 5
6 7 8
or this
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
The program reads the number "d" (side of the square 2d array- above are examples of d=3 and d=5), number "n" (how many inputs there will be next) and these n inputs (eg. if n=3, the program should let me insert three numbers, like from the first example, let's say I'd choose 1 and 4 and 3. So the input looks like:
3
3
1 4 2
Then, it needs to calculate the distance between the first and second, second and third input and sum them up. That sum is then the output. Here is the program
if(b==2) {
int d=sc.nextInt();
int n=sc.nextInt();
int[][] array=new int[d][d]; //length and heigth of array
int c=0;
int manhattanDistanceSum=0;
for (int i = 0; i < n; i ++){ //for inserting values
for (int j = 0; j < n; j ++){
if (i < n){
i++;
array[i][j] = sc.nextInt();
}
else {
break;
}
for( i=0; i<array.length;i++) {
for( j=0;j<array[0].length;j++) {
array[i][j]=c; //actual locations of numbers
//numbers in array
c++;
if(manhattanDistanceSum != 0) {
int dx= c / d;
int dy= c % d;
c=Math.abs(dx) + Math.abs(dy);
manhattanDistanceSum+=c;
}
}
}
System.out.print(array[i][j]);
System.out.println();
}
}
System.out.println(manhattanDistanceSum);
}
}
}
*the b doesn't matter, it just means this is going to be a square array, so ignore it. It has nothing to do with this.
This is all I got, and need help with anything that is wrong in my code.
Thankyou
I've just cobbled together this example and tested that it works with positive and negative numbers. It might not do exactly what you want (for example, is the data in your array organised row-by-column or column-by-row) and it might not exactly format the output the way you want, but it should show you how to iterate through the array and analyse and then extract the data to produce a String which can be printed out.
Be sure to conduct your own testing (create unit tests for all cases which your application will need) as I have thrown this together in a few minutes in the hope that it would get you started. It should not be considered a finished product by any means.
public static void main(String[] args) {
int[][] data = {{0, -10734, 2}, {3, 437, 5}, {6, 733838, 8}};
System.out.println("Table:\n" + formatAsTable(data));
}
public static String formatAsTable(int[][] squareNumericArray) {
int cellSpacing = 2;
StringBuilder sb = new StringBuilder();
int squareSide = squareNumericArray.length;
int cellSize = findLargestNumericString(squareNumericArray)
+ cellSpacing;
for (int firstIndex = 0; firstIndex < squareSide; ++firstIndex) {
if (squareNumericArray[firstIndex].length != squareSide) {
throw new IllegalArgumentException(
"Array must have same size in both dimensions.");
}
for (int secondIndex = 0; secondIndex < squareSide; ++secondIndex) {
sb.append(String.format("%-" + cellSize + "d",
squareNumericArray[firstIndex][secondIndex]));
}
sb.append("\n");
}
return sb.toString();
}
private static int findLargestNumericString(int[][] squareNumericArray) {
int maxLength = 0;
for (int firstIndex = 0; firstIndex < squareNumericArray.length;
++firstIndex) {
for (int secondIndex = 0; secondIndex
< squareNumericArray[firstIndex].length; ++secondIndex) {
String numberAsString = Integer.toString(
squareNumericArray[firstIndex][secondIndex]);
if (numberAsString.length() > maxLength) {
maxLength = numberAsString.length();
}
}
}
return maxLength;
}
This code will output the following to the console:
Table:
0 -10734 6
3 437 5
6 733838 19

I am trying to merge to integer strings but Dr. Java the program I am using won't let me use ArrayUtils?

In this lab, you will be creating a program that merges two arrays of non-negative (equal to or greater than 0) integers. Your program will accept each array as input from the keyboard. You do not know ahead of time how many values will be entered, but you can assume each array will have a maximum length of 10,000 elements. To stop entering values enter a negative number. You may disregard any negative numbers input and not store these in the array.
The elements of the two input arrays should be in increasing order. In other words, each array element must have a value that is greater than or equal to the previous element value. An array may contain repeated elements.
After the two arrays have been input, your program must check to make sure the elements of each array have been entered in order. If an out of order element is found, print the message “ERROR: Array not in correct order”.
Your task is to merge the two input arrays into a new array, with all elements in order, lowest to highest. Print out each of the original arrays entered, followed by the merged array.
Please note that your program must output the arrays with exactly one space between each of the numbers.
Sample Run 1:
Enter the values for the first array, up to 10000 values, enter a negative number to quit
3
3
5
6
8
9
-1
Enter the values for the second array, up to 10000 values, enter a negative number to quit
3
4
5
6
-5
First Array:
3 3 5 6 8 9
Second Array:
3 4 5 6
Merged Array:
3 3 3 4 5 5 6 6 8 9
Sample Run 2:
Enter the values for the first array, up to 10000 values, enter a negative number to quit
4
5
7
2
-1
Enter the values for the second array, up to 10000 values, enter a negative number to quit
3
3
3
3
3
3
-100
First Array:
4 5 7 2
Second Array:
3 3 3 3 3 3
ERROR: Array not in correct order
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
import java.lang.Math;
import java.lang.Object;
import java.util.Arrays;
import java.util.ArrayList;
import org.apache.commons.lang3.ArrayUtils;
class Main
{
public static void main (String str[]) throws IOException {
{
Scanner scan = new Scanner(System.in);
int[] arrayone = new int[10000];
int[] arraytwo = new int[10000];
int [] mergeQ = new int[arrayone.length + arraytwo.length];
int integers = 0;
int inte = 0;
System.out.println("\nEnter the values for the first array, up to 10000 values, enter a negative number to quit");
for (int i = 0; i < arrayone.length; i++)
{
arrayone[i] = scan.nextInt();
if (arrayone[i] < 0){
break;
} else {integers ++;}
}
System.out.println("\nEnter the values for the second array, up to 10000 values, enter a negative number to quit");
for (int i=0; i<arraytwo.length; i++)
{
arraytwo[i] = scan.nextInt();
if (arraytwo[i] < 0)
{
break;
} {inte ++;}
}
System.out.println("First Array:");
for (int i=0; i< integers; i++)
{
System.out.print(arrayone[i] + " ");
}
System.out.println("\nSecond Array:");
for (int i=0; i< inte; i++)
{
System.out.print(arraytwo[i] + " ");
}
System.out.println("\nMerged Array:");{
String[] both = ArrayUtils.addAll(arrayone[integer], arraytwo[inte]);
Arrays.sort(both);
}
}
}
}
you were adding elements but not the arrays themselves.
In you second loop
}{ inte++; }
change this to
}else {inte ++;}
one solution could be
int[] both = ArrayUtils.addAll(Arrays.copyOf(arrayone, integers), Arrays.copyOf(arraytwo,inte));
Arrays.sort(both);
for (int i=0; i< both.length; i++){
System.out.print(both[i] + " ");
A very bad way to do it.. but will work in your CS class
for (int i=0; i< integers; i++){
mergeQ[i] = arrayone[i];
}
for (int i=integers; i< inte + integers; i++){
mergeQ[i] = arraytwo[i - integers];
}
int both[] = Arrays.copyOf(mergeQ,integers+inte);
Arrays.sort(both);
for (int i=0; i< both.length; i++){
System.out.print(both[i] + " ");
}
Note: this way is pretty evil.. memory inefficient.. etc..
Here is another way it is a bit cleaner but roughly has the same performance as the one above..
System.arraycopy(arrayone, 0, mergeQ, 0, integers);
System.arraycopy(arraytwo, 0, mergeQ, integers, inte);
int both[] = Arrays.copyOf(mergeQ,integers+inte);
Arrays.sort(both);
for (int i=0; i< both.length; i++){
System.out.print(both[i] + " ");
}

Categories

Resources