I want to get a number from user and calculate how many different triangles can be formed with the given length for example :
5 (2-2-1)
Answer: 1
12 (5,5,2)(3,4,5)(4,4,4)
Answer: 3
I've wrote some codes but I want a faster way to do that.
Here is my codes:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
int value = 0;
for (int i = 1; i < t; i++) {
for (int j = i; j < t; j++) {
for (int h = j; h < t; h++) {
if (i+h+j == t & i+j > h & i+h > j & h+j > i) value++;
}
}
}
System.out.println(value);
}
You can do it in O(1):
int n = input.nextInt();
long value = Math.round(((long)n*n)/12d) - ((long)n/4)*(((long)n + 2)/4);
using Alcuin's Sequence.
You can make it O(n^2) easily.
for (int i = 1; i < t; i++) {
for (int j = i; j < t; j++) {
int h=t-i-j;
//check in O(1)
}
}
Related
I need the maximum elements position if there is more than one maximum element then the first one is to be printed.
My code prints the position of the maximum element but not the first one.
I don't understand why the last iteration is not working as I intend it to.
Please solve it using only Java.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
// define lengths
int n = sc.nextInt();
int m = sc.nextInt();
// add length to matrix
int[][] matrix = new int[n][m];
// insert elements
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
// define max
int max = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
// System.out.print(i + " " + j);
}
// System.out.print(max + " ");
// print index of highest element
// int pos1 = 0;
// int pos2 = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (matrix[i][j] == max) {
System.out.print(i + " " + j);
break;
}
// pos2 += 1;
break;
}
// pos1 += 1;
// break;
}
}
}
There is no need to go through the matrix twice. When you are searching for the max, store also the coordinates of the matrix where that max was found. A code example:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
// define lengths
int n = sc.nextInt();
int m = sc.nextInt();
// add length to matrix
int[][] matrix = new int[n][m];
// insert elements
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
// define max
int max = Integer.MIN_VALUE, row=0, col=0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
row=i;
col=j;
}
}
}
System.out.print("max: "+max + " is at: ");
System.out.print(col + " " + row); //indexes starting from zero
}
}
Create a new variable to hold the position of the max value and set it in the current loop
int max = matrix[0][0];
int[] maxPos = new int[2];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
maxPos[0] = i;
maxPos[1] = j;
}
}
}
and then remove the rest of the code and print the result
System.out.printf("Max is %d and is found at [%d, %d]\n", max, maxPos[0], maxPos[1]);
I'm trying to create a 2D int array of numbers that are the product of 2 via user input defining the length of the rows and columns, as the one below:
1 2 4 8
2 4 8 16
4 8 16 32
8 16 32 64
I've only got up to here, and cannot figure out how to make the matrix to start from 1 and to look like the one above. I'd appreciate your help on this one!
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
int[][] matrix = new int[n][n];
matrix[0][0] = 1;
int temp = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = temp * 2;
temp *= 2;
}
}
System.out.println(Arrays.deepToString(matrix));
I'd say that each element of the matrix would be:
matrix[i][j] = (int) Math.pow(2, i+j) ;
So, your loop would look like this:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = (int) Math.pow(2, i+j);
}
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
int[][] matrix = new int[n][n];
matrix[0][0] = 1;
int temp = 1;
for (int i = 0; i < n; i++) {
temp = (int)Math.pow(2, i);
for (int j = 0; j < n; j++) {
matrix[i][j] = temp;
temp *= 2;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j]+" ");
}
System.out.println();
}
}
I am doing a solution to a coding problem, and I tweaked some existing code to be able to figure out how many semi-primes exist up till and including a certain number.
However, I am stuck at the part where I want to count the number of unique semi-primes between two numbers e.g. 10 and 4, which would be 4,6,9 and 10, i.e. 4. My answer is simply saying 10 has 4 semi-primes, 4 has 1 semi-primes, so the sub-primes between them are 4-1 =3. This is where I am going wrong.
Code is here:
public class SemiPrimeRange {
public static int[] solution(int N, int[] P, int[] Q) {
int arrSize = P.length;
int[] arr = new int[arrSize];
for (int i = 0; i < arr.length; i++) {
int n = NoSemiPrimes(Q[i]);
int m = NoSemiPrimes(P[i]);
arr[i] = n-m;
}
for (int i : arr) {
System.out.println(i);
}
return arr;
}
public static int NoSemiPrimes(int large) {
int n = 0;
boolean[] primeTop = new boolean[large + 1];
boolean[] semiprimeTop = new boolean[large + 1];
for (int i = 2; i <= large; i++) {
primeTop[i] = true;
}
for (int i = 2; i * i <= large; i++) {
if (primeTop[i]) {
for (int j = i; i * j <= large; j++) {
primeTop[i * j] = false;
}
}
}
int primes = 0;
for (int i = 2; i <= large; i++) {
if (primeTop[i])
primes++;
}
for (int i = 0; i < large; i++) {
semiprimeTop[i] = false;
}
for (int i = 0; i <= large; i++) {
for (int j = i; j <= large; j++) {
if (primeTop[j]&&primeTop[i]) {
if(i*j<=large){
semiprimeTop[j*i] = true;
}
}
}
}
for (int i = 0; i < semiprimeTop.length; i++) {
System.out.println(semiprimeTop[i]);
}
int semiprimes = 0;
for (int i = 2; i <= large; i++) {
if (semiprimeTop[i])
semiprimes++;
}
System.out.println("The number of semiprimes <= " + large + " is " + semiprimes);
return semiprimes;
}
public static void main(String[] args) {
int[] P = { 1, 4, 16 };
int[] Q = { 26, 10, 20 };
int N = 26;
solution(N, P, Q);
}
If you want number of semi-primes between y and x (y > x), count(y) - count(x) (count(a) is number of semi-primes between a and 1) is not a correct formula because it will omit x if it is semi-prime. Correct formula is count(y) - count(x - 1).
Also note that your code is ineffective because it will count between 1 and the lesser number twice.
The method signature should be
public static int NoSemiPrimes(int small, int large)
and change the loop
int semiprimes = 0;
for (int i = 2; i <= large; i++) {
if (semiprimeTop[i])
semiprimes++;
}
to
int semiprimes = 0;
for (int i = small; i <= large; i++) {
if (semiprimeTop[i])
semiprimes++;
}
to count the number of semi-primes in desired range directly instead of using int NoSemiPrimes(int large) twice.
I need to sort book objects by their titles in a simple way. However, the selection sort algorithm I wrote isn't working properly and just moves the books around, but with no apparent order. What am I doing wrong?
int j;
int b;
for (int i = 0; i < 20 - 1; i++) {
int minIndex = i;
for (j = i + 1; j < 20; j++) {
b = (bookA[j].getTitle().compareTo(bookA[minIndex].getTitle()));
if (b < 0) {
minIndex=j;
}
}
Book temp = bookA[i];
bookA[i] = bookA[j];
bookA[j] = temp;
}
for (int z = 0; z < 20; z++)
System.out.println(bookA[z].toString());
You're using j as an index in bookA[i] = bookA[j];. The problem is that you're overriding the value of j at every iteration, so when it finally gets to bookA[i] = bookA[j]; it will always be 20.
What you want is to replace it with bookA[minIndex]. The resulting code would look like this:
int j;
int b;
for(int i=0;i<20-1;i++){
int minIndex=i;
for(j=i+1;j<20; j++) {
b=(bookA[j].getTitle().compareTo(bookA[minIndex].getTitle()));
if(b<0){
minIndex=j;
}
}
Book temp = bookA[i];
bookA[i] = bookA[minIndex];
bookA[minIndex] = temp;
}
for(int z=0;z<20;z++)
System.out.println(bookA[z].toString());
I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is marked with a "1".
The last step of my program is to print out the 20/20 array. I can't figure out how to print it and I need to replace the "1" with an "X". The print command is actually a method inside a class that a parent program will call. I know I have to use a loop.
public void printGrid() {
System.out.println...
}
you can use the Utility mettod. Arrays.deeptoString();
public static void main(String[] args) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
System.out.println(Arrays.deepToString(twoD));
}
public void printGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
And to replace
public void replaceGrid()
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
}
}
}
And you can do this all in one go:
public void printAndReplaceGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
Something like this that i answer in another question
public class Snippet {
public static void main(String[] args) {
int [][]lst = new int[10][10];
for (int[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}
public static void printTwoDimensionalArray(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%d ", a[i][j]);
}
System.out.println();
}
}
just for int array
Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.
public void printGrid(int[][] in){
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++){
if(in[i][j] == 1)
System.out.print('X' + "\t");
else
System.out.print(in[i][j] + "\t");
}
System.out.print("\n");
}
}
You should loop by rows and then columns with a structure like
for ...row index...
for ...column index...
print
but I guess this is homework so just try it out yourself.
Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.
How about trying this?
public static void main (String [] args)
{
int [] [] listTwo = new int [5][5];
// 2 Dimensional array
int x = 0;
int y = 0;
while (x < 5) {
listTwo[x][y] = (int)(Math.random()*10);
while (y <5){
listTwo [x] [y] = (int)(Math.random()*10);
System.out.print(listTwo[x][y]+" | ");
y++;
}
System.out.println("");
y=0;
x++;
}
}
If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.
int numDigits = (int) Math.log10(maxValue) + 1;
if (numDigits <= 1) {
numDigits = 2;
}
StringBuffer buf = new StringBuffer();
for (int i = 0; i < matrix.length; i++) {
int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
int block = row[j];
buf.append(String.format("%" + numDigits + "d", block));
if (j >= row.length - 1) {
buf.append("\n");
}
}
}
return buf.toString();
I am also a beginner and I've just managed to crack this using two nested for loops.
I looked at the answers here and tbh they're a bit advanced for me so I thought I'd share mine to help all the other newbies out there.
P.S. It's for a Whack-A-Mole game hence why the array is called 'moleGrid'.
public static void printGrid() {
for (int i = 0; i < moleGrid.length; i++) {
for (int j = 0; j < moleGrid[0].length; j++) {
if (j == 0 || j % (moleGrid.length - 1) != 0) {
System.out.print(moleGrid[i][j]);
}
else {
System.out.println(moleGrid[i][j]);
}
}
}
}
Hope it helps!
more simpler approach , use java 5 style for loop
Integer[][] twoDimArray = {{8, 9},{8, 10}};
for (Integer[] array: twoDimArray){
System.out.print(array[0] + " ,");
System.out.println(array[1]);
}