Printing diagonal elements of a 2D array - java

l'm trying to print the diagonal numbers of a square 2D array but l'm having a hard time with it.It's because of how l create the array isn't it? What l am doing wrong?
int[][] arr1 = { { 1, 2,6}, { 3, 4,5} }; // l'm stuck here
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j <arr1.length; j++) {
System.out.print(arr1[i][j] + " ");
}
System.out.println();
}
for (int k = 0; k < arr1.length; k++) {
System.out.println( arr1[k][k]);
}
l expected to see 1 2 3
4 5 6
7 8 9
And for the actual results? l have being stuck

Your array declaration should look like this:
int[][] arr1 = { { 1, 2, 3}, { 4, 5, 6}, {7, 8, 9} };
assuming you want an ordered 3 x 3 matrix.

Related

how to write a method to reverse a 2D array

I got this question to solve
Write a method that takes a two-dimensional array of type integer as a parameter and return
the inverse of the array (the rows become the columns and vice versa).
that is what I did through searching, but it shows a bunch of errors
public static class inverse{
public static int[][] arrayInverse(int[][] A){
int[][] B = new int[3][3];
for(int i=0; i<B.length/2;i++){
for (int j=0; j<B[i].length/2;j++) {
int swap = B[i][j];
B[B.length - i - 1] = swap;
}
}
return swap;
}
}
}
First, as mentioned in the comments, the task is to transpose the input array the rows become the columns and vice versa
If the input 2D array is square (the number of the rows is the same as the number of columns), the most efficient way would be to swap the elements below and over the main diagonal: a[i][j] ⇄ a[j][i] without using extra array:
public static int[][] transposeSquare(int[][] arr) {
for (int i = 0, n = arr.length; i < n; i++) {
// select the elements only above the main diagonal
for (int j = i + 1, m = arr[i].length; j < m; j++) {
int tmp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = tmp;
}
}
return arr;
}
However, in general case of a rectangular matrix it may be needed to create a new array/matrix of size M x N instead of N x M, and copy the values from the input in appropriate order (no swap is needed then):
public static int[][] transpose(int[][] arr) {
int[][] result = new int[arr[0].length][arr.length];
for (int i = 0, n = arr.length; i < n; i++) {
for (int j = 0, m = arr[i].length; j < m; j++) {
result[j][i] = arr[i][j];
}
}
return result;
}
You need to replace between columns and rows
public class inverse {
/**
* The entry point of application.
*
* #param args the input arguments
*/
public static void main(String[] args) {
int ints[][] = {{1, 2, 3},
{5, 6, 7},
{9, 10, 11},
{12, 13, 14}
};
print2D(ints);
System.out.println("\n");
print2D(arrayInverse(ints));
}
/**
* Array inverse int [ ] [ ].
*
* #param A the a
* #return the int [ ] [ ]
*/
public static int[][] arrayInverse(int[][] A) {
if (A.length == 0 || A[0].length == 0) {
System.out.println("A.length==0 || A[0].length==0");
return A;
}
int[][] B = new int[A[0].length][A.length];
for (int i = 0; i < B.length; i++) {
for (int j = 0; j < B[i].length; j++) {
B[i][j] = A[j][i];
}
}
return B;
}
/**
* Print 2 d.
*
* #param mat the mat
*/
public static void print2D(int mat[][]) {
// Loop through all rows
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println(" ");
}
}
}
Output:
1 2 3
5 6 7
9 10 11
12 13 14
1 5 9 12
2 6 10 13
3 7 11 14
Here is a general solution. It will transpose any matrix, including a ragged one.
List<int[][]> demo = List.of(
new int[][] { { 1 }, { 2, 3, 4 }, { 5, 6 } },
new int[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } },
new int[][] { { 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9, 10 } });
for (int[][] arr : demo) {
System.out.println("Original");
for (int[] b : arr) {
System.out.println(Arrays.toString(b));
}
System.out.println("Transposed");
for (int[] b : transpose(arr)) {
System.out.println(Arrays.toString(b));
}
System.out.println();
}
prints
Original
[1]
[2, 3, 4]
[5, 6]
Transposed
[1, 2, 5]
[3, 6]
[4]
Original
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Transposed
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
Original
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
Transposed
[1, 6]
[2, 7]
[3, 8]
[4, 9]
[5, 10]
first, find the resulting number of rows, which is the maximum number of columns in the source matrix.
Then simply iterate thru the matrix, creating the new rows and copying the appropriate values of each column to their new row. Since the rows may be of different lengths, a check is made to ensure the value exists in the current row.
then copy that row of the proper length to the transposed row.
public static int[][] transpose(int[][] nums) {
int maxRows = nums[0].length;
for (int[] ar : nums) {
maxRows = Math.max(maxRows, ar.length);
}
int[][] trans = new int[maxRows][];
for (int r = 0; r < maxRows; r++) {
int[] row = new int[nums.length];
int cc = 0;
for (int c = 0; c < row.length; c++) {
if (r < nums[c].length) {
row[cc++] = nums[c][r];
}
}
trans[r] = Arrays.copyOf(row, cc);
}
return trans;
}
prints

