Specific output pattern of array in java - 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...

Related

How can I match the original array and the shuffled array?

This is the Prompt:
This is what I wrote:
import java.util.Scanner;
public class ContagionControl {
public static void main(String[] args) {
System.out.println("Please Enter the Number of Citizens: ");
Scanner input= new Scanner(System.in);
int a = input.nextInt();
int[] A = new int [a];
System.out.printf(" Id");
for (int i=0; i< A.length; i++) {
System.out.printf("%4d", i);
}
System.out.println();
System.out.printf("Cantactee");
for (int i=0; i< A.length; i++) {
int b= (int) (Math.random() * A.length);
System.out.printf ("%4d", b);
}
System.out.println();
System.out.println("Please Enter the Number of Citizens");
int c = input.nextInt();
for (int j=0; )
}
}
How can I match the infected id with his/her contactee ?
you need to create another ArrayList to hold quarantine_citizens;
step 1 Then get the contactee from to the citizen array base (index of citizen, map index to contactee array)
create variable to hold contactee and put into quarantine_citizens ArrayList
and it needs to map to the citizen array again ( do step 1 again )
#Jay explained the required algorithm in his answer. Below is the code that implements the algorithm.
The following appears in the assignment instructions that you posted in your question:
use the shuffling algorithm
And also
Be aware that all the elements are distinct
Your shuffling algorithm does not ensure that all elements are distinct. In other words, the algorithm that appears in the code in your question may produce the same number more than once.
The below code uses code taken from this Web page:
Shuffle Array in Java
The below code also checks for valid user input. More explanation appears after the code.
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class CC {
private static int[] getCitizens(int numberOfCitizens) {
int[] citizens = new int[numberOfCitizens];
for (int i = 0; i < numberOfCitizens; i++) {
citizens[i] = i;
}
return citizens;
}
private static int[] getContactees(int[] array, int a) {
int[] contactees = new int[array.length];
System.arraycopy(array, 0, contactees, 0, array.length);
Random rd = new Random();
// Starting from the last element and swapping one by one.
for (int i = a - 1; i > 0; i--) {
// Pick a random index from 0 to i
int j = rd.nextInt(i + 1);
// Swap array[i] with the element at random index
int temp = contactees[i];
contactees[i] = contactees[j];
contactees[j] = temp;
}
return contactees;
}
private static void printArray(int[] array, String format, String prompt) {
System.out.print(prompt);
for (int i : array) {
System.out.printf(format, i);
}
System.out.println();
}
private static void printResult(List<Integer> list) {
System.out.println("These citizens are to be self-isolated in the following 14 days:");
for (Integer id : list) {
System.out.print(id + " ");
}
System.out.println();
}
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in); // Don't close 'Scanner' that wraps stdin.
// (Even though IDE warns that you should.)
int numberOfCitizens = 0;
do {
System.out.print("Number of citizens: ");
try {
numberOfCitizens = input.nextInt();
if (numberOfCitizens <= 0) {
System.out.println("Must be positive integer. Try again.");
}
}
catch (InputMismatchException xInputMismatch) {
System.out.println("Not an integer. Try again.");
input.nextLine();
}
} while (numberOfCitizens <= 0);
int[] citizens = getCitizens(numberOfCitizens);
String format = "%" + Integer.toString(numberOfCitizens).length() + "d ";
printArray(citizens, format, " ID ");
int[] contactees = getContactees(citizens, numberOfCitizens);
printArray(contactees, format, "Contactee ");
int infectedCitizen = -1;
int limit = numberOfCitizens - 1;
do {
System.out.printf("ID of infected citizen [0-%d]: ", limit);
try {
infectedCitizen = input.nextInt();
if (infectedCitizen < 0 || infectedCitizen > limit) {
System.out.println("Not within range. Try again.");
}
}
catch (InputMismatchException xInputMismatch) {
System.out.println("Not an integer. Try again.");
input.nextLine();
}
} while (infectedCitizen < 0 || infectedCitizen > limit);
List<Integer> infected = new ArrayList<>(numberOfCitizens);
while (true) {
if (!infected.contains(infectedCitizen)) {
infected.add(infectedCitizen);
infectedCitizen = contactees[infectedCitizen];
}
else {
break;
}
}
Collections.sort(infected);
printResult(infected);
}
}
The last while loop, in method main is the actual algorithm. All preceding code is just preparation. I refer to the following code:
List<Integer> infected = new ArrayList<>(numberOfCitizens);
while (true) {
if (!infected.contains(infectedCitizen)) {
infected.add(infectedCitizen);
infectedCitizen = contactees[infectedCitizen];
}
else {
break;
}
}
I now use the sample data from your question to explain the above algorithm. Here is the sample data:
ID 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Contactee 2 0 7 11 15 4 14 1 8 13 3 5 12 9 6 10
We create an empty List.
The user-entered ID is 0 (zero).
We add 0 to the List.
We get the element in Contactee array at index 0 – which is 2
We add 2 to the List.
We get the element in Contactee array at index 2 – which is 7
We add 7 to the List.
We get the element in Contactee array at index 7 – which is 1
We add 1 to the List.
The element in Contactee at index 1 is 0. Since 0 already appears in the List, we are done.
List now contains all the infected citizens, namely 0, 1, 2 and 7.
Note that sorting the list is only to display the list in ascending order. It is not required.
Here is output from a sample run of the above code:
Number of citizens: 16
ID 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Contactee 5 8 3 0 11 12 14 9 7 1 15 2 4 13 6 10
ID of infected citizen [0-15]: 0
These citizens are to be self-isolated in the following 14 days:
0 2 3 4 5 11 12

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

