Basic array - Java - java

I need to make 2 arrays called A and B, both of type int with size 100. Each index should be a random number between 0 and 100 inclusive and then compare both arrays, and say how many times 2 of the same number appeared in both arrays.
This is what I have so far
int count = 0;
int [] A = new int [100];
int [] B = new int [100];
for(int i = 0; i < A.length; i++){
A [i] = (int)(Math.random()*101);
System.out.println("Array A: " + i);
}
for(int i = 0; i < B.length; i++){
B [i] = (int)(Math.random()*101);
System.out.println("Array B: " + i);
}
if(A [i] == B [i]){
count++;
}
I'm not sure how to show how many times 2 of the same number appeared in both arrays.

You need to loop through both of the arrays:
int count = 0;
int [] A = new int [100];
int [] B = new int [100];
for(int i = 0; i < A.length; i++){
A [i] = (int)(Math.random()*101);
System.out.println("Array A: " + i);
}
for(int i = 0; i < B.length; i++){
B [i] = (int)(Math.random()*101);
System.out.println("Array B: " + i);
}
// Loop through the first array
for(int i = 0; i < A.length; i++) {
// For each element in the first array, loop through the whole second one
for (int j = 0; j < B.length; j++) {
// If it's a match
if(A[i] == B[j])
count++;
}
}
System.out.println("Count: " + count);

Alternatively, if you don't need the 2 arrays, you can simply do:
int count = Random.ints(100, 0, 101).boxed().collect(toSet())
.retainAll(Random.ints(100, 0, 101).boxed().collect(toSet()))
.size();

You started off nicely, but you need a nested for-loop to check each of the indexes.
ALSO-- make sure that in your arrays you print out A[i] and B[i] otherwise you're just printing out the number of the index as opposed to the number inside the index.
int count = 0;
int[] A = new int[100];
int[] B = new int[100];
//Create the first array
for (int i = 0; i < A.length; i++) {
A[i] = (int)(Math.random() * 101);
System.out.println("Array A: " + A[i]);
}
//Create the second array
for (int i = 0; i < B.length; i++) {
B[i] = (int)(Math.random() * 101);
System.out.println("Array B: " + B[i]);
}
//Check the indexes and make sure they are all compared-- 10,000 comparisons are made
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
if(A[i] == B[j])
count++;
}
}
Hopefully that posted correctly... first time posting code on this website, but I hope that I was of help!
Keep in mind if the same number is being posted twice, you're going to get counts over 100.
Good luck!

Related

Sum the elements of 2D array

