Find duplicated elements in a matrix - java

Introduction
I'm doing some homework where we are tasked for making a game of finding pairs.
I made a matrix and filled it with letters as such:
Display
----------------
C H F E
G F D D
E C H B
A B G A
Right now I'm currently testing the display method which uses an empty matrix and fills it with the given input (row_1, col_1, row_2, col_2, gameMatrix)
Problem
While creating a "cheat/test function" to test my display method. I encounter some trouble with finding the position of both A's (or any other letter).
This is my try at such method:
Code
public static void PlayMeBoi(String[][] gameMatrix)
{
int row_1 = 0;
int col_1 = 0;
int row_2 = 0;
int col_2 = 0;
for (int i = 0; i < gameMatrix.length; i++)
{
for (int j = 0; j < gameMatrix.length; j++)
{
if ("A".equals(gameMatrix[i][j]))
{
row_1 = i;
col_1 = j;
break;
}
}
}
for (int i = (row_1+1); i < gameMatrix.length; i++)
{
for (int j = (col_1+1); j < gameMatrix.length; j++)
{
if ("A".equals(gameMatrix[i][j]))
{
row_2 = i;
col_2 = j;
break;
}
}
}
System.out.println("First " + gameMatrix[row_1][col_1] + " at " + " [ " + row_1 + " ] " + "," + " [ " + col_1 + " ] ");
System.out.println("Second " + gameMatrix[row_1][col_1] + " at " + " [ " + row_2 + " ] " + "," + " [ " + col_2 + " ] ");
Turn(row_1, col_1, row_2, col_2, gameMatrix);
}
Notes about the code
I'm working with String not char
Turn is the function which evaluates if a letter equals a letter (if "A".equals("A"))
The (row_1+1) and (col_1+1) it's my thought at "if I haven't found my letter previously, then the second 'for' will handle the rest of the matrix)
gameMatrix is the matrix where all the letters are loaded
Question
I want to be able to find the position of both "A" or any other letter inside the matrix. As of now, I'm not getting my desired result with my current idea
Feel free to comment about the code as much as you can. I might post it on GitHub later on for those who are interested or find anything useful in it.
Thanks for the interest in this question.

The second for is wrong. let's look at your example matrix:
C H F E
G F D D
E C H B
A B G A
If you're looking for the value D you'll find it first at row = 1 and col = 2. then in the second for you only runs from row = 2 and col = 3 which means in practice you'll iterate only over the right down cells from the position you found, which in this example will result in only 2 cells instead of 9 (marked in *):
C H F E
G F D D
E C H *B*
A B G *A*
So in the second for what you should do is continue the search from the same row and the next column:
for (int i = row_1; i < gameMatrix.length; i++)
{
// In the first row starting from the next cell, in the next rows start
// from column 0
int j = i == row_1 ? col_1 + 1 : 0;
for (; j < gameMatrix.length; j++)
{
if ("A".equals(gameMatrix[i][j]))
{
row_2 = i;
col_2 = j;
break;
}
}
}

if I haven't found my letter previously, then the second 'for' will
handle the rest of the matrix
Correct, but what exactly is the rest of the matrix?
If the 1st A is found in row = 1 and col = 1, is the rest of the matrix every item with indices > 1. This would leave out items with indices (1,2) and (2,1) and (1,3) etc.
There are other issues also.
When you put a break inside a nested loop it only breaks form the nested loop and not the outer.
Here's a solution I came up with, maybe it's not optimal but I think it works:
public static void PlayMeBoi(String[][] gameMatrix) {
int row_1 = -1;
int col_1 = -1;
int row_2 = -1;
int col_2 = -1;
boolean found = false;
for (int i = 0; i < gameMatrix.length; i++) {
if (found) break;
for (int j = 0; j < gameMatrix[0].length; j++) {
if ("A".equals(gameMatrix[i][j])) {
row_1 = i;
col_1 = j;
found = true;
break;
}
}
}
if (!found) {
System.out.println("Not Found");
return;
}
found = false;
for (int i = 1; i < gameMatrix.length; i++) {
if (found) break;
for (int j = 1; j < gameMatrix[0].length; j++) {
if (i * gameMatrix[0].length + j > row_1 * gameMatrix[0].length + col_1) {
if ("A".equals(gameMatrix[i][j])) {
row_2 = i;
col_2 = j;
found = true;
break;
}
}
}
}
System.out.println("First " + gameMatrix[row_1][col_1] + " at " + " [ " + row_1 + " ] " + "," + " [ " + col_1 + " ] ");
if (!found) {
System.out.println("Second Not Found");
return;
}
System.out.println("Second " + gameMatrix[row_1][col_1] + " at " + " [ " + row_2 + " ] " + "," + " [ " + col_2 + " ] ");
}