JAVA Creating a program using an array

So I have an array of 20 elements:
int[]a = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40};
The array starts from 1 and ends at 20. So everything is doubled. 1 = 2, 2 = 4, 4 =6, etc.
And I am trying to create a program that when the user selects a number say for example 30. It adds the total from place point 15 to 20. So 30 + 32 + 34 + 36 + 38 + 40).
How would I tell the program to calculate the total based on the number the user inputs?
I cannot seem to figure this out. Would I use a for statement? I'm lost. Any help would be great. I am new to Java.
You can try something likewise,
int[]array = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40};
System.out.println("Enter Your choice Number : ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int index = n/2;
int sum = 0;
if(index < array.length){
for(int i = index;i<array.length;i++){
if( i > index){
System.out.print("+ ") ;
}
System.out.print(array[i]);
sum += array[i];
}
System.out.println("Answer : " + sum);
}
else{
System.out.println("InValid Value Entered, Try Again...!!");
}
Output :
public class Array {
public static void main(String[] args) {
int[]a = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40};
System.out.println("Enter the value");
Scanner s=new Scanner(System.in);
int in=s.nextInt();
int sum=0;
for(int i=0;i<a.length;i++)
{
if(in==a[i]){
for(int j=i;j<a.length;j++){
sum=a[j]+sum;
System.out.println(sum+"===="+j);
}
}
}
}

How to input integer 2d array fast

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] + " ");
}
}

Put a range on the input of an array in java

I am new to java programming. I would like to know if there is a way that I can fill the array with integers from the keyboard(range: 10 to 65). Here is my code:
public static void main(String[] args)
{
//Keyboard Initialization
Scanner kbin = new Scanner(System.in);
//a.Declare an array to hold 10 intgers values
int list[]=new int[10];
int i=0;
//b.Fill the array with intgers from the keyboard(range: 10 to 50).
System.out.print("\n\tInput numbers from 10 to 50: \n");
list[i]= kbin.nextInt();
if(10<=list[i] && list[i] <= 50)
{
for(i=1; i<=9;i++)
{
list [i] = kbin.nextInt();
}
}
}
please help.Thanks!
If I understand you intent properly...
You need to loop until you have 10 valid numbers. If a number entered by the user is out of range, then it needs to be discarded.
import java.util.Scanner;
public class TestStuff {
public static void main(String[] args) {
//Keyboard Initialization
Scanner kbin = new Scanner(System.in);
//a.Declare an array to hold 10 intgers values
int list[] = new int[10];
int i = 0;
System.out.print("\n\tInput numbers from 10 to 50: \n");
while (i < 10) {
//b.Fill the array with intgers from the keyboard(range: 10 to 50).
int value = kbin.nextInt();
if (value >= 10 && value <= 50) {
list[i] = value;
i++;
} else {
System.out.println("!! Bad number !!");
}
}
for (int value : list) {
System.out.println("..." + value);
}
}
}
Example output...
Input numbers from 10 to 50:
1
!! Bad number !!
2
!! Bad number !!
3
!! Bad number !!
4
!! Bad number !!
5
!! Bad number !!
6
!! Bad number !!
7
!! Bad number !!
8
!! Bad number !!
9
!! Bad number !!
10
11
12
13
14
15
16
17
18
19
...10
...11
...12
...13
...14
...15
...16
...17
...18
...19
This should fix it...
System.out.print("\n\tInput numbers from 10 to 50: \n");
for(int i=0; i<10;)
{
int k = kbin.nextInt();
if (k >= 10 && k <= 50)
{
list[i] = k;
++i;
}
}
I am not really sure what you are trying to do. But, I am guessing that you are trying to take the first 10 numbers the users enters?
One important thing to remember is that java (and other languages) uses 0 based indexing. So your for loop where i = 1, i <= 9; i++ I think that i should start at 0, but again I am not sure what you are going for here.
Though this question has been answered already but I noticed that no one provided or talked about the .hasNext() regex method so below I am providing an answer to this question using regex expression:
import java.util.Scanner;
public class Main3 {
public static void main (String [] args) {
int list [] = new int [10];
for (int i = 0; i < 10; i ++) {
Scanner sc = new Scanner (System.in);
if (sc.hasNext("([1-4][0-9])?(50)?")) {
list[i] = sc.nextInt();
} else {
System.err.println("Entered value is out of range 10 - 50. Please enter a valid number");
i --;
}
}
for (int i = 0; i < 9; i ++) {
System.out.print(list[i] + " ");
}
System.out.println(list[9]);
}
}

Categories

Resources