Combine two int arrays without duplicates using only for loops

This is a pretty beginner assignment, and I would love to get some help with my code.
I need to combine two integer arrays into one using for loops, and make sure I don't have duplicates. Anything I googled is pretty over complicated and uses all sorts of built in methods.
Here is my code:
static void SumArray(){
int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
int[] merged = new int[array1.length + array2.length];
int pos = 0;
for (int i = 0; i < array1.length; i++) {
merged[pos] = array1[i];
pos++;
}
for (int j = merged[pos]; j < array2.length; j++) {
if (merged[pos] != array2[j]) {
merged[pos] = array2[j];
pos++;
}
}
System.out.println(Arrays.toString(merged));
Ultimately, it should return {1, 2, 3, 4, 5}. Instead, currently it returns 1, 2, 3, 3, 4, 5.
I would like to know why my if doesn't work. It should skip the 3 since it is already in there.
What am I missing?
Thanks :)
Edit:
Thanks guys, this is what I ended up doing, which still isn't good since I'm not checking for duplicates in the first loop that goes over the first array:
static void SumArray(){
int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
int arrSize = array1.length + array2.length;
int[] merged = new int[arrSize];
int pos = 0;
int counter = 0;
for (int i = 0; i < array1.length; i++) {
merged[pos] = array1[i];
pos++;
}
for (int j = merged[pos]; j < array2.length; j++) {
if (merged[pos-1] != array2[j]) {
merged[pos] = array2[j];
pos++;
counter++;
}
}
int[] newMerged = new int[arrSize - counter + 1];
System.arraycopy(merged, 0, newMerged, 0, newMerged.length);
System.out.println(Arrays.toString(newMerged));
}
I'm sure I'll find a way.
I would like to know why my if doesn't work.
Because merged[pos] is always 0, because you've never assigned any other value to it in your code. Array entries are initialized to zero when you create the array.
You can't just check one entry to know whether to add a value from array2. You have to check all of the entries you've written, with a nested loop within your second for loop. Only add a new entry if it isn't already there.
Note that you'll also need to either check ahead of time how many duplicates there are so you know that merged should only be 5 entries long, or you need to re-create merged later when you know how long it should be. Otherwise, your end result will be {1, 2, 3, 4, 5, 0}, not {1, 2, 3, 4, 5}.
because of the "pos++" in the first for loop as you are using as start index of j in the second loop.
Your 3 is in the index 2 and you are comparing it to index 3, which never be equal
here is your answer:
int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
int[] merged = new int[array1.length + array2.length];
int pos = 0,i=0, j;
Set<Integer> intSet = new HashSet();
for (i = 0; i < array1.length; i++) {
if(!intSet.contains(array1[i])) {
merged[pos] = array1[i];
intSet.add(Integer.valueOf(i));
pos++;
}
}
for (j= 0, pos = pos-1; j < array2.length; ) {
if(!intSet.contains(Integer.valueOf(array2[j]))) {
merged[pos] = array2[j];
intSet.add(Integer.valueOf(i));
pos++;
j++;
}
}
System.out.println(Arrays.toString(merged));
Here is solution for Java 8 and bigger version:
int[] first = { 1, 2, 3 };
int[] second = { 3, 4, 5 };
int[] merged = Stream.of(first, second)
.flatMapToInt(Arrays::stream)
.distinct()
.toArray();

How do I construct a fix-sized matrix from an array of numbers in Java?