Related

Calculate the number of pyramid

I'm trying to calculate the sum of the numbers in my pyramid in java. For this, mathematical rule is 2+5+8+9. I mean first row+first number of second row+ second number of third row like that.
int[] numbers = { 2,5,7,1,8,3,6,0,9,4 };
System.out.println(" " + numbers[0]);
System.out.println(" " + numbers[1] + " " + numbers[2]);
System.out.println(" " + numbers[3] + " " + numbers[4] + " " + numbers[5]);
System.out.println("" + numbers[6] + " " + numbers[7] + " " + numbers[8] + " " + numbers[9]);
For example:
2
5 7
1 8 3
6 0 9 4
How can I calculate 2+5+8+9 in Java?
The simplest way of calculating 2+5+8+9 is using Java build-in feature:
int result = 2+5+8+9;
You should construct your pyramid as a 2D array.
int[] numbers = { 2,5,7,1,8,3,6,0,9,4 };
int addedElements = 0;
int nextSize = 1;
ArrayList<int[]> pyramid = new ArrayList<>();
while(addedElements< numbers.size()) {
int[] level = new int[nextSize++];
for (int i = 0; i < nextSize - 1; i++) {
level[i] = numbers[addedElements++];
}
}
int result = 0;
//add maximum of each `int[]` in pyramid.
for (int[] array : pyramid) {
int currentMax = array[0];
for (int i = 0; i < array.size(); i++) {
if (array[i] > currentMax) {
currentMax = array[i];
}
result+=currentMax;
}
System.out.println(result);
Try the follwoing code :
int[] numbers = { 2,5,7,1,8,3,6,0,9,4 };
int index = 1;
int number = 2;
int result = numbers[0];
while (index < numbers.length) {
result += numbers[index + number -2];
index += number;
number += 1;
}
System.out.println(result);
But the whole whing would be much easier and clearer if you just put your pyramide into a 2 dimensional array.
int[][] numbers = { {2},
{5,7},
{1,8,3},
{6,0,9,4} };
int result = numbers[0][0];
for (int i = 1; i < numbers.length; i++) {
result += numbers[i][i-1];
}
System.out.println(result);

How to calculate parenthesis

I want to calculate the coefficients of x^i(and the last number) resulted from calculating (x+i1)*(x+i2)*....*(x+in), where in is integer.
Having for instance, (x-1)(x-3)=x^2-4x+3, I calculate the coefficients like this:
x^2's is always 1
x's is i1+i2
and the last number is `i1*i2`
The problem comes when I have >2 parenthesis. I will get (grade 2 poly)*( grade 1 poly) and the algorithm that I described doesn't work, because there will be 3 coef. in the first parenthesis and my algorithm works only for 2. Basicly, I am looking for a generalization. What algorithm can I use, or is there any Java library or function to use?
the easiest way to do this is to repeatedly multiply by each additional term.
assuming you have a double[] coe where coe[j] is the ij in your example and you have a term where in=nextTerm:
double[] multiply(double[] coe, double nextTerm){
double[] product=Arrays.copyof(coe,coe.length+1);
for(int i=0;i<coe.length;++i)
product[i+1]+=nextTerm*coe[i]
return product;
}
with some modifications this can be used for terms of the form ax+b.
Did it after a few hours of hard work. Time to get a beer. Here is the code, feel free to use it.
private static int[] S_desfaparanteze(int[] poli) {
int size = poli.length;
List<Integer> rez = new ArrayList<>();
List<Integer> rezc = new ArrayList<>();
// rez.add(1); adauga 1 in coada
//rez.set(0, 2); pune 2 pe pozitia 0
//rez.size() dimensiunea
//rez.get(1) afiseaza elementul pe pozitia 1
//pentru fiecare paranteza aka element al lui poli
for (int i = 0; i < size; i++) {
//pas curent
//adaug un 0 la sfarsit
rez.add(0);
//fac o copie a vectorului rezultat
rezc = new ArrayList(rez);
/*System.out.println("rez initial");
for (int s : rez) {
System.out.print(s + " ");
}
System.out.println();
System.out.println("rezc initial");
for (int s : rezc) {
System.out.print(s + " ");
}
System.out.println();*/
/*System.out.println("primul element: " + rez.get(0));
System.out.println("primul element in copie: " + rezc.get(0));*/
//primul element e calculat diferit
rezc.set(0, rez.get(0) - poli[i]);
/*System.out.println("rez dupa calcularea primului element");
for (int s : rez) {
System.out.print(s + " ");
}
System.out.println();
System.out.println("rezc dupa calcularea primului element");
for (int s : rezc) {
System.out.print(s + " ");
}
System.out.println();*/
//calculez si restul elementelor
for (int j = 1; j < rez.size(); j++) {
//System.out.println("pe" + j + "pun" + rez.get(j) + "+" + rez.get(j - 1) + "*" + (-poli[i]));
rezc.set(j, rez.get(j) + rez.get(j - 1) * (-poli[i]));
}
//copii vectorul
rez = rezc;
/*System.out.println("la sfarsitul fiecarui pas, REZ");
for (int s : rez) {
System.out.print(s + " ");
}
System.out.println();
System.out.println("---------------------");*/
}
/*System.out.println("la final");
for (int s : rez) {
System.out.print(s + " ");
}*/
//convertesc arraylist la array simplu
int[] ret = new int[rez.size() + 1];
for (int j = 0; j < rez.size(); j++) {
ret[j + 1] = rez.get(j);
}
ret[0] = 1;
return ret;
}

Nested For Loop and specific array element searching

I have a question on the method and process of how to look at these generated arrays.
Basically I want to create an array of [a,b,c,(a+b+c)] and as well as a second array of [d,e,f,(d+e+f)] and if the third element in array1 and array2 are the same, display the arrays to strings.
int num = 10;
for(int a = 0; a < num; a++){
for(int b = 0; b < num; b++){
for(int c = 0; c < num; c++){
if(a<=b && b<=c){
arrayOne[0] = a;
arrayOne[1] = b;
arrayOne[2] = c;
arrayOne[3] = (a+b+c);
}
}
}
}
for(int d = 0; d < num; e++){
for(int e = 0; e < num; e++){
for(int f = 0; f < num; f++){
if(d<=e && e<=f){
arrayTwo[0] = d;
arrayTwo[1] = e;
arrayTwo[2] = f;
arrayTwo[3] = (f -(d+e));
}
}
}
}
as you can see I am beyond stump.I am not quite sure where i can get each iteration of the arrays and compare the values by matching the sums in each array and as well as displaying the respective array they are in. Thank you all in advanced.
If I understand your question correctly if a=1, b=3, c=4 and d=2, e=3, f=3 you'd like to print something along the lines of 1 + 3 + 4 = 8 = 2 + 3 + 3. First, what you're doing right now is creating two arrays like Floris described in the comment. What you want to do is store all the values in one array of arrays, as follows:
int max; \\ To determine the value of max see the edit below.
int array[][] = new int[max][num];
int index = 0;
for (int a=0; a < num; a++) {
for (int b=a; b < num; b++) {
for (int c=b; c < num; c++) {
array[index][0] = a;
array[index][1] = b;
array[index][2] = c;
array[index][3] = a + b + c;
index++;
}
}
}
for (int i = 0; i < max; i++) {
for (int j = i; j < max; j++) {
if (array[i][3] == array[j][3]) {
string outString = array[i][0] + " + " + array[i][1] + " + " + array[i][2] + " = " + array[i][3] + " = " + array[j][0] + " + " + array[j][1] + " + " + array[i][2];
System.out.println(outString);
}
}
}
You can see that I improved performance by starting b from a and c from b since you are throw out all the values where b < a or c < b. This also should eliminate the need for your if statement (I say should only because I haven't tested this). I needed to use an independent index due to the complexities of the triple nested loop.
Edit 2: Ignore me. I did the combinatorics wrong. Let An,k be the number of unordered sets of length k having elements in [n] (this will achieve what you desire). Then An,k = An-1,k + An,k-1. We know that An,1 = n (since the values are 0, 1, 2, 3, 4, ..., n), and A1,n = 1 (since the only value can be 11111...1 n times). In this case we are interested in n= num and k = 3 , so plugging in the values we get
A_num,3 = A_num-1,3 + A_num,2
Apply the equation recursively until you come to an answer. For example, if num is 5:
A_5,3 = A_4,3 + A_5,2
= A_3,3 + A_4,2 + A_4,2 + A_5,1
= A_3,3 + 2(A_4,2) + 5
= A_2,3 + A_3,2 + 2(A_3,2) + 2(A_4,1) + 5
= A_2,3 + 3(A_3,2) + 2(4) + 5
= A_1,3 + A_2,2 + 3(A_2,2) + 3(A_3,1) + 2(4) + 5
= 1 + 4(A_2,2) + 3(3) + 2(4) + 5
= 1 + 4(A_1,2) + 4(A_2,1) + 3(3) + 2(4) + 5
= 1 + 4(1) + 4(2) + 3(3) + 2(4) + 5
= 5(1) + 4(2) + 3(3) + 2(4) + 5
It looks like this may simplify to (num + (num - 1)(2) + (num - 2)(3) + ... + (2)(num - 1) + num) which is binomial(num, num) but I haven't done the work to say for sure.
int givenNumber = 10;
int []arrayOne = new int [4];
int []arrayTwo = new int [4];
int count = 0;
for ( int i = 0; i < givenNumber; i ++)
{
for ( int x = 0; x < givenNumber; x ++ )
{
for ( int a = 0; a < givenNumber; a++ ){
arrayOne[0] = (int)(a * java.lang.Math.random() + x);
arrayOne[1] = (int)(a * java.lang.Math.random() + x);
arrayOne[2] = (int)(a * java.lang.Math.random() + x);
arrayOne[3] = (int)(arrayOne[0]+arrayOne[1]+arrayOne[2]);
}
for ( int b = 0; b < givenNumber; b++ ){
arrayTwo[0] = (int)(b * java.lang.Math.random() + x);
arrayTwo[1] = (int)(b * java.lang.Math.random() + x);
arrayTwo[2] = (int)(b * java.lang.Math.random() + x);
arrayTwo[3] = (int)(arrayTwo[0]+arrayTwo[1]+arrayTwo[2]);
}
if (arrayOne[3] == arrayTwo[3])
{
for ( int a = 0; a < 2; a++ )
{
System.out.print(arrayOne[a] + " + ");
} System.out.print(arrayOne[2] + " = " + arrayOne[3] + " = ");
for ( int a = 0; a < 2; a++ )
{
System.out.print(arrayTwo[a] + " + ");
} System.out.print(arrayTwo[2]);
System.out.println("\n");
count += 1;
}
}
}
if (count == 0)
System.out.println(
"\nOops! you dont have a match...\n" +
"Please try running the program again.\n");

Creating multiplication table by looping in Java

I was tasked to make a multiplication table from 1-10 but I was not satisfied with my code, it seems to be long:
for (int i = 1; i <= 10; i++)
{
System.out.println("1x" + i + " = " + i + "\t" + "2x" + i + " = " + (2*i)
+ "\t" + "3x" + i + " = " + (3*i) + "\t" + "4x" + i + " = " + (4*i)
+ "\t" + "5x" + i + " = " + (5*i) + "\t" + "6x" + i + " = " + (6*i)
+ "\t" + "7x" + i + " = " + (7*i) + "\t" + "8x" + i + " = " + (8*i)
+ "\t" + "9x" + i + " = " + (9*i) + "\t" + "10x" + i + " = " + (10*i));
}
Output:
1x1 = 1 2x1 = 2
1x2 = 2 2x2 = 4
etc.
Try something like
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
System.out.println(i + "x" + j + "=" (i*j));
}
}
so you have an inner and an outer loop, controlling what you want multiplied and what you want it multiplied by.
To be more explicit you could (should?) rename i and j as multiplier and multiplicand
This will format the table how you have it in your example code, and uses two loops:
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print(i + "x" + j + "=" + (i * j) + "\t");
}
System.out.println();
}
The outer loop controls the rows in the multiplication table and the inner loop controls the columns in the multiplication table. System.out.println() signifies moving into a new row of the table
You could use two loops:
for (int i = 1; i <= 10; i++)
{
for (int j = i; j <= 10; j++)
{
System.out.println(i + "x" + j + "=" + (i*j));
}
}
for (int i = 1; i <= 10; i++)
{
for(int j=1; j<10; j++){
System.out.println(j+"x"+i+"="+(j*i)+"\t");
}
System.out.println("\n");
}
import java.util.Scanner;
public class TableMultiplication {
public static void main(String[] args) {
int table,count,total;
//Reading user data from console
Scanner sc = new Scanner(System.in);
//reading data for table
System.out.println("Enter Your Table:");
table = sc.nextInt();
//reading input for how much want to count
System.out.println("Enter Your Count to Table:");
count = sc.nextInt();
//iterate upto the user required to count and multiplay the table and store in the total and finally display
for (int i = 1; i < count; i++) {
total = table*i;
System.out.println(table+"*"+i+"="+total);
}//for
}//main
}//TableMultiplication
import java.util.Scanner;
public class P11 {
public static void main(String[] args) {
Scanner s1=new Scanner(System.in);
System.out.println("Enter a value :");
int n=s1.nextInt();
for(int i=1;i<=10;i++)
{
for(int j=1;j<=10;j++)
{
System.out.println(i+"x"+j+ "="+(i*j)+"\t");
}
}
}
}

