Hello to all who are taking the time out of their day to attempt and help solve my problem. I am truly stuck for the first time in a while and would really appriciate some help. But enough exposition; here is the what I have implemented thus far:
public class EulerBrick {
private int a, b, c;
private int d, e, f;
private Random random;
public EulerBrick(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
this.d = (int) Math.sqrt((a * a) + (b * b));
this.e = (int) Math.sqrt((a * a) + (c * c));
this.f = (int) Math.sqrt((b * b) + (c * c));
this.random = new Random();
if (verify(a, b, c, random.nextInt())) {
if (a % 3 != 0) {
if (b % 3 != 0) return;
if (c % 3 != 0) return;
}
if (a % 4 != 0) {
if (b % 4 != 0) return;
if (c % 4 != 0) return;
}
if (a % 11 != 0) {
if (b % 11 != 0) {
if (c % 11 != 0) return;
}
}
} else return;
printDimensions();
}
public boolean verify(double a, double b, double c, int k) {
a *= k;
b *= k;
c *= k;
if (a % 3 != 0) {
if (b % 3 != 0) return false;
if (c % 3 != 0) return false;
}
if (a % 4 != 0) {
if (b % 4 != 0) return false;
if (c % 4 != 0) return false;
}
if (a % 11 != 0) {
if (b % 11 != 0) {
if (c % 11 != 0) return false;
}
}
return true;
}
public void printDimensions() {
System.out.println("Side A: " + a + ", Side B: " + b + ", Side C: " + c + ", Side D: " + d + ", Side E: " + e + ", Side F: " + f);
}
}
And here is the main class I am using to test it:
public class Main {
public static void main(String[] args) throws InterruptedException {
int i = 0, j = 0, k = 0;
while (true) {
new EulerBrick(i += 3, j += 4, k += 11);
Thread.sleep(1000);
}
// EulerBrick brick = new EulerBrick(44, 117, 240);
}
}
Again any help would be greatly appreciated. Also this isn't for a course/class just an exercise that Ive stumped myself on.
Related
I have a method that determines whether an expression equal to 24 can be made up of 4 whole array elements.
At the entrance: an array of 4 integers from 1 to 9.
On output: true (if an expression equal to 24 can be constructed from a given set) or false (if it is impossible to build such an expression from a given set).
Admissible arithmetic operators: addition, subtraction, multiplication, division, parentheses.
Example:
Input: [4, 1, 8, 7]
at the exit: true
explanation: (8 - 4) * (7 - 1) = 24
How can I do this without an array of combinations?
public static boolean canBeEqualTo24(int[] nums) {
if (nums.length < 4 || nums.length > 4) return false;
for (int num : nums) {
if (num < 1 || num > 9) return false;
}
final int RESULT = 24;
if (nums[0] + nums[1] + nums[2] + nums[3] == RESULT) return true;
if (nums[0] * nums[1] * nums[2] * nums[3] == RESULT) return true;
int[][] combinations = {
{0, 1, 2, 3},
{0, 1, 3, 2},
{0, 2, 1, 3},
{0, 2, 3, 1},
{0, 3, 2, 1},
{0, 3, 1, 2},
{1, 0, 2, 3},
{1, 0, 3, 2},
{1, 2, 0, 3},
{1, 2, 3, 0},
{1, 3, 2, 0},
{1, 3, 0, 2},
{2, 0, 1, 3},
{2, 0, 3, 1},
{2, 1, 0, 3},
{2, 1, 3, 0},
{2, 3, 0, 1},
{2, 3, 1, 0},
{3, 0, 1, 2},
{3, 0, 2, 1},
{3, 1, 0, 2},
{3, 1, 2, 0},
{3, 2, 0, 1},
{3, 2, 1, 0},
};
int i = 0;
while (i < combinations.length) {
int a = nums[combinations[i][0]];
int b = nums[combinations[i][1]];
int c = nums[combinations[i][2]];
int d = nums[combinations[i][3]];
if (a + b + c - d == RESULT) return true;
if (a + b - c - d == RESULT) return true;
if (a + b + c * d == RESULT) return true;
if (a + b * c * d == RESULT) return true;
if (a - b + c * d == RESULT) return true;
if (-a + b * c - d == RESULT) return true;
if (a * b * c - d == RESULT) return true;
if (a + b * (c + d) == RESULT) return true;
if (a - b * (c + d) == RESULT) return true;
if (a + b * (c - d) == RESULT) return true;
if (a * b * (c + d) == RESULT) return true;
if (a * b * (c - d) == RESULT) return true;
if (-a + b * (c - d) == RESULT) return true;
if (a * (b + c + d) == RESULT) return true;
if (a * (b + c - d) == RESULT) return true;
if (a * (b - c - d) == RESULT) return true;
if (-a + (b * (c + d)) == RESULT) return true;
if ((a + b) * (c + d) == RESULT) return true;
if ((a - b) * (c + d) == RESULT) return true;
if ((a - b) * (c - d) == RESULT) return true;
if ((a * b) + (c * d) == RESULT) return true;
if ((a * b) - (c * d) == RESULT) return true;
if (a * (b * c - d) == RESULT) return true;
if (a * (b * c + d) == RESULT) return true;
if (d != 0) {
if (a * b - c / d == RESULT && c % d == 0) return true;
if (a + b - c / d == RESULT && c % d == 0) return true;
if ((a * b) / d + c == RESULT && (a * b) % d == 0) return true;
if (((a + b) * c) / d == RESULT && ((a + b) * c) % d == 0) return true;
if (((a - b) * c) / d == RESULT && ((a - b) * c) % d == 0) return true;
if (((a * b) - c) / d == RESULT && ((a * b) - c) % d == 0) return true;
if (((a * d + c) * b) / d == RESULT && ((a * d + c) * b) % d == 0) return true;
if (((a * d - c) * b) / d == RESULT && ((a * d - c) * b) % d == 0) return true;
}
if (d * c != 0) {
if ((a * b) / (d * c) == RESULT && (a * b) % (d * c) == 0) return true;
}
if (c - d != 0) {
if ((a * b) / (c - d) == RESULT && (a * b) % (c - d) == 0) return true;
}
if (c + d != 0) {
if ((a * b) / (c + d) == RESULT && (a * b) % (c + d) == 0) return true;
}
if ((a * c - b) != 0) {
if ((d * c) / (a * c - b) == RESULT && (d * c) % (a * c - b) == 0) return true;
}
i++;
}
return false;
}
I have done this before, my solution worked and got me good grades. But then i found this on a website and this solution is complex and lengthy but have a more elegant and systematic approach:
import java.util.*;
public class Game24Player {
final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo",
"nnnnooo"};
final String ops = "+-*/^";
String solution;
List<Integer> digits;
public static void main(String[] args) {
new Game24Player().play();
}
void play() {
digits = getSolvableDigits();
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("Make 24 using these digits: ");
System.out.println(digits);
System.out.println("(Enter 'q' to quit, 's' for a solution)");
System.out.print("> ");
String line = in.nextLine();
if (line.equalsIgnoreCase("q")) {
System.out.println("\nThanks for playing");
return;
}
if (line.equalsIgnoreCase("s")) {
System.out.println(solution);
digits = getSolvableDigits();
continue;
}
char[] entry = line.replaceAll("[^*+-/)(\\d]", "").toCharArray();
try {
validate(entry);
if (evaluate(infixToPostfix(entry))) {
System.out.println("\nCorrect! Want to try another? ");
digits = getSolvableDigits();
} else {
System.out.println("\nNot correct.");
}
} catch (Exception e) {
System.out.printf("%n%s Try again.%n", e.getMessage());
}
}
}
void validate(char[] input) throws Exception {
int total1 = 0, parens = 0, opsCount = 0;
for (char c : input) {
if (Character.isDigit(c))
total1 += 1 << (c - '0') * 4;
else if (c == '(')
parens++;
else if (c == ')')
parens--;
else if (ops.indexOf(c) != -1)
opsCount++;
if (parens < 0)
throw new Exception("Parentheses mismatch.");
}
if (parens != 0)
throw new Exception("Parentheses mismatch.");
if (opsCount != 3)
throw new Exception("Wrong number of operators.");
int total2 = 0;
for (int d : digits)
total2 += 1 << d * 4;
if (total1 != total2)
throw new Exception("Not the same digits.");
}
boolean evaluate(char[] line) throws Exception {
Stack<Float> s = new Stack<>();
try {
for (char c : line) {
if ('0' <= c && c <= '9')
s.push((float) c - '0');
else
s.push(applyOperator(s.pop(), s.pop(), c));
}
} catch (EmptyStackException e) {
throw new Exception("Invalid entry.");
}
return (Math.abs(24 - s.peek()) < 0.001F);
}
float applyOperator(float a, float b, char c) {
switch (c) {
case '+':
return a + b;
case '-':
return b - a;
case '*':
return a * b;
case '/':
return b / a;
default:
return Float.NaN;
}
}
List<Integer> randomDigits() {
Random r = new Random();
List<Integer> result = new ArrayList<>(4);
for (int i = 0; i < 4; i++)
result.add(r.nextInt(9) + 1);
return result;
}
List<Integer> getSolvableDigits() {
List<Integer> result;
do {
result = randomDigits();
} while (!isSolvable(result));
return result;
}
boolean isSolvable(List<Integer> digits) {
Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);
permute(digits, dPerms, 0);
int total = 4 * 4 * 4;
List<List<Integer>> oPerms = new ArrayList<>(total);
permuteOperators(oPerms, 4, total);
StringBuilder sb = new StringBuilder(4 + 3);
for (String pattern : patterns) {
char[] patternChars = pattern.toCharArray();
for (List<Integer> dig : dPerms) {
for (List<Integer> opr : oPerms) {
int i = 0, j = 0;
for (char c : patternChars) {
if (c == 'n')
sb.append(dig.get(i++));
else
sb.append(ops.charAt(opr.get(j++)));
}
String candidate = sb.toString();
try {
if (evaluate(candidate.toCharArray())) {
solution = postfixToInfix(candidate);
return true;
}
} catch (Exception ignored) {
}
sb.setLength(0);
}
}
}
return false;
}
String postfixToInfix(String postfix) {
class Expression {
String op, ex;
int prec = 3;
Expression(String e) {
ex = e;
}
Expression(String e1, String e2, String o) {
ex = String.format("%s %s %s", e1, o, e2);
op = o;
prec = ops.indexOf(o) / 2;
}
}
Stack<Expression> expr = new Stack<>();
for (char c : postfix.toCharArray()) {
int idx = ops.indexOf(c);
if (idx != -1) {
Expression r = expr.pop();
Expression l = expr.pop();
int opPrec = idx / 2;
if (l.prec < opPrec)
l.ex = '(' + l.ex + ')';
if (r.prec <= opPrec)
r.ex = '(' + r.ex + ')';
expr.push(new Expression(l.ex, r.ex, "" + c));
} else {
expr.push(new Expression("" + c));
}
}
return expr.peek().ex;
}
char[] infixToPostfix(char[] infix) throws Exception {
StringBuilder sb = new StringBuilder();
Stack<Integer> s = new Stack<>();
try {
for (char c : infix) {
int idx = ops.indexOf(c);
if (idx != -1) {
if (s.isEmpty())
s.push(idx);
else {
while (!s.isEmpty()) {
int prec2 = s.peek() / 2;
int prec1 = idx / 2;
if (prec2 >= prec1)
sb.append(ops.charAt(s.pop()));
else
break;
}
s.push(idx);
}
} else if (c == '(') {
s.push(-2);
} else if (c == ')') {
while (s.peek() != -2)
sb.append(ops.charAt(s.pop()));
s.pop();
} else {
sb.append(c);
}
}
while (!s.isEmpty())
sb.append(ops.charAt(s.pop()));
} catch (EmptyStackException e) {
throw new Exception("Invalid entry.");
}
return sb.toString().toCharArray();
}
void permute(List<Integer> lst, Set<List<Integer>> res, int k) {
for (int i = k; i < lst.size(); i++) {
Collections.swap(lst, i, k);
permute(lst, res, k + 1);
Collections.swap(lst, k, i);
}
if (k == lst.size())
res.add(new ArrayList<>(lst));
}
void permuteOperators(List<List<Integer>> res, int n, int total) {
for (int i = 0, npow = n * n; i < total; i++)
res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));
}
}
Note: Here you can find this website. Do tell me if this works for you and always give credit to owner.
EDIT: You have to change this code a bit, because it produces random numbersand check if they can be solved to give 24 as a result, if they not then it'll produce another set of random variables and keep ding so until they produces such numbers that can be solved.
Hint: Check methods like
isSolvable()
getSolvableDigits()
randomDigits()
and edit them as you wish.
I'm going to try to define function which return greatest common divisor.
Now I'm just meeting some obstacle.
Why do dead code warning appear in the i--?
I can feel nothing so please let me know what is wrong.
public class Main {
public static int function(int a, int b, int c) {
int min;
if (a > b) {
if (b > c) {
min = c;
} else {
min = b;
}
} else {
if (a > c) {
min = c;
} else {
min = a;
}
}
for (int i = min; i > 0; i--) {
if (a % i == 0 && b % i == 0 && c % i == 0) {
return i;
}
return -1;
}
return 0;
}
public static void main(String[] args) {
System.out.println("(400, 300, 750)의 최대 공약수 : " + function(400, 300, 750));
}
}
The for loop has an if block where you are returning the greatest common divisor if found. If not you are returning -1. So the loop will never continue and "i--" will never be executed. That is why it's a dead code. Remove "return -1", it should work properly.
Stepping through the code in your debugger is often the quickest way to find these bugs. However, you could make the code much faster by only checking values which are a factor of the min value. This reduces the number of iterations dramatically.
public class Main {
public static int function(int a, int b, int c) {
int min;
if (a > b) {
if (b > c) {
min = c;
} else {
min = b;
}
} else {
if (a > c) {
min = c;
} else {
min = a;
}
}
for (int i = min; i > 0; i--) {
if (a % i == 0 && b % i == 0 && c % i == 0) {
System.err.println("Iterations " + (min + 1 - i));
return i;
}
}
return 0;
}
public static long gcd(long a, long b, long c) {
long min = Math.min(a, Math.min(b, c));
for (int j = 1, max = (int) Math.sqrt(min); j <= max; j++) {
long i = min / j;
if (a % i == 0 && b % i == 0 && c % i == 0) {
System.err.println("Iterations: " + j);
return i;
}
}
return 1;
}
public static void main(String[] args) {
System.out.println("(400, 300, 750)의 최대 공약수 : " + function(400, 300, 750));
System.out.println("(400, 300, 750)의 최대 공약수 : " + gcd(400, 300, 750));
}
}
prints
(400, 300, 750)의 최대 공약수 : 50
(400, 300, 750)의 최대 공약수 : 50
Iterations 251
Iterations: 6
In your approach, it has to consider all the factors from 300 to 50 (251 values). But considering only the factors of 300 i.e. 300/1, 300/2, 300/3, 300/4, 300/5, 300/6 (6 values) it is much faster.
I have been trying to implement a Miller-Rabin primality test from scratch (only primitives and Strings) that works for 64 bit integers (longs). I've tried the Java and pseudocode from Wikipedia, as well as various other websites. So far, only very small numbers have worked correctly. Most numbers are incorrectly marked composite, such as 53 or 101. I have tried tracking various sections of the code to see where the problem is. It seems to be in the innermost loop. I don't know what the specific issue is. Any help is appreciated. Thanks!
Here is my code:
public class PrimeTest
{
public static void main(String[] args)
{
PrimeTest app = new PrimeTest();
}
private PrimeTest()
{
long n = 53; // Change to any number. 53 is prime, but is reported as composite
if (checkPrime(n, 10))
{
System.out.println(n + " is prime.");
}
else
{
System.out.println(n + " is not prime.");
}
}
// Check if n is prime with 4^(-k) change of error
private boolean checkPrime(long n, int k)
{
// Factor n-1 as d*2^s
long d = n - 1;
int s = 0;
while (d % 2 == 0)
{
d /= 2;
s++;
}
// Repeat k times for 4^-k accuracy
for (int i = 0; i < k; i++)
{
long a = (long) ((Math.random() * (n - 3)) + 2);
long x = modPow(a, d, n);
if (x == 1 || x == (n - 1))
{
continue;
}
int r;
for (r = 0; r < s; r++)
{
x = modPow(x, 2, n);
if (x == 1)
{
return false;
}
if (x == (n - 1))
{
break;
}
}
if (r == s)
{
return false;
}
}
return true;
}
// Return (base^exp) % mod
private long modPow(long base, long exp, long mod)
{
if (mod == 1)
{
return 0;
}
long result = 1;
base = base % mod;
while (exp > 0)
{
if ((exp & 1) == 0)
{
result = (result * base) % mod;
}
exp = exp >> 1;
base = (base * base) % mod;
if (base == 1)
{
break;
}
}
return result;
}
}
This line in modPow:
if ((exp & 1) == 0)
is wrong and should instead be
if ((exp & 1) == 1)
I tried a program but it shows the first digit. I want a mid digit program by using while loop.
I used the following-
public class MID {
public static void Indra(int n) {
int a = 0, c = 0, m = 0, r = 0;
a = n;
while (n != 0) {
c++;
n = n / 10;
}
n = a;
if (c % 2 == 0) {
System.out.println("No mid digit exsist!!");
} else {
m = (c + 1) / 2;
c = 0;
while (n != 0) {
c++;
r = n % 10;
if (c == r) {
System.out.println(r);
}
n = n / 10;
}
}
}
}
But it keeps on giving the same output-
The mid digit of 345 is 3
Please,help me!
If you dont mind using a different logic, you can try this..
int x = 354;
String num = Integer.toString(x);
if(num.length() % 2 != 0){
System.out.println("The mid digit of " + x + " is " + num.charAt(num.length()/2));
}else {
System.out.println("No middle number.");
}
You calculate m for the position middle digit, but you don't use it.
m = (c + 1) / 2;
for (int i = 0; i < m; i++)
n /= 10;
System.out.println(n % 10);
If you want to stick to int then use this
if (c == 1 || c % 2 == 0) {
System.out.println("No mid digit exsist!!");
}
else
{
m = c/2;
int lower = (int)(n % Math.pow(10, m));
int upper = n-((int)(n % Math.pow(10, m+1)));
r = n-(upper+lower);
while (r >= 10)
{
r = r/10;
}
System.out.println(r);
}
I have completed this exercise on codingbat successfully, but I want to know is there a better/faster or more elegant solution?
Given 3 int values, a b c, returns their sum. However, if one of the values is the same as another of the values, it does not count towards the sum.
loneSum(1, 2, 3) → 6
loneSum(3, 2, 3) → 2
loneSum(3, 3, 3) → 0
public int loneSum(int a, int b, int c)
{
int sum = a + b + c;
if ( a == b) { sum = sum - a - b; }
if ( a == c) { sum = sum - a - c; }
if( b == c) { sum = sum - b - c; }
if (( a == b ) && (b==c)) { sum = 0; }
return sum;
}
Maybe this code?
public static int loneSum(int a, int b, int c) {
if (a == b && b == c) {
a = 0;
b = 0;
c = 0;
}
if (a == b) {
a = 0;
b = 0;
}
if (a == c) {
a = 0;
c = 0;
}
if (b == c) {
b = 0;
c = 0;
}
return a + b + c;
}
You can measure the time ... this seems like less sub ops so might be faster
public int loneSum(int a, int b, int c) {
int sum = 0;
boolean ab = a != b;
boolean ac = a != c;
boolean bc = b != c;
if(ab && ac) sum += a;
if(ab && bc) sum += b;
if(bc && ac) sum += c;
return sum;
}
public int loneSum(int a, int b, int c) {
if ( (a==b) && (b==c) && (c==a) ) return 0;
else
{
if (a==b) return c ;
if (b==c) return a;
if (a==c) return b;
else return a+b+c;
}
}
public int loneSum(int a, int b, int c) {
int sum = a+b+c;
if (a==b) sum -= a*2;
if (b==c) sum -= b*2;
if (c==a) sum -= c*2;
if (sum<0) sum=0;
return sum;
}
This take 4 comparisons.
Initialize sum to a+b+c
Compare numbers to each other and if same, decrease sum by num*2.
If multiple IF's are hit (meaning a==b==c), the sum becomes 0. Return 0 in that case.
if (a==b && b==c) return 0;
if (a==b) return c;
if (a==c) return b;
if (b==c) return a;
return a+b+c;
def lone_sum(a, b, c):
sum=0
if a==b==c:
sum=0
elif a==b:
sum=c
elif a==c:
sum=b
elif b==c:
sum=a
else:
sum=a+b+c
return sum
This is for python
public int loneSum(int a, int b, int c)
{
int sum = a + b + c;
if ( a == b) { sum = c; }
if ( a == c) { sum = b; }
if( b == c) { sum = a; }
if (( a == b ) && (b==c)) { sum = 0; }
return sum;
}
This is for java
I sending you another approach using ternary operators. I hope it can be useful in your exercises and learning process.
public int noTeenSum(int a, int b, int c) {
a = (a >= 13 && a <= 19) ? (a == 15 || a == 16) ? a : 0 : a;
b = (b >= 13 && b <= 19) ? (b == 15 || b == 16) ? b : 0 : b;
c = (c >= 13 && c <= 19) ? (c == 15 || c == 16) ? c : 0 : c;
return a+b+c;
}
I think this is easier to read
def lone_sum(a, b, c):
if a == b == c:
return 0
if a == b:
return c
if b == c:
return a
if a == c:
return b
else:
return a + b + c
Here's my answer:
def lone_sum(a, b, c):
if a!=b and b!=c and c!=a:
return a+b+c
elif a==b==c:
return 0
elif a==b:
return c
elif b==c:
return a
elif c==a:
return b
public int loneSum(int a, int b, int c) {
int sum = a+b+c;
if(a==b)
sum -= (a+b);
if(a==c)
sum -= (a + c);
if(b==c)
sum -= (b+c);
return sum > 0? sum: 0;
}
def lone_sum(a, b, c):
tempSum, arr2 = a+b+c, list(set([a,b,c]))
if (a==b==c): return 0
return sum(arr2) - (tempSum - sum(arr2))
Please see the below function :
def su(a,b,c):
total=0
for x in (a,b,c):
if x==(x+1):
y=0
else:
y=1
total+=x*y
return total
print(su(3,2,3))