I made 2D arrray which prints some random elements.
Now i need a method which calculates the sum of that elements but just elements below the main diagonal.
Here is my code...
class Init {
public static void main(String[] args) {
int n = 0;
int m = 0;
int aray[][];
Random random = new Random();
Scanner tastatura = new Scanner(System.in);
int[][] array = new int[n][m];
n = tastatura.nextInt();
m = tastatura.nextInt();
array = new int[n][m];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = random.nextInt(20);
}
}
for (int[] a : array) {
System.out.println(Arrays.toString(a));
}
}
}
I did it like this... Now i can sum, but when i try to multyply same numbers i am geting 0 Why is that?
Scanner scanner = new Scanner(System.in);
System.out.print("Unesite duzinu kolona i redova : ");
int rows = scanner.nextInt();
int columns = rows;
int[][] matrix = new int[rows][rows];
Random random = new Random();
System.out.println("Nasumicni/random brojevi su :");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = random.nextInt(20);
}
}
for (int[] a : matrix) {
System.out.println(Arrays.toString(a));
}
//here is the logic which sum those elements
int sum = 0;
for (int i = 1; i < rows; i++) {
for (int j = i - 1; j >= 0; j--) {
sum = sum + matrix[i][j];
}
}
System.out.println("\nMatrix is : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("Proizvod elemenata ispod glavne dijagonale je: " + sum);
What about this?
int s = 0;
for(int i = 1; i < m; ++i)
for(int j = 0; j < i; ++j)
s += a[i][j];
This selectively loops through the elements below the main diagonal and sums them up, without looping through the entire matrix and making it lengthier.
The main diagonal of a matrix consists of those elements that lie on the diagonal that runs from top left to bottom right. But since you want those elements "below" the main diagonal, here is an algorithm I came up with for that.
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (i == j && (i + 1 < n))
{
int temp = i + 1;
while (temp < n)
{
sum += arr[temp][j];
temp++;
}
}
Also, you declare int[][] array multiple times. You need to declare it only once, after you get the values for n and m.
for(i=0;i
        for(j=0;j
        {
                if(j>i)
                    d1+=a[i][j];. // Above the diagon
                else
                    if(i>j)
                        d2+=a[i][j];. // Below the diagonal
        }
    

Trouble multiplying 2D arrays of different dimensions in Java

I've got the following code, I'm trying to get it to multiply array a by array b and produce array c. I've browsed several questions on here and for some reason I can't get the array to produce the correct results, I believe because it's not multiplying the right indices by one another. Any help would be greatly appreciated, as I am still trying to grasp how array multiplication works. Here is the code:
class Main
{
public static void main (String[] args)
{
int[][]a =
{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
//print array a
};
for(int i = 0; i < a[0].length-1; i++)
{
for(int j = 0; j < a[0].length; j++)
{
System.out.print(a[i][j] + " ");
}
System.out.println();
}
int[][]b =
{
{-1,-2,-3},
{-4,-5,-6},
{-7,-8,-9},
{-10,-11,-12},
};
System.out.println();
//print array b
for(int i = 0; i < b.length; i++)
{
for(int j = 0; j < b.length-1; j++)
{
System.out.print(b[i][j] + " ");
}
System.out.println();
}
System.out.println();
int[][]c = new int[a.length][b[0].length];
if(b.length == a[0].length)
{
for(int i = 0; i < a.length; i++)
{
for (int j = 0; j < b[0].length; j++)
{
for (int k = 0; k < a[0].length; k++)
{
c[i][j] = a[i][k]*b[k][j];
}
}
}
}
else
{
System.out.println("Dimension requirements not satisfied for accurate calculation");
}
for(int i = 0; i < c.length; i++)
{
for(int j = 0; j < c.length; j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
Change c[i][j] = a[i][k]*b[k][j]; to c[i][j] += a[i][k]*b[k][j];
The answer by #Jeffrey Chen is correct because in the matrix multiplication each row of the first matrix multiply by each column of second matrix
In your case row 1 of matrix a is 1, 2, 3, 4
Column 1 of matrix b is -1, -4, -7, -10
So the answer is (1*-1)+(2*-4)+(3*-7)+(4*-10)
= -1-8-21-40 = -70
Then the first row of matrix a multiply by second column of matrix b
(1*-2)+(2*-5)+(3*-8)+(4*-11)
= -2-10-24-44 = -80
And so on
So the following is correct
c[i][j] += a[i][k] * b[k][j];

Merging two arrays and short that merged array

I got homework "Take two given array(already sorted up, for example {1,2,3}) and create a new array contains both arrays and then sort him up", we have a function to sort up arrays so it's not the problem, however it gets a little bit complex to me, here is my code:
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int[] a = new int[3];
int[] b = new int[5];
Help_arr.scan(a);
Help_arr.scan(b);
Help_arr.print(peula(a, b));
}
public static int[] peula(int[] a1, int[] b1) {
int[] c = new int[a1.length + b1.length];
for (int i = 0; i < a1.length; i++)
c[i] = a1[i];
for (int i = a1.length; i < c.length; i++){
c[i] = b1[i];
}
Help_arr.sortup(c);
return c;
}
Functions used from Help_arr class:
1) Scan an array:
public static void scan(int[] arr1) {
for (int i = 0; i < arr1.length; i++) {
System.out.println("Enter number" + (i + 1));
arr1[i] = in.nextInt();
}
}
2) Print an array:
public static void print(int[] arr1) {
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i] + " ");
}
}
3) Sort up an array:
public static void sortup(int[] arr1) {
int i, mini, temp, j;
for (j = 0; j < arr1.length; j++) {
mini = j;
for (i = j; i < arr1.length; i++) {
if (arr1[i] < arr1[mini])
mini = i;
}
temp = arr1[j];
arr1[j] = arr1[mini];
arr1[mini] = temp;
}
}
I get an error in the line c[i]=b1[i]; the array is going out of index bounds but I followed the code and this for will run until i=7 as the c.length is 8 and it is possible. But maybe I am missing something, here is the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at arrays.PgRonTargilMivhan.peula(PgRonTargilMivhan.java:21)
at arrays.PgRonTargilMivhan.main(PgRonTargilMivhan.java:13)
The issue is with this code:
for (int i = a1.length; i < c.length; i++){
c[i] = b1[i];
here b1 index should start with 0 but you are starting with a1.length. You should have a separate index for b1 or use b1[i-a1.length].
Please find the logic ..
you were using 'i' index for array b is the problem.
Solution is below. Good luck
int[] c = new int[a.length + b.length];
int i = 0;
for (i = 0; i < a.length; i++)
c[i] = a[i];
for (int j = 0; j < b.length; j++)
c[i] = b[j];
}

multiplication of 2-dimensional array java