Unable to get loop to check if a set of values passed through the loop is bigger than a certain value

I have a set of values stored in Map/HashMap. Then I did a triple for loop to compare the values. The values are compared this way: First get the values for 0-1 then compare it to a set of values that starts with 1-x [1-2, 1-3,...1-n]. IF and ONLY IF the value of (e.g 0-1) is BIGGER THAN all the other values in the 1-x set value (e.g: 1-2, 1-3,...1-n), the IF-ELSE statement will trigger an event.
An example of the data is given in the code snippet below:
import java.util.HashMap;
import java.util.Map;
public class CompareSequence{
public static void main(String[] args)
{
Map<String, Integer> myMap = new HashMap<String, Integer>();
myMap.put("0-1", 33);
myMap.put("0-2", 29);
myMap.put("0-3", 14);
myMap.put("0-4", 8);
myMap.put("1-2", 37);
myMap.put("1-3", 45);
myMap.put("1-4", 17);
myMap.put("2-3", 1);
myMap.put("2-4", 16);
myMap.put("3-4", 18);
for(int i = 0; i < 5; i++)
{
for(int j = i+1; j < 5; j++)
{
String testLine = i+"-"+j;
int itemA = myMap.get(testLine);
for(int k = j+1; k < 5; k++)
{
String newLine = j+"-"+k;
int itemB = myMap.get(newLine);
if(itemA > itemB)
{
//IF and ONLY all values of item A that is passed through is bigger than item B
//THEN trigger an event to group item B with A
System.out.println("Item A : " + itemA + " is bigger than item "
+ newLine + " (" +itemB + ")"); // Printing out results to check the loop
}
else
{
System.out.println("Comparison failed: Item " + itemA + " is smaller than " + newLine + " (" + itemB + ")");
}
}
}
}
}
}
Current Result:
Get main value for comparison: myMap.get(0-1) = 33
Get all values related to Key 1-x (set value) ..
myMap.get(1-2) = 37 // This value is bigger than myMap.get(0-1) = 33
myMap.get(1-3) = 45 // This value is bigger than myMap.get(0-1) = 33
myMap.get(1-4) = 17 // This value is smaller than myMap.get(0-1) = 33
In that example given, the IF-ELSE statement should not let it pass, ONLY if all are smaller than 33, should an event be triggered. Is there something different I should do to the IF-ELSE statement or is there a problem with my loop?
Desired Result:
If((myMap.get(0-1) > myMap.get(1-2)) && (myMap.get(0-1) > myMap.get(1-3)) && (myMap.get(0-1) > myMap.get(1-4))...(myMap.get(0-1) > myMap.get(1-n))
{
//Trigger event to group all set values 1-x to value key 0-1
//Then delete all set valued related to 1-x from list
}
Any advice or help would be greatly appreciated. Thank you!
You could try something like this:
for (int i = 0; i < 5; i++) {
for (int j = i + 1; j < 5; j++) {
String testLine = i + "-" + j;
int itemA = myMap.get(testLine);
boolean greaterThanAll = true;
for (int k = j + 1; k < 5; k++) {
String newLine = j + "-" + k;
int itemB = myMap.get(newLine);
if (itemA <= itemB) {
System.out.println("Comparison failed: Item " + itemA + " is smaller than " + newLine + " (" + itemB + ")");
greaterThanAll = false;
break;
} else {
System.out.println("Item A : " + itemA + " is bigger than item "
+ newLine + " (" + itemB + ")"); // Printing out results to check the loop
}
}
if (greaterThanAll) {
System.out.println(testLine + "=" + itemA + " is greater than all");
//IF and ONLY all values of item A that is passed through is bigger than item B
//THEN trigger an event to group item B with A
}
}
}

Categories