printing a 2d array java - 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

Related

How to rotate 2-D Array in Java

[SOLVED]
The title of this question is vague but hopefully this will clear things up.
Basically, what I am looking for is a solution to rotating this set of data. This data is set up in a specific way.
Here is an example of how the input and output would look like:
Input:
3
987
654
321
Output:
123
456
789
The '3' represents the number of columns and rows that will be used. If you input the number '4', you will be allowed to input 4 sets of 4 integers.
Input:
4
4567
3456
2345
1234
Output:
1234
2345
3456
4567
The goal is to find a way to rotate the data only if needed. You have to make sure the smallest corner number is at the top left. For example, for the code above, you rotated it so 1 is at the top left.
The problem I have is that I don't know how to rotate the data. I am only able to rotate the corners but not the sides. This is what my code does so far:
take the input of each line and turn them into strings
split those strings into separate characters
store those characters in an array
I just do not know how to compare those characters and in the end rotate the data.
Any help would be appreciated! Any questions will be answered.
A detailed description of the problem is here(problem J4).
This is just a challenge I assigned myself for practice for next year's contest, so giving me the answer won't "spoil" the question, but actually help me learn.
Here is my code so far:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int max = kb.nextInt();
int maxSqrt = (max * max);
int num[] = new int[max];
String num_string[] = new String[max];
char num_char[] = new char[maxSqrt];
int counter = 0;
int counter_char = 0;
for (counter = 0; counter < max; counter++) {
num[counter] = kb.nextInt();
}
for (counter = 0; counter < max; counter++) {
num_string[counter] = Integer.toString(num[counter]);
}
int varPos = 0, rowPos = 0, charPos = 0, i = 0;
for (counter = 0; counter < maxSqrt; counter++) {
num_char[varPos] = num_string[rowPos].charAt(charPos);
i++;
if (i == max) {
rowPos++;
i = 0;
}
varPos++;
if (charPos == (max - 1)) {
charPos = 0;
} else {
charPos++;
}
}
//
for(int a = 0 ; a < max ; a++){
for(int b = 0 ; b < max ; b++)
{
num_char[counter_char] = num_string[a].charAt(b);
counter_char++;
}
}
//here is where the code should rotate the data
}
}
This is a standard 90 degree clockwise rotation for a 2D array.
I have provided the solution below, but first a few comments.
You said that you're doing this:
take the input of each line and turn them into strings
split those strings into separate characters
store those characters in an array
Firstly youre essentially turning a int matrix into a character matrix. I do not think you need to do this, since even if you do want to compare values, you can use the ints provided.
Secondly, there is no need to compare any 2 data elements in the matrix, since the rotation does not depend on any value.
Here is an adapted solution for java, originally written in C# by Nick Berardi on this question
private int[][] rotateClockWise(int[][] matrix) {
int size = matrix.length;
int[][] ret = new int[size][size];
for (int i = 0; i < size; ++i)
for (int j = 0; j < size; ++j)
ret[i][j] = matrix[size - j - 1][i]; //***
return ret;
}
If you wanted to do a counterCW rotation, replace the starred line with
ret[i][j] = matrix[j][size - i - 1]

Filling rest of Array

I am writing a two's complement program where I convert decimal to binary using an array. I also want to have 8 Bits binary.
Since, for example, 22 is 10110 in binary, I want to fill the rest of the array with zeros, but I wasn't able to find a way how to do this.
Any help is appreciated.
Edit:
static void toBin(int number){
int[] bin = new int[8];
int i =0;
while (number > 0){
bin[i] = number % 2;
number = number/2;
i++;
}
// Here is where I would like to add zeros if the size of the array is below 0
for (int j = i-1; j>=0;j--){
System.out.println(bin[j]); //Array gets reserved
}
}
There is a class called "Arrays" that has a method called "fill()".
The syntax is "Arrays.fill()".
Inside the round brackets, after "fill", you have to put the value that will fill the rest of the array.
The example below fills the elements which have index from 0 to 5 (without 6) with the value 1.
int[] intArray = new int[8];
Arrays.fill(ints2, 0, 6, 1) ;
System.out.println(Arrays.toString(intArray));
Here is the output:
[1, 1, 1, 1, 1, 1, 0, 0]
Look at this code:
int number =22;
int bits[]= new int[8];
for(int i=0;i<=7;i++){
if(number>0){
bits[7-i]=number%2;
number/=2;
}
else{
bits[7-i]=0;
}
}
for(int i=0;i<=7;i++){
System.out.print(bits[i]);
}
I think, I have resolved your problem.
First initialize the whole string and reserve some space, like eight characters.
String binaryStr = "00000000";
for (int i = 0; i < binaryStr.Length (); i++)
{
if (binaryShouldBeOne)
{
binaryStr[i] = '1';
} else
{
binaryStr[i] = '0';
}
}
This may help.
int out[] = new int[8];
int in = 22;
int i = out.length - 1;
while (i >= 0 && in > 0) {
out[i] = in % 2;
in /= 2;
i--;
}
for (int j = 0; j < out.length; j++) {
System.out.print(out[j] + " ");
}
System.out.println("");
The array is initialized with zeros when it is created. You need just to change the required digits with 1 and rest will remain zeros. Try to start filling the array from 8th digit then decrement your counter so you may reach the most left digit.

Issue in swapping specific array elements