Suppose I have an array of numbers
1, 2, 3, 4, 5, 6, 7, 8, 9
How do I construct a 3x3 matrix where the first row contains 1,2,3; the second row contains 4,5,6; the third row contains 7, 8, 9?
Essentially, I want to fill the numbers into the 3x3 matrix row by row.
In R, I can construct this matrix using this command:
matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3, ncol=3, byrow = TRUE)
How do I accomplish this in Java?
int arr[][] = { {1,2,3}, {4,5,6}, {7,8,9} };
Initial the array :
int [][] numbers = new int [nrow][ncol]; // suppose 3X3
Assign each index to some integer number:
Scanner s = new Scanner(System.in);
for(int i = 0 ; i < nrow ; i++)
for(int j = 0 ; j < ncol; j++)
numbers[i][j] = s.nextInt();
And print the matrix :
for(int []n : numbers){
for(int i : n){
System.out.println(i);
}
System.out.println();
}

How do I generate 6 random numbers between 1 and 6 using Java?

I am encountering a problem generating 6 random numbers between 1 and 6 in Java. All the numbers have to be unique. When I enter kolon value 5, the arrays should be like this:
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
I don't want the program to generate the same two numbers. What is wrong here?
Relevant code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter row quantity: ");
int kolon = input.nextInt();
Integer[][] dizi_asil = new Integer[kolon][6];
for (int i = 0; i < kolon; i++) {
Integer[] dizi = new Integer[6];
for (int j = 0; j < 6; j++) {
dizi[j] = (int) ((Math.random() * 6) + 1);
for (int u = 0; u < 1; u++) {
for (int k = 0; k < j; k++) {
while (dizi[k] == dizi[j]) {
dizi[j] = (int) ((Math.random()* 6) + 1);
u++;
}
}
}
dizi_asil[i][j] = dizi[j];
}
Arrays.sort(dizi_asil[i]);
}
for (int i = 0; i < dizi_asil.length; i++) {
for (int k = 0; k < dizi_asil[i].length; k++) {
System.out.print(dizi_asil[i][k] + "\t");
}
System.out.println();
}
create a list containing 1 to 6. then shuffle it using Collection.shuffle. Then you will get random unique number
This is an easy way:
List<Integer> list = Arrays.asList(1,2,3,4,5,6);
Collections.shuffle(list);
// you can convert it to an array if you need to.
A very simple fix - replace u++; with u--;. ++ will make the loop stop, -- will make it carry on.
Though I'd suggest something more like the below. I hope it's easy enough to understand.
Integer[] dizi = new Integer[6];
for (int j = 0; j < 6; j++)
{
boolean isValid;
do
{
dizi[j] = (int) ((Math.random() * 6) + 1);
isValid = true;
for (int k = 0; isValid && k < j; k++)
if (dizi[k] == dizi[j])
isValid = false;
}
while (!isValid);
dizi_asil[i][j] = dizi[j];
}
I'd also suggest the Random class, which has a nextInt(int) method, which is better than (int) ((Math.random() * 6) + 1).
But shuffling is probably a faster way to do it. Either use the API like one of the other answers or look into the Fisher-Yates / Knuth shuffle for an easy shuffle algorithm.
Try Collections.shuffle(list);
List<Integer> list = new ArrayList<Integer>();
for(int i = 1; i<7 ; i++)
list.add(i);
Or you can do :
List<Integer> list = Arrays.asList(1,2,3,4,5,6)
Collections.shuffle(list);
Iterate the list and get unique value each time.
A much shorter way is to use shuffle as many have mentioned already.
public static void main(String... ignored) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter row quantity: ");
List<Integer> rolls = Arrays.asList(1, 2, 3, 4, 5, 6);
for (int i = 0, rows = input.nextInt(); i < rows; i++) {
Collections.shuffle(rolls);
System.out.println(rolls);
}
}
if you run it you get something like
Please enter row quantity:
5
[5, 6, 3, 2, 4, 1]
[5, 4, 3, 6, 2, 1]
[6, 4, 2, 3, 5, 1]
[3, 1, 6, 2, 5, 4]
[4, 1, 6, 3, 5, 2]
Imports:
import acm.util.RandomGenerator;
private RandomGenerator rgen = RandomGenerator.getInstance();
Actually picking:
randnum = rgen.nextInt(1, 6);
This picks a random number between 0 and 5. You can just do this for 1 through 6:
randnum = rgen.nextInt(2, 7);
Or:
randnum = rgen.nextInt(1, 6);
randnum++;

