Counting triangles in Java [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
question i am trying to solve.
You are given n triangles.
You are required to find how many triangles are unique out of given triangles. For each triangle you are given three integers a,b,c , the sides of a triangle.
sample input:
5
7 6 5
5 7 6
8 2 9
2 3 4
2 4 3
here is my code:
class TestClass {
public static void main(String args[]) throws Exception {
Scanner scanner = new Scanner(System.in);
int testCases = scanner.nextInt();
int arr[][]=new int[testCases][3];
int count=0;
for (int i = 0; i < testCases; i++) {
for (int j=0;j<3;j++){
arr[i][j]=scanner.nextInt();
}
}
int result[] =new int[testCases];
for (int i = 0; i < testCases; i++) {
for (int j = 0; j < 3; j++) {
result[i] = arr[i][j]+arr[i][j+1]; //possible error
}
}
for (int i=0;i<testCases;i++){
for (int j=i+1;j<testCases;j++) { //possible error
if (result[i]!=result[j]){
count++;
}
}
}
System.out.println(count);
}
}
error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at P1.TestClass.main(Solution.java:21)
how to correct the loops so as to not get the errors(note there maybe other errors than the one's i have highlighted) also some better ways of solving this problem are appreciated.

Your program has an ArrayIndexOutOfBoundException in the line result[i] = arr[i][j]+arr[i][j+1];. And I am not sure your second set of nested loops achieve what you want (Summing the triangles). Here is something that can work.
class TestClass {
public static void main(String args[]) throws Exception {
Scanner scanner = new Scanner(System.in);
int testCases = scanner.nextInt();
int arr[][]=new int[testCases][3];
int count=0;
for (int i = 0; i < testCases; i++) {
for (int j=0;j<3;j++){
arr[i][j]=scanner.nextInt();
}
}
//This section sums each set of three
int result[] =new int[testCases];
for (int i = 0; i < testCases; i++) {
for (int j = 0; j < 3; j++) {
result[i] += arr[i][j];
}
}
//This section counts values that are not duplicated
for (int i=0;i<testCases;i++){
boolean hasDuplicate = false;
for (int j=0;j<testCases;j++) {
if (i == j) continue; //skip comparison of value against itself
if (result[i]==result[j]){
hasDuplicate = true; //duplicate found
}
}
if (!hasDuplicate) count++;
}
System.out.println(count); //display number of unique entries
}
}

I don't want to be doing any homework for you, so I'll give you some pointers. Try not to have a look at a solution I have come up with below before trying it yourself again though.
I'd use an ArrayList to store the test data given to you. They're really useful and Java has great support for them.
result[i] = arr[i][j]+arr[i][j+1]; This breaks because j+1 will always be one over the final index of your array.
You can sort strings alphabetically using Arrays.sort which will make comparing triangles much easier, as possible combinations will all end up the same.
Collections.frequency will tell you how many times an element appears in your ArrayList.
My solution certainly isn't the best, and uses more advanced things as apposed to just arrays and booleans, but it works and produces the right answer at the end. It shows that you can solve problems in many different ways!
public static void main(String[] args) {
ArrayList<String> triangleArray = new ArrayList<String>();
Scanner scanner = new Scanner(System.in);
int uniqueTriangles = 0;
// Ask for input, and store in a string that remove all whitespace
System.out.print("Enter triangle sides in format abc separated by a comma:");
String input = scanner.nextLine().trim().replaceAll("\\s", "");
triangleArray.addAll(Arrays.asList(input.split(",")));
// For each item, check it is three characters, and if so, reorder them in
// ascending order i.e 726 => 267
for (int i = 0; i < triangleArray.size(); i++) {
if (triangleArray.get(i).length() != 3) {
triangleArray.remove(i);
}
// Split the triangle string into a character array and sort 'alphabetically'
char[] charArray = triangleArray.get(i).toCharArray();
Arrays.sort(charArray);
triangleArray.set(i, new String(charArray));
}
// Now go through them all again and see if any are unique
for (String s : triangleArray) {
if (Collections.frequency(triangleArray, s) < 2) {
uniqueTriangles++;
}
}
System.out.println(uniqueTriangles);
}

Related

Unable to make array with 25 integers populated with random numbers from 10 to 99. /java [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Array Printing Java
(3 answers)
Closed 2 years ago.
I have to use the math.random to populate my array with 25 random integers between the range 10 and 99. I'm also having problems trying to print the array. Instead of the full array being printed, only the memory location is printed. How to I write the command for it to print? This is how I've written my code and I know there's something wrong with it but just done know how to iron it out.
public class Proj5COMP110
{
public static void main(String args[])
{
System.out.println ("Project 5: Quick Sort");
int i;
int mSample [] = new int[25];
for ( i= 0; i< mSample.length ; i++)
{
mSample[25] = (int)(Math.random ()* (99-10)+10);
}
System.out.print(mSample[25]);
}
}
The problem as already mentioned in comments is that you have to change
mSample[25] = (int)(Math.random ()* (99-10)+10);
to
mSample[i] = (int)(Math.random ()* (99-10)+10);
I would like to prefer below code, which is less erroneous and doesn't have any warning.
public static void main(String[] args) {
int[] mSample = new int[25];
for (int loop = 0; loop < mSample.length; loop++)
mSample[loop] = new Random().nextInt(90) + 10;
for (int element : mSample)
System.out.println(element);
}
You are storing values into wrong index. use mSample[i] instead of mSample[25] to store value at index i.
mSample[i] = (int)(Math.random ()* (99-10)+10);
Also don't forget to change this line: System.out.print(mSample[25]); This will give you an indexOutOfBounds exception. Learn why this exception occurred.
public class Proj5COMP110
{
public static void main(String args[])
{
System.out.println ("Project 5: Quick Sort");
int i;
int mSample [] = new int[25];
for ( i= 0; i< mSample.length ; i++)
{
mSample[i] = (int)(Math.random ()* (99-10)+10);
}
for ( i= 0; i< mSample.length ; i++)
{
System.out.print(mSample[i]);
}
}
}
In an array the index starts from 0, therefore you should be able to store from mSample[1-24], mSample[25] would be out of bounds. When you are trying to print mSample[25], it is printing garbage value and not memory address.

How to add java.util.Scanner class to read two-dimensional array of float entries input?

I have a question about using java.util.Scanner class to read two-dimensional array of float entries input, I've tried to find on internet, but still can't work. The code show me errors. Anyone can check for me which part I get wrong? Below is my code:
import java.util.Scanner;
public class CloneTwoDarray {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
float[][] a = new float[][];
Scanner sc = new Scanner(System.in);
System.out.println("Type nine float numbers two-dimensional array of similar type and size with line breaks, end by \"-1\":");
String append = "";
while (sc.hasNextLine()) {
String input = sc.nextLine();
if ("-1".equals(input)) {
break;
}
lines.add(input);
}
sc.close();
System.out.println("\n\nThe result is:\n");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
The output error show me like below:
C:\Users\User\AppData\Local\NetBeans\Cache\8.0.2\executor-snippets\run.xml:48:
Cancelled by user.
BUILD FAILED (total time: 3 seconds)
Actually I want the output show me like below:
run:
Type nine float numbers two-dimensional array of similar type and size with line breaks, end by"-1":
1.513
2.321
3.421
4.213
5.432
6.123
7.214
8.213
9.213
-1
The result is:
1.513 2.321 3.421
4.213 5.432 6.123
7.214 8.213 9.213
BUILD SUCCESSFUL (total time: 11 second)
Hope someone can help me solve this problem. Thanks.
I am not entirely sure what your goal is. Also, you define a method CloneTwoDarray that is never used. Your line formatting needs to be adjusted to be more readable.
As for the code itself, lines.add(input) accesses an object, lines, that was never defined.
float[][] a= new float[5][5]; is an example of declaring a two dimensional array with 5 rows and 5 columns. float[][] a = new float[][]is not a correct declaration.
Your stack trace does not provide enough information.
Java's garbage collection will generally take care of closing Scanner for you, you do not need to utilize sc.close() in this instance.

Why is this line printing twice?

So I help tutor an Algebra 2 class at my local high school, and the class is currently looking over matrices. Though not there, they will eventually get to multiplication of matrices. After taking Computer Science last year and learning Java, the teacher I help thought I should try to write a program to multiple matrices.
At the moment, I have up to defining the numbers for the first array that holds the information for the first matrix. However, I have a small issue. As represented by this picture:
the line asking for the index integers is being repeated after already recording the integers. I assume this is due to my layered for loops, but I can't be for certain. Usually new eyes see problems clearer. Any who could help me would be appreciated.
Code:
package matrixmultiplication;
import java.util.*;
public class MatrixMultiplication {
public static void main(String[] args) {
System.out.println("What is the size of the first matrix?");
int matrix1Rows = matrixRows();
int matrix1Columns = matrixColumns();
int[] matrix1 = new int[matrix1Rows * matrix1Columns];
doubleSpace();
System.out.println("What is the size of the second matrix?");
int matrix2Rows = matrixRows();
int matrix2Columns = matrixColumns();
int[] matrix2 = new int[matrix2Rows * matrix2Columns];
doubleSpace();
if (matrix1Columns != matrix2Rows) {
System.out.println("These cannot be multiplied!");
System.exit(0);
} else {
matrix1Numbers(matrix1Rows, matrix1Columns);
}
}
public static int matrixRows() {
System.out.print("Rows:");
Scanner rowSc = new Scanner(System.in);
int rows = rowSc.nextInt();
return rows;
}
public static int matrixColumns() {
System.out.print("Columns:");
Scanner colSc = new Scanner(System.in);
int cols = colSc.nextInt();
return cols;
}
public static int[] matrix1Numbers(int rows, int cols) {
int[] numb = new int[rows * cols];
for (int j = 0; j <= numb.length; j += rows) {
for (int i = 1; i <= cols; i++) {
for (int k = 1; k <= rows; k++) {
System.out.println("What is the value for index ("
+ k + "," + i + ")?");
Scanner inp = new Scanner(System.in);
if (j + k <= numb.length) {
numb[j + k - 1] = inp.nextInt();
}
}
}
}
for (int i = 0; i < numb.length; i++) {
System.out.println(numb[i]);
}
return numb;
}
public static void doubleSpace() {
System.out.println();
System.out.println();
}
}
I use NetBeans 8.2 and the latest working version of Java for NetBeans.
I'm not familiar with the matrixmultiplication package, so I may be rambling here.
for (int j = 0; j <= numb.length; j += rows){
I'm not entirely sure what the outer for loop your have is for, but this most outer for loop causes you to ask for the values of the indices cols times more than you want.
I feel that you originally wanted to use this outer for loop to iterate through each row, and wasn't planning on having the second for loop iterating through cols perhaps?
Also, Kevin Anderson mentions this above. You might avoid this problem altogether if you return a double int array as opposed to storing all values in the matrix in a single dimension. I personally feel it would make more sense.
Just nitpicking, but I wouldn't make a new scanner every time you want to use one in a different method. You could just make a field at the top of your class, instantiate it once in your main method, and then pass it in as a parameter to all methods using the scanner.

Java Arrays: Finding Unique Numbers In A Group of 10 Inputted Numbers RE:

Java Arrays: Finding Unique Numbers In A Group of 10 Inputted Numbers
I have a problem that I have looked into Doestovsky's question but from his question, I need to know on how to make the part on finding duplicates into a function of it's own:
java.util.Scanner input = new java.util.Scanner(System.in);
int[] numbers = new int[10];
boolean[] usedBefore = new boolean[10];
// Insert all numbers
for (int i = 0; i < numbers.length; i++) {
// Read number from console
numbers[i] = input.nextInt();
// Check if number was inserted before
usedBefore[i] = false;
for(int k = 0; k < i; k++) {
if(numbers[k] == numbers[i]) {
usedBefore[i] = true;
break;
}
}
}
// Print all numbers that were not inserted before
for(int j = 0; j < numbers.length; j++) {
if(!usedBefore[i]) {
System.out.print(String.valueOf(numbers[j])+" ");
}
}
I have tried this part of this code and it worked but I need this to take the part that find duplicates into a function of it's own that is powered by arrays.
Credits to ThimoKl for creating this code.
Let's try something else, using Treeset, and let's get rid of that for for
import java.util.*;
public class duplicate {
private static TreeSet<Integer> numbers = new TreeSet<Integer>();
private static TreeSet<Integer> duplicates = new TreeSet<Integer>();
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int n=0;
int numberOfIntToRead=10;
for (int i = 0; i < numberOfIntToRead; i++) {
// Read number from console
n=input.nextInt();
// Check if number was inserted before
checkIfDuplicate(n);
}
// Print all numbers that were not inserted more than one time
for (Integer j : numbers) {
System.out.print(j+" ");
}
}
public static void checkIfDuplicate(int n){
if(!numbers.contains(n) && !duplicates.contains(n)){
numbers.add(n);
}else{
numbers.remove(n);
duplicates.add(n);
}
}
}
But if you really want to use arrays an not a Collection of any sort, then you need to declare your arrays as class members, that way you can put the "for" that checks for duplicates in a function a give it your i, and this way you can also put the "for" that does the printing in a function. and give to it numbers.length. That should do the trick.
You can make use of a Set to make finding duplicates easy:
List<Integer> dups = new ArrayList<>();
Set<Integer> set = new HashSet<>();
for (int i : numbers)
if (!set.add(i))
dups.add(i);
This works because Set#add() returns false if it doesn't change as a result if being called, which happens eggnog the set already contains the number - ie it's a dup.

java.lang.ArrayIndexOutOfBoundsException: 2 >= 2

I'm brand new to Java and my first assignment was to implement a "for" loop. I wrote this program in C++ and it compiles in Java, but I got an error at runtime. Can anyone tell me what's wrong?
import java.util.Scanner;
import java.util.Vector;
public class GlobalMembersMain
{
public static Vector<Integer> get_prime_factors(int number)
{
Vector<Integer> primefactors = new Vector<Integer>();
for (int j = 2; j <= number; j++)
{
if (number % j == 0)
{
primefactors.add(j);
number = number / j;
j = 1;
}
}
return primefactors;
}
public static void main(String[] args)
{
int number;
int count = 1;
System.out.print("Enter integer to analyse:");
System.out.print("\n");
Scanner scan = new Scanner(System.in);
number = scan.nextInt();
Vector<Integer> primefactors = new Vector<Integer>();
primefactors = get_prime_factors(number);
System.out.print("Prime factors are ");
for (int a = 0; a < primefactors.size() + 1; a++)
{
if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
{
count++;
}
else
{
System.out.print(primefactors.elementAt(a));
System.out.print(" (");
System.out.print(count);
System.out.print(") ");
count = 1;
}
}
System.out.print("\n");
}
}
The output:
Enter integer to analyse:
10
Prime factors are 2 (1) Exception in thread "main" java.lang.ArrayIndexOutOfBoun
dsException: 2 >= 2
at java.util.Vector.elementAt(Unknown Source)
at GlobalMembersMain.main(GlobalMembersMain.java:36)
for (int a = 0; a < primefactors.size() + 1; a++)
{
if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
{
count++;
}
Is exceeding the size of the primefactors collection. By 2, in fact.
Change to primefactors.size() - 1 to avoid this error.
Arrays are zero based, which I imagine you are aware of. What you may not be aware of is that in Java a List is backed by an array as well. When you invoke primefactors.size() +1 you are getting one more than you would possibly want. For instance is pf is of size 1 your loop will do the following:
pf.get(0); //returns the only value in the list
pf.get(1); // element doesn't exist
Now the other thing is you do not want to use Vector, generally speaking in Java. It is a synchronized collection. What you want is List/ArrayList.
OTHER CODE ISSUES
public static Vector<Integer> get_prime_factors(int number)
this does not need to be static. Also naming convention is camel case in Java so your function name should be getPrimeFactors(int number)
GlobalMembersMain
Should most likely be named GlobalMember as classes are to be singular in nature and I believe you added Main to indicate it was the class that holds the main function.
In your main function you would do this:
GlobalMember member = new GlobalMember();
member.getPrimeFactors(number);
This is where the problem is:
for (int a = 0; a < primefactors.size() + 1; a++)
{
if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
{
count++;
}
//...
primefactors.elementAt(a+1) for the last element in your collection will throw the exception (AIOB).
Remember that arrays, lists and vectors in Java are zero-based. In your case, the primefactors vector will consist of two elements, available at index 0 and 1 respectively.
The problem you are facing is that you try to access the element primefactors.elementAt(2) which does not exist.
One problem is the break condition in the loop:
for (int a = 0; a < primefactors.size() + 1; a++) {
// ...
}
The first time, a will be 0, the second time 1 which are both fine. However, the loop will not break the third time, because a will equal 2, which is less than primefactors.size() + 1. Consequently, there will be a call to primefactors.elementAt(2) which does not exist and the program will blow up.
There is also a second problem inside the loop since you increment the loop variable by one during the comparison:
if (primefactors.elementAt(a) == primefactors.elementAt(a+1)) {
// ...
}
Yet again, your program will fail if you pass 2 as an argument to primefactors.elementAt(...)

Categories