The following is no homework. I'm just trying to write my own permutation code. I have an idea but I have problems in writing this idea as code.
As example the input is myArray={1,2,3};
Then the output is supposed to be:
1 2 3
2 1 3
2 3 1
3 2 1
3 1 2
1 3 2
I figured out it's possible by switching the first element with second, then switch second with third (however not entirely possible, but I know I need this).
That's why my question is how can I do this in Java?
I have 1 2 3 and I want switch first element with second, so I get 2 1 3. Print this. Now I want switch second element with third, I get 2 3 1, print it. Repeat n! times where n is myArray length.
I tried to do this with the following code but it seems like I'm far away from it :(
public class Test{
public static void main(String[] args){
int[] myArray = {1,2,3};
for(int x=0; x<6; x++){
for(int i=0; i<myArray.length-1; i++){
int temp=myArray[i];
myArray[i]=myArray[i+1];
myArray[i+1]=temp;
}
for(int i=0; i<myArray.length; i++){
System.out.print(myArray[i]+" ");
}
System.out.println("");
}
}
}
Output:
2 3 1
3 1 2
1 2 3
2 3 1
3 1 2
1 2 3
I'm not sure if I understood correctly though.
public static void main(String[] args) {
int[] myArray = {1, 2, 3};
for (int i = 0; i < 6; i++) {
print(myArray);
int temp = myArray[i % myArray.length];
myArray[i % myArray.length] = myArray[(i + 1) % myArray.length];
myArray[(i + 1) % myArray.length] = temp;
}
}
private static void print(int[] array) {
for (int anArray : array) {
System.out.print(anArray + " ");
}
System.out.println("");
}
EDIT:
I noticed, there is a wrong order, so it should be better:
public static void main(String[] args) {
int[] myArray = {1, 2, 3};
for (int i = 0; i < 6; i++) {
int idx = i % (myArray.length - 1);
print(myArray);
int temp = myArray[idx];
myArray[idx] = myArray[idx + 1];
myArray[idx + 1] = temp;
}
}

Java: generate all number combitations to a bound

I have the digits 1 3 5 7 and 9 (odds)what I want is a method type long[] that takes as parameter int digits
the digits paremater is supposed to be the maximum digits that the number could have.
this method is suppose to add all the possible combinations with 1 3 5 7 and 9 to the array.
What I've done so far:
Figured out the size of the array
int size = 0
for(int i = 0; i < digits; i++){
size += (int) Math.pow(5,i+1);
I've tried many for-loops but none of them seem to work.
The goal of this is that i'm trying to find some sort of a prime number and making this table will make my program a lot faster.
If i understand you correctly i think this might work. Maybe there is a cleaner way, it's been a while since i worked in JAVA.
long[] expand(int digits) {
int[] a = {1, 3, 5, 7, 9};
long[] b = long[5];
for(int i=0; i<5; i++){b[i] = a[i];}
int it_left = digits;
while(it_left > 0) {
it_left--;
long[] c = long[(b.length()*5)];
for(int i=0; i<5; i++){
long tmp = a[i]*Math.pow(10, (digits-it_left));
for(int j=0; j<b.length(); j++){
c[(i*b.length())+j] = tmp + b[j];
}
}
b = long[c.length()];
for(int i=0; i<c.length(); i++){
b[i]=c[i];
}
}
return b;
}

How to create a program i n Java which gets all combinations of 1 and 2 of given number of digits

Let's say n= 7, so I need to display all possible combinations of 7 digits made out of 1s and 2s:
1111111
1111112
1111121
1111211
1112111
.......
2222222
Here is my code, but it is hardcoded nested 7 times loops. So my count=128 which is 2^7 But how to make it programmatically for n number of times nesting? I think it needs some recursion, but how to do it?
int count = 0;
for (int j = 1; j<=2; j++) {
for (int z= 1; z<=2; z++) {
for (int i = 1; i<=2; i++) {
for (int k = 1; k<=2; k++) {
for (int l= 1; l<=2; l++) {
for (int m = 1; m<=2; m++) {
for (int y = 1; y<=2; y++) {
count++;
System.out.println(count+":"+j+z+i+k+l+m+y+",");
}
}
}
}
}
}
}
Usually, "all combinations of N symbols" is the same than "counting in base N".
Since you have two symbols, even easier. Count from 0 to X, get the binary representation of each number, replace 0 by 2. Once the binary representation gets longer than the number of values you desire, stop.
Do not forget to add leading 2 to numbers which are too short.
I quite like an obfuscated version .... ;-) :
final int l = 7;
long m = 1 << l;
while (--m >= 0) {
int b=l;
while (--b >= 0) {
System.out.print(((m >> b)& 1 ) + 1);
}
System.out.println();
}
}
Edit:
I should add a description of the above.... All I do is count down from 2^7 - 1 and then print the bits set in each value (printing 2 for bit-value 1, and printing 1 for bit-value 0);
Use recursion. You should plan to pass in the partially-built string, and the number of digits remaining. I will concatenate strings here, though StringBuilders should generally be used.
public static void printOutString(int levelsRemaining, String current){
if(levelsRemaining==0) System.out.println(current);
else{
printOutString(levelsRemaining-1, current+"1");
printOutString(levelsRemaining-1, current+"2");
}
}
You can also use an iterative approach:
public static ArrayList<String> getAllStrings(int length){
ArrayList<String> prev;
for(int i=0; i<length; i++){
ArrayList<String> newL=new ArrayList<String>;
for(String s:prev){
newL.add(s+"1");
newL.add(s+"2");
}
prev=newL;
}
return prev;
}
Here's a simple way to get all permutations of some domain, ie you would calling:
permute(3,"12", ""); yields:
111 112 121 122 211 212 221 222
public void permute(int length, String domain, String result)
{
if (length == 0)
{
System.out.println(result);
}
else
{
for (int i = 0; i < domain.length(); i++)
permute(length-1, domain, result + domain.charAt(i));
}
}

Categories

Resources