I want to enter 2 dimensional arrays by joptionpane and display the multiplication of it by java,
I tried do this but I don't no why the result always is (0 0 0),I think that the result arrays is empty! could anyone help me ....!!??
System.out.print("can not multiply");
}
public static double[][] multiplyMatrix(double[][] x, double[][] z) {
double[][] result = new double[x.length][z[0].length];
for (int i = 0; i < x.length; i++)
for ( int j = 0; j <z[0].length; j++){
result[i][j]=0;
for (int k = 0; k < z.length; k++)
result[i][j] += x[i][k] * z[k][j];}
return result;
}
You populate your A array in both of your for loops. You have to populate B in the second for loop.
double[][] B = new double[n2][m2];
int k;
int l;
for (k = 0; k < n2; k++) {
for (l = 0; l < m2; l++) {
String s1 = JOptionPane.showInputDialog("Enter B" + "[" + (k) + (l) + "]" + " element ");
//A[k][l] = Integer.parseInt(s1); //This should be populating B
B[k][l] = Integer.parseInt(s1); //Change it to this
}
}
After fixing that issue, you still have some bugs in your multiplication method. But now that you actually get a result array, you can debug it pretty easily.
Hope this helps.

How to count 1st duplicates value in array in Java

I have taken array int[] a = {33,33,5,5,9,8,9,9}; In this array so many values are duplicates means 33 comes twice & 5 also comes twice & 9 comes three times.
But I want to count the first value which is duplicate means 33 is first value which comes twice so answer would be 2.
I try:
public class FindFirstDuplicate
{
public static void main(String[] args) {
int c=0;
int[] a = {33,33,5,5,9,8,9,9};
outerloop:
for(int i = 0; i < a.length; i++)
{
for(int j = i+1; j< a.length; j++)
{
if(a[i] == a[j])
{
System.out.println(a[i]); //Duplicate value
c++;
break outerloop;
}
}
}
System.out.print("Count: "+c);
}
}
Output:
33
1
public class HelloWorld{
public static void main(String[] args) {
int[] a = {33,33,5,5,9,8,9,9};
for(int i = 0; i < a.length; i++)
{
int c=1; // we already found one.
// and we initialize this counter inside the loop,
// so that it is reset for each new starting number.
for(int j = i+1; j< a.length; j++) // we're starting from next number (reason we start with c=1)
{
if(a[i] == a[j])
c++;
}
if(c > 0) {
System.out.println("First uplicate value: "+ a[i] + " Count: " + c);
break; // we have to break out of the outer loop,
// so the inner loop can finish counting duplicates
}
}
}
}
Try something like:
int[] numbers = {33, 33, 5, 5, 9, 8, 9, 9};
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i< numbers.length; i++) {
if (!set.add(number[i])) {
System.out.println("first duplicate is " + number[i] + " and index is " + i);
break;
}
}
If the values in the array are non-negative and reasonably small, you can use a BitSet to store whether or not you have seen a value previously:
BitSet bits = new BitSet();
for (int i = 0; i < numbers.length; ++i) {
if (bits.get(numbers[i])) {
System.out.println("first duplicate at " + i + ": " + numbers[i]);
break;
}
bits.set(numbers[i]);
}
You could try this out:
int[] a = {33,33,5,5,9,8,9,9};
Integer[] uniques = new Integer[a.length];
Integer[] counts = new Integer[a.length];
int len = 0;
for(int num : a){
boolean matched = false;
for(int i = 0; i < len; i++){
if(num == uniques[i].intValue()){
matched = true;
counts[i] = new Integer(counts[i]+1);
break;
}
}
if(!matched){
uniques[len] = new Integer(num);
counts[i] = new Integer(1);
len++;
}
}
for(int i = 0; i < len; i++){
if(counts[i].intValue() > 1){
System.out.println("first duplicate is " + uniques[i] + " and number of times it appears " + counts[i]);
break;
}
}
In your code you exit both loops after the first duplicate is found, so any other occurences of the element would be ignored.
Also you start with c = 0. When you get to the second occurence, c will be incremented and be 1, not 2.
To count all elements simply change the loop condition of the outer loop and remove the break:
int c = 1;
int i;
for(i = 0; (c == 1) && (i < a.length); i++)
{
for(int j = i+1; j < a.length; j++)
{
if(a[i] == a[j])
{
c++;
}
}
}
System.out.println(a[i]); //Duplicate value
System.out.print("Count: "+c); // maybe do something else, if c == 1 (no duplicates)???
However SMA's answer describes a more performant way (for arbitrary input arrays) of finding the first duplicate. Once you found the second occurence of the first duplicate, you'd only need to count the number of occurences in the rest of the array to get the final count.

Categories