How to get unique items from an array?

I am Java beginner, I found a few topics regarding this theme, but none of them worked for me.
I have an array like this:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
and I would need to get this output:
1, 2, 3, 4, 5
Every item from that array just once.
But how to get it?
The simpliest solution without writing your own algorithm:
Integer[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> uniqKeys = new TreeSet<Integer>();
uniqKeys.addAll(Arrays.asList(numbers));
System.out.println("uniqKeys: " + uniqKeys);
Set interface guarantee uniqueness of values. TreeSet additionally sorts this values.
You can use a Set<Integer> and save lot of time since it holds unique elements. If you aren't allowed to use any class from Java Collections, sort the array and count the unique elements. You can sort the array manually or use Arrays#sort.
I'll post the Set<Integer> code:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for(int x : numbers) {
setUniqueNumbers.add(x);
}
for(Integer x : setUniqueNumbers) {
System.out.println(x);
}
Note that I prefer to use LinkedHashSet as Set implementation since it maintains the order of how the elements were inserted. This means, if your array was {2 , 1 , 2} then the output will be 2, 1 and not 1, 2.
In Java 8:
final int[] expected = { 1, 2, 3, 4, 5 };
final int[] numbers = { 1, 1, 2, 1, 3, 4, 5 };
final int[] distinct = Arrays.stream(numbers)
.distinct()
.toArray();
Assert.assertArrayEquals(Arrays.toString(distinct), expected, distinct);
final int[] unorderedNumbers = { 5, 1, 2, 1, 4, 3, 5 };
final int[] distinctOrdered = Arrays.stream(unorderedNumbers)
.sorted()
.distinct()
.toArray();
Assert.assertArrayEquals(Arrays.toString(distinctOrdered), expected, distinctOrdered);
//Running total of distinct integers found
int distinctIntegers = 0;
for (int j = 0; j < array.length; j++)
{
//Get the next integer to check
int thisInt = array[j];
//Check if we've seen it before (by checking all array indexes below j)
boolean seenThisIntBefore = false;
for (int i = 0; i < j; i++)
{
if (thisInt == array[i])
{
seenThisIntBefore = true;
}
}
//If we have not seen the integer before, increment the running total of distinct integers
if (!seenThisIntBefore)
{
distinctIntegers++;
}
}
Below code will print unique integers have a look:
printUniqueInteger(new int[]{1, 1, 2, 1, 3, 4, 5});
static void printUniqueInteger(int array[]){
HashMap<Integer, String> map = new HashMap();
for(int i = 0; i < array.length; i++){
map.put(array[i], "test");
}
for(Integer key : map.keySet()){
System.out.println(key);
}
}
Simple Hashing will be far efficient and faster than any Java inbuilt function:
public class Main
{
static int HASH[];
public static void main(String[] args)
{
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
HASH=new int[100000];
for(int i=0;i<numbers.length;i++)
{
if(HASH[numbers[i]]==0)
{
System.out.print(numbers[i]+",");
HASH[numbers[i]]=1;
}
}
}
}
Time Complexity: O(N), where N=numbers.length
DEMO
public class Practice {
public static void main(String[] args) {
List<Integer> list = new LinkedList<>(Arrays.asList(3,7,3,-1,2,3,7,2,15,15));
countUnique(list);
}
public static void countUnique(List<Integer> list){
Collections.sort(list);
Set<Integer> uniqueNumbers = new HashSet<Integer>(list);
System.out.println(uniqueNumbers.size());
}
}
In JAVA8, you can simply use
stream()
and
distinct()
to get unique elements.
intArray = Arrays.stream(intArray).distinct().toArray();
There is an easier way to get a distinct list:
Integer[] intArray = {1,2,3,0,0,2,4,0,2,5,2};
List<Integer> intList = Arrays.asList(intArray); //To List
intList = new ArrayList<>(new LinkedHashSet<>(intList)); //Distinct
Collections.sort(intList); //Optional Sort
intArray = intList.toArray(new Integer[0]); //Back to array
Outputs:
1 2 3 0 0 2 4 0 2 5 2 //Array
1 2 3 0 0 2 4 0 2 5 2 //List
1 2 3 0 4 5 //Distinct List
0 1 2 3 4 5 //Distinct Sorted List
0 1 2 3 4 5 //Distinct Sorted Array
See jDoodle Example
You could do it like this:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
ArrayList<Integer> store = new ArrayList<Integer>(); // so the size can vary
for (int n = 0; n < numbers.length; n++){
if (!store.contains(numbers[n])){ // if numbers[n] is not in store, then add it
store.add(numbers[n]);
}
}
numbers = new int[store.size()];
for (int n = 0; n < store.size(); n++){
numbers[n] = store.get(n);
}
Integer and int can be (almost) used interchangeably. This piece of code takes your array "numbers" and changes it so that all duplicate numbers are lost. If you want to sort it, you can add Collections.sort(store); before numbers = new int[store.size()]
I don't know if you've solved your issue yet, but my code would be:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
int x = numbers.length;
int[] unique = new int[x];
int p = 0;
for(int i = 0; i < x; i++)
{
int temp = numbers[i];
int b = 0;
for(int y = 0; y < x; y++)
{
if(unique[y] != temp)
{
b++;
}
}
if(b == x)
{
unique[p] = temp;
p++;
}
}
for(int a = 0; a < p; a++)
{
System.out.print(unique[a]);
if(a < p-1)
{
System.out.print(", ");
}
}
String s1[]= {"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee"};
int c=0;
for(int i=0;i<s1.length;i++)
{
for(int j=i+1;j<s1.length;j++)
{
if(s1[i]==(s1[j]) )
{
c++;
}
}
if(c==0)
{
System.out.println(s1[i]);
}
else
{
c=0;
}
}
}
}
To find out unique data:
public class Uniquedata
{
public static void main(String[] args)
{
int c=0;
String s1[]={"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee","hello","hello","hybernet"};
for(int i=0;i<s1.length;i++)
{
for(int j=i+1;j<s1.length;j++)
{
if(s1[i]==(s1[j]) )
{
c++;
s1[j]="";
}}
if(c==0)
{
System.out.println(s1[i]);
}
else
{
s1[i]="";
c=0;
}
}
}
}
you can use
Object[] array = new HashSet<>(Arrays.asList(numbers)).toArray();
Here is my piece of code using counting sort (partially)
Output is a sorted array consiting of unique elements
void findUniqueElementsInArray(int arr[]) {
int[] count = new int[256];
int outputArrayLength = 0;
for (int i = 0; i < arr.length; i++) {
if (count[arr[i]] < 1) {
count[arr[i]] = count[arr[i]] + 1;
outputArrayLength++;
}
}
for (int i = 1; i < 256; i++) {
count[i] = count[i] + count[i - 1];
}
int[] sortedArray = new int[outputArrayLength];
for (int i = 0; i < arr.length; i++) {
sortedArray[count[arr[i]] - 1] = arr[i];
}
for (int i = 0; i < sortedArray.length; i++) {
System.out.println(sortedArray[i]);
}
}
Reference - discovered this solution while
trying to solve a problem from HackerEarth
If you are a Java programmer, I recommend you to use this.
It will work.
public class DistinctElementsInArray {
//Print all distinct elements in a given array without any duplication
public static void printDistinct(int arr[], int n) {
// Pick all elements one by one
for (int i = 0; i < n; i++) {
// Check if the picked element is already existed
int j;
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;
// If not printed earlier, then print it
if (i == j)
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args) {
int array[] = { 4, 5, 9, 5, 4, 6, 6, 5, 4, 10, 6, 4, 5, 3, 8, 4, 8, 3 };
// 4 - 5 5 - 4 9 - 1 6 - 3 10 - 1 3 - 2 8 - 2
int arrayLength = array.length;
printDistinct(array, arrayLength);
}
}
public class DistinctArray {
public static void main(String[] args) {
int num[]={1,2,5,4,1,2,3,5};
for(int i =0;i<num.length;i++)
{
boolean isDistinct=false;
for(int j=0;j<i;j++)
{
if(num[j]==num[i])
{
isDistinct=true;
break;
}
}
if(!isDistinct)
{
System.out.print(num[i]+" ");
}
}
}
}

Categories