What's wrong with my code? It prints 2,2 when the correct answer is clearly 6,8
public static void main(String[] args) {
int a = 1;
int b = 1;
int answer = 0;
int j = 4;
while (j == 4) {
for (a = 1; a <= 10; a++) {
for (b = 1; b <= 10; b++) {
answer = a * a + b * b;
if (answer == 100) {
j = 10;
}
}
}
}
System.out.println(a + " " + b);
}
if(answer == 100);
you have an extra semicolon after your if.
This will cause it to execute the j = 10; no matter what answer equals
You are incrementing a and b at the same time. In your code, the two numbers will always be equal. Also, you are not testing for a match when you exit the loop.
Related
I want to print the result the same way that i print the numbers that i use.
for ex i print 1,2,3,4 2,3,4,5 but the pow remains the same 1024,1024,1024,1024.
public static void main(String[] args) {
int d = 0, e = 0;
double c = 0;
for (int a = 1; a < 5; a++) {
d = a;
for (int b = 2; b < 6; b++) {
c = java.lang.Math.pow(a, b);
}
}
for (int a = 1, b = 2; a < 5; a++, b++) {
d = a;
e = b;
System.out.println(d + " " + e + " " + c);
}
}
This should work, and is also more readable.(you really ought to indent code properly).
Your problem is in the loop logic.
What you are doing is probably possible with for loops, but i think a while loop with two conditionals would work nice.
int a = 1;
int b = 2;
double c = 0.0;
while (a < 5 && b < 6){
c=java.lang.Math.pow (a,b);
System.out.println ( a+ " " +b +" " + c);
b++;
a++;
}
public static void main(String[] args) {
int d = 0, e = 0;
double c = 0;
for (int a = 1; a < 5; a++) {
for (int b = 2; b < 6; b++) {
c = java.lang.Math.pow(a, b);
System.out.println(a + " " + b + " " + c);
}
}
}
If I understood your problem try something like this output should be ok
public class checkerBoard
{
public static void main(String[] args)
{
int m = 6; //m is rows
int n = 2; //n is columns
char o = 'O';
char x = 'X';
for (int r = 1; r <= m; r++)
{
for (int c = 1; c <= n; c++)
{
if (c+r % 2 == 0)
System.out.print(x);
else
System.out.print(o);
if (c == n)
System.out.print("\n");
}
}
}
}
It should be printing
XO
OX
XO
OX
But instead it prints
OO
OO
OO
OO
It's probably a really obvious solution but I'm new to this (obviously) and can't figure out what I did wrong.
This is Java, by the way.
Try changing c+r % 2 to (c+r) % 2.
% takes precedence over +.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Try changing if (c+r % 2 == 0) to if((c+r) % 2 == 0)
Enclose your c+r inside parenthesis because % operator has precedence over + operator which is causing modulus to be executed before sum and causing error.
public class checkerBoard
{
public static void main(String[] args)
{
int m = 6; //m is rows
int n = 2; //n is columns
char o = 'O';
char x = 'X';
for (int r = 1; r <= m; r++)
{
for (int c = 1; c <= n; c++)
{
if ((c+r) % 2 == 0)
System.out.print(x);
else
System.out.print(o);
if (c == n)
System.out.print("\n");
}
}
}
}
The problem is that % takes precedence over +. So, you're code,finally, must look like this :
public class checkerBoard {
public static void main(String[] args) {
int m = 6; //m is rows
int n = 2; //n is columns
char o = 'O';
char x = 'X';
for (int r = 1; r <= m; r++) {
for (int c = 1; c <= n; c++) {
if ((c+r) % 2 == 0){ //% takes precedence over +
System.out.print(x);
} else {
System.out.print(o);
}
}
System.out.print("\n");
}
}
}
I am trying to solve the following problem:
Find the largest palindrome made from the product of two 3-digit numbers.
I have the following Java code:
public static void main(String[] args) {
int a = 999, b = 999;
for(int i = 100; i <= a; i++) {
for(int j = 100; j <= b; j++) {
checkPalindrome(i*j, i, j);
}
}
}
public static void checkPalindrome(int n, int a, int b) {
String s = "" + n;
boolean palindrome = false;
int j = s.length()-1;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) != s.charAt(j))
break;
j -= i;
}
if(palindrome)
System.out.println(n + ", " + a + ", " + b);
}
I'm still lacking the change of the "palindrome" variable but at the moment if I run it I get a String index out of range on line 28 which is the j -= i I just don't understand why this is happening I mean, I get that the difference is resulting in a number lower than 0 but I can't figure out WHY it happens. Could someone please explain me?
Your method can be improved like this. The condition in for loop i<=j reduced number of iterations too.
public static void checkPalindrome(int n, int a, int b) {
String s = "" + n;
boolean palindrome = false;
int j = s.length()-1;
for(int i = 0; i <= j; i++){
if(s.charAt(i) != s.charAt(j))
break;
j --;
}
if(palindrome)
System.out.println(n + ", " + a + ", " + b);
}
Hope this helps.
I think you want j-- not j -= i. Especially since i starts at 0.
change your code to:
public static void checkPalindrome(int n, int a, int b) {
String s = "" + n;
boolean palindrome = true;
int j = s.length()-1;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) != s.charAt(j))
palindrome = false;
}
if(palindrome)
System.out.println(n + ", " + a + ", " + b);
}
You're incrementing i - you want to decrement j - you DON'T want to do j -= i.
Otherwise for a string of length 5, you'd get:
i = 0, j = 4
i = 1, j = 4
i = 2 , j = 3
i = 3 , j = 1
i = 4, j = -2
Though if it's giving an index out of range message, you're running a different version of the code - j -= i can't possibly generate that.
I am currently attempting this question :
A Pythagorean triplet is a set of three natural numbers, a, b and c, for which
a2 + b2 = c2.
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
My code is as follows, I think it should be correct, but the site is telling me my answer is wrong? Can someone help me see the flaws in my logic please?
public class Pythagoras {
public static void main(String[] args) {
int sum = 1000;
int a;
int product=0;
for (a = 1; a <= sum/3; a++)
{
int b;
for (b = a + 1; b <= sum/2; b++)
{
int c = sum - a - b;
if ( c > 0 && (a*a + b*b == c*c) )
System.out.printf("a=%d, b=%d, c=%d\n",a,b,c);
product = a * b * c;
}
}
System.out.println(product);
}
}
Here are 5 solutions (from slow to fast):
1) Trivial implementation - 732857 microseconds (0.7 seconds)
private static void p1(int sum) {
for (int a = 0; a <= sum; a++) {
for (int b = 0; b <= sum; b++) {
for (int c = 0; c <= sum; c++) {
if (a < b && b < c && a + b + c == sum
&& (c * c == a * a + b * b)) {
System.out.print(a * b * c);
return;
}
}
}
}
}
2) Limit the lower bound for b & c (establish the order relation) - 251091 microseconds (0.2 seconds)
private static void p2(int sum) {
for (int a = 0; a <= sum; a++) {
for (int b = a + 1; b <= sum; b++) {
for (int c = b + 1; c <= sum; c++) {
if (a + b + c == sum && (c * c == a * a + b * b)) {
System.out.print(a * b * c);
return;
}
}
}
}
}
3) Limit the lower & upper bounds for b & c - 111220 microseconds (0.1 seconds)
private static void p3(int sum) {
for (int a = 0; a <= sum; a++) {
for (int b = a + 1; b <= sum - a; b++) {
for (int c = b + 1; c <= sum - a - b; c++) {
if (a + b + c == sum && (c * c == a * a + b * b)) {
System.out.print(a * b * c);
return;
}
}
}
}
}
4) Limit lower & upper bounds for b and fix value for c - 2625 microseconds
private static void p4(int sum) {
for (int a = 0; a <= sum; a++) {
for (int b = a + 1; b <= sum - a; b++) {
int c = sum - a - b;
if (c > b && c * c == a * a + b * b) {
System.out.print(a * b * c);
return;
}
}
}
}
5) Use Euclid's formula - 213 microseconds
private static void p5(int sum) {
// a = m^2 - n^2
// b = 2mn
// c = m^2 + n^2
int a, b, c;
int sqrt = (int)Math.sqrt(sum);
for (int n = 1; n <= sqrt; n++) {
for (int m = n+1; m <= sqrt; m++) {
a = m*m - n*n;
b = 2*m*n;
c = m*m + n*n;
if ( a + b + c == 1000 ) {
System.out.print(a * b * c);
return;
}
}
}
}
I think you're missing a set of braces. The indentation leads me to believe the two innermost statements go together but you need curly braces for that to be correct.
if ( c > 0 && (a*a + b*b == c*c) )
{
System.out.printf("a=%d, b=%d, c=%d\n",a,b,c);
product = a * b * c;
}
Without the braces product will always contain the product of the last values of a, b, and c. (333 * 500 * 167 == 27805500).
Though others have already given specific fixes for you code, here's a more general hint that will be useful on other problems as well. Test your code on a simpler version of the problem.
For example, see if your program can find 6,8,10 as a triplet with a sum of 24. With a smaller test you can actually step through the code to see where it's going wrong.
You may try it this way,
public class Pythagoras {
public static void main(String[] args) {
int m = 1, n = 0, a = 0, b = 0, c = 0, sum = 0;
int product = 0;
for (m = 2; m < 100; m++) {
for (n = 1; n < 100; n++) {
while (m > n) {
a = (m * m) - (n * n);
b = (2 * m) * n;
c = (m * m) + (n * n);
sum = a + b + c;
if (sum == 1000) {
product = a * b * c;
System.out.print("a :" + a + "b :" + b + "c : " + c);
System.out.println("Product is" + product);
break;
}
break;
}
}
}
}
}
This implements the Euclid's formula for generating Pythagorean triplet as explained here
Note that in this method we make only triplets hence unwanted repetitions are reduced.
and the output is a :375 b :200 c : 425 Product is 31875000
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public javax.swingx.event.*;
public class Triplet extends JApplet implements ActionListener
{
JLabel l1, l2, l3;
JButton b1;
JTextFiel t1, t2;
public void init()
{
Container c = getContentPane();
c.setLayout(new FlowLayout());
l1=new JLabel("Enter the value of a: ");
l2=new JLabel("Enter the value of b: ");
t1 = new JTextField(20);
t2 = new JTextField(20);
b1=new JButton("Ok");
l2=new JLabel(" ");
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(l3);
b1.addActionListener(this);
public void ActionPerformed(ActionEvent e)
{
int a = Integer.parseInt(t1.getText());
int b = Integer.parseInt(t2.getText());
long c = Math.sqrt(a*a + b*b);
l3.setText(" " +c);
}
}
}
public class Pythagorean_Triplets
{
public static void main(long n)
{
long h=1,p=1,b1;
double b;
while(h<=n)
{
while(p<h)
{
b=Math.sqrt((h*h)-(p*p));
if(b%1==0)
{
b1=(long)b;
System.out.println(b1+","+p+","+h);
break;
}
p++;
}
h++;
p=1;
}
}
}
OK, I have this problem to solve but I can’t program it in Java correctly. See the picture below, you’ll see a 6 pointed star were every point and intersection of lines is a letter.
The assignment is to position the numbers 1 to 12 in such a way that the sum of all lines of four balls is 26 and the sum of all the 6 points of the star is 26 as well.
This comes down to:
(A+C+F+H==26)
(A+D+G+K==26)
(B+C+D+E==26)
(B+F+I+L==26)
(E+G+J+L==26)
(H+I+J+K==26)
(A+B+E+H+K+L==26)
So I started programming a program that would loop through all options brute forcing a solution. The loop is working, however, it now shows solutions where one number is used more than once, which is not allowed. How can I make it in the code that it also checks whether all variables are different or not?
if ((A!= B != C != D != E != F != G != H != I != J != K != L)
I tried the above, but it doesn't work, because it says:
incomparable types: boolean and int.
How can I make a check within 1 or a small statement for whether or not all the numbers are different?
(instead of making a nested 12*12 statement which checks every variable combination)
This is my code so far:
public class code {
public static void main(String[] args){
for(int A = 1; A < 13; A++){
for(int B = 1; B < 13; B++){
for(int C = 1; C < 13; C++){
for(int D = 1; D < 13; D++){
for(int E = 1; E < 13; E++){
for(int F = 1; F < 13; F++){
for(int G = 1; G < 13; G++){
for(int H = 1; H < 13; H++){
for(int I = 1; I < 13; I++){
for(int J = 1; J < 13; J++){
for(int K = 1; K < 13; K++){
for(int L = 1; L < 13; L++){
if ((A+C+F+H==26) && (A+D+G+K==26) && (B+C+D+E==26) && (B+F+I+L==26) && (E+G+J+L==26) && (H+I+J+K==26) && (A+B+E+H+K+L==26)){
if ((A= C != D != E != F != G != H != I != J != K != L)){
System.out.println("A: " + A);
System.out.println("B: " + B);
System.out.println("C: " + C);
System.out.println("D: " + D);
System.out.println("E: " + E);
System.out.println("F: " + F);
System.out.println("G: " + G);
System.out.println("H: " + H);
System.out.println("I: " + I);
System.out.println("J: " + J);
System.out.println("K: " + K);
System.out.println("L: " + L);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
If I get it correctly, you want to check if all A to L are unique. So just put them in a set and find the size of the set:
if ((new HashSet<Integer>(
Arrays.asList(A, B, C, D, E, F, G, H, I, J, K, L)))
.size() == 12) {
//do your stuff
}
I strongly advise using recursion instead, which would vastly simplify the code. Do something like this:
function generate(set used, array list):
if list.size() == 12:
if list matches criteria:
yield list as solution
else:
for next = 1; next < 13; next++:
if next not in used:
used.add(next)
generate(used, list + next)
used.remove(next)
However, to answer you question directly: You can throw all the values into a set and check that it's size is equal to the number of items you threw in. This works because a set will count duplicates as one.
Before looking for a good solution for you, I would like to help with the error you get.
if ((A= C != D != E != F != G != H != I != J != K != L)){
This line does not makes much sense. The first thing the compiler will check is:
if (A=C)
You probably wanted to code if (A!=C), but let's consider what you really type. A=C is an attribution, so A will receive C value.
Then, the compiler will go on. After attributing C's value to A, it will check the comparison:
if (A=C != D)
This will compare A's value to D, which will result in a boolean -- let's say that the result is false.
The next comparison would be:
if (false != E)
At this point, there is a comparison between a boolean and an int, hence the error incomparable types: boolean and int..
Well, as you need to check wheter your numbers are unique, a nice solution would be the one proposed by #abhin4v.
Your nested loops will execute 12^12 = 8.91610045E12 IF-Statements, many of them invalid because of wrong combinations of numbers. You need permutations of 1,2,3,..,12 as candidates of your bruteforcing approach. The number of permutations of 12 Elements is 12!= 479 001 600, so the bruteforcing will be much faster I guess. With only generating valid permutations you don't need any check for valid combinations.
Here is some sample code, the code in nextPerm() is copied and modified from Permutation Generator :
import java.util.Arrays;
public class Graph26 {
private static final int A = 0;
private static final int B = 1;
private static final int C = 2;
private static final int D = 3;
private static final int E = 4;
private static final int F = 5;
private static final int G = 6;
private static final int H = 7;
private static final int I = 8;
private static final int J = 9;
private static final int K = 10;
private static final int L = 11;
private final static boolean rule1(final int[] n) {
return n[A] + n[C] + n[F] + n[H] == 26;
}
private final static boolean rule2(final int[] n) {
return n[A] + n[D] + n[G] + n[K] == 26;
}
private final static boolean rule3(final int[] n) {
return n[H] + n[I] + n[J] + n[K] == 26;
}
private final static boolean rule4(final int[] n) {
return n[B] + n[C] + n[D] + n[E] == 26;
}
private final static boolean rule5(final int[] n) {
return n[B] + n[F] + n[I] + n[L] == 26;
}
private final static boolean rule6(final int[] n) {
return n[E] + n[G] + n[J] + n[L] == 26;
}
private final static boolean rule7(final int[] n) {
return n[A] + n[B] + n[E] + n[H] + n[K] + n[L] == 26;
}
private final static boolean isValid(final int[] nodes) {
return rule1(nodes) && rule2(nodes) && rule3(nodes) && rule4(nodes)
&& rule5(nodes) && rule6(nodes) && rule7(nodes);
}
class Permutation {
private final int[] o;
private boolean perms = true;
public boolean hasPerms() {
return perms;
}
Permutation(final int[] obj) {
o = obj.clone();
}
private int[] nextPerm() {
int temp;
int j = o.length - 2;
while (o[j] > o[j + 1]) {
j--;
if (j < 0) {
perms = false;
break;
}
}
if (perms) {
int k = o.length - 1;
while (o[j] > o[k]) {
k--;
}
temp = o[k];
o[k] = o[j];
o[j] = temp;
int r = o.length - 1;
int s = j + 1;
while (r > s) {
temp = o[s];
o[s] = o[r];
o[r] = temp;
r--;
s++;
}
}
return o.clone();
}
}
public static void main(final String[] args) {
int[] nodes = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
final Graph26 graph = new Graph26();
final Permutation p = graph.new Permutation(nodes);
int i = 0;
while (p.hasPerms()) {
if (isValid(nodes)) {
System.out.println(Arrays.toString(nodes));
}
i++;
nodes = p.nextPerm();
}
System.out.println(i);
}
}