Solving 2 equations - 9 Unknowns, with constraints. - matlab

I'm trying to solve a riddle with the use of matlab.
This is realy more about matlab than the riddle itself (The riddle is taken from a daily newspaper).
The riddle gives two 3 digits numbers represented by letters. I need to find the digit (0-9) the doesn't participate.
aba-dcc=efe ; aba+dcc=ghi
Now, I have 2 equations with 9 unknowns.
I've managed to solve it by checking all permutations of the vector 0:9, in a while loop.
vecAns = 0:9;
P = perms(vecAns);
P = P(:,1:9);
A = [ 101 10 -100 -11 -101 -10 0 0 0 ;...
101 10 100 11 0 0 -100 -10 -1];
resVec = [0;0];
found=false;
i=1;
h = waitbar(0,'Computing');
while found==false
Res=A*P(i,:)';
if (Res(1)==0)&&(Res(2)==0)
break;
end
i=i+1;
waitbar(i/length(P),h,sprintf('%d%%',i/length(P)*100));
end
close(h)
Is there a way (without adding mathematical considerations) to solve the problem.
For example, I know that all the unknowns must be integers and within the range 0-9.
If there isn't a way. How can make it more efficient?

You don't have to enumerate all the permutations. You can start with the first 4 digits (a, b, c and d), and check if they produce a difference and sum that matches efe and ghi. You also need to make sure all the digits are distinct.
I'm not very proficient in writing matlab code, so I'll demonstrate it with C# code:
//aba-dcc=efe
//aba+dcc=ghi
for (int a = 1; a <= 9; a++) // 'a' cannot be zero
for (int b = 0; b <= 9; b++)
if (a != b)
for (int c = 0; c <= 9; c++)
if (c != a && c != b)
for (int d = 1; d <= 9; d++) // 'd' cannot be zero
if (d != a && d != b && d != c)
{
int aba = a*101 + b*10;
int dcc = c*11 + d*100;
int efe = aba - dcc;
if (efe < 0) continue;
int ghi = aba + dcc;
if (ghi > 999) continue;
int e = efe % 10;
if (e == a || e == b || e == c || e == d) continue;
int f = (efe/10)%10;
if (f == a || f == b || f == c || f == d || f == e) continue;
if (efe != e*101 + f*10) continue;
int i = ghi%10;
if (i == a || i == b || i == c || i == d || i == e || i == f) continue;
int h = (ghi/10)%10;
if (h == a || h == b || h == c || h == d || h == e || h == f || h == i) continue;
int g = (ghi/100)%10;
if (g == a || g == b || g == c || g == d || g == e || g == f || g == i || g == h) continue;
Console.WriteLine("{0:d3}-{1:d3}={2:d3} ; {0:d3}+{1:d3}={3:d3}", aba, dcc, efe, ghi);
}
This completes in less than a millisecond on my computer.
Output:
717-233=484 ; 717+233=950
(% is modulus, and / is integer division. continue skips to the next iteration of the loops.)

Related

How to display column vector x in Cramer's rule in MATLAB?

I am trying to code the Cramer's Rule on MATLAB for a square matrix. I understand the Rule perfectly and also believe the logic behind my code is alright. However, could you please check where I might be going wrong that my result is not being displayed correctly? Any help would be appreciated! Thanks :)
function x = cramer(A, b)
r = size(A, 1);
c = size(A, 2);
n = size(b, 1);
if r ~= c
disp('Oops! Please enter a square matrix');
end
if r == c == n
D = det(A);
if D == 0
disp('Oops! Either, there are a family of soultions or no unique solution')
end
if D ~= 0
result = zeros(n, 1);
for (i = 1:n)
A_x = A;
A_x(:, i) = b;
Dx = det(A_x);
result(i,1) = Dx/D;
end
x = result;
end
end
end
You have an error in your if r == c == n check.
The expression r == c == n can be expanded as (r == c) == n
So it compares the value of logical(r == c) with n.
As an example:
>> 2 == 2 == 1
ans =
logical
1
Rewrite your check as r == c && c == n or isequal(r,c,n) and you should be good.
EDIT: You can simplify your logic quite some, say for example by:
function x = cramers(A, b)
if diff(size(A)) && size(A,1) == n
D = det(A);
if D == 0
disp('Oops! Either, there are a family of solutions or no unique solution')
return
else
result = zeros(n, 1);
for i = 1:n
A_x = A;
A_x(:, i) = b;
Dx = det(A_x);
result(i,1) = Dx/D;
end
x = result;
end
else
disp('Dimension error')
return
end
end

Parce error at IF: Usage might be invalid MATLAB syntax

function [a] = Int_Force(x,x1,x2,u1,u2,rRep,rAli,rAtt)
r = x1-x2;
v = u1-u2;
if
((0 <= r) && (r < rRep));
g = -1;
end
if
((rRep <= r) && (r < rAli));
g = 0;
end
if
(rAli <= r) && (r <= rAtt));
g = 1;
end
a = (1/x-1)*Sum(g*r/norm(r)) + (1-mod(g)*(v/norm(v)));
end
Hi there, sorry I am new to Matlab this year and this is my first time using this website so apologies if I am being unclear. I am trying to create a function based on the interaction forces between moving vectors. I am experiencing errors with my 'if' statements, specifically the first 2 but not the last one, with the error message saying 'Parce error at IF: Usage might be invalid MATLAB syntax'. Does anyone know how I might fix this?
Cheers,
Dan.
Get rid of the semi colons after the if statements. You can view valid if statement syntax here
function [a] = Int_Force(x,x1,x2,u1,u2,rRep,rAli,rAtt)
r = x1-x2;
v = u1-u2;
if (0 <= r) && (r < rRep)
g = -1;
end
if (rRep <= r) && (r < rAli)
g = 0;
end
if (rAli <= r) && (r <= rAtt)
g = 1;
end
a = (1/x-1)*Sum(g*r/norm(r)) + (1-mod(g)*(v/norm(v)));
end

coffeescript prime number generation

I am trying to generate prime numbers like this:
generatePrimeNumbersBelowN = (n) ->
for i in [2..n-1]
isPrime = true
for j in [2..i-1]
isPrime = false if i % j == 0
break if not isPrime
console.log(i, "is Prime Number.") if isPrime
generatePrimeNumbersBelowN(100);
I am getting prime numbers from 3 to 97, inclusive. I am new to JavaScript/CoffeeScript, so please tell me what's happening to 2?
Here's the generated JS code:
var generatePrimeNumbersBelowN;
generatePrimeNumbersBelowN = function(n) {
var i, isPrime, j, k, l, ref, ref1, results;
results = [];
for (i = k = 2, ref = n - 1; 2 <= ref ? k <= ref : k >= ref; i = 2 <= ref ? ++k : --k) {
isPrime = true;
for (j = l = 2, ref1 = i - 1; 2 <= ref1 ? l <= ref1 : l >= ref1; j = 2 <= ref1 ? ++l : --l) {
if (i % j === 0) {
isPrime = false;
}
if (!isPrime) {
break;
}
}
if (isPrime) {
results.push(console.log(i, "is Prime Number."));
} else {
results.push(void 0);
}
}
return results;
};
generatePrimeNumbersBelowN(100);
generatePrimeNumbersBelowN = (n) ->
for i in [2..n-1]
isPrime = true
for j in [2..i-1]
isPrime = false if i % j == 0
break if not isPrime
console.log(i, "is Prime Number.") if isPrime
When i is 2, j ranges from 2 down to 1. You then check i % j which is 2 % 1 which is zero and claim that 2 is not a prime.
Because for x in [b..a] delivers a downward loop from b to a, while loop construct solves this problem.
generatePrimeNumbersBelowN = (n) ->
i = 2
while i < n
isPrime = true
j = 2
while j < i
isPrime = false if i % j == 0
break if not isPrime
j++
console.log(i, "is Prime Number.") if isPrime
i++
generatePrimeNumbersBelowN(100);

Integer division in Scala [duplicate]

(note: not the same as this other question since the OP never explicitly specified rounding towards 0 or -Infinity)
JLS 15.17.2 says that integer division rounds towards zero. If I want floor()-like behavior for positive divisors (I don't care about the behavior for negative divisors), what's the simplest way to achieve this that is numerically correct for all inputs?
int ifloor(int n, int d)
{
/* returns q such that n = d*q + r where 0 <= r < d
* for all integer n, d where d > 0
*
* d = 0 should have the same behavior as `n/d`
*
* nice-to-have behaviors for d < 0:
* option (a). same as above:
* returns q such that n = d*q + r where 0 <= r < -d
* option (b). rounds towards +infinity:
* returns q such that n = d*q + r where d < r <= 0
*/
}
long lfloor(long n, long d)
{
/* same behavior as ifloor, except for long integers */
}
(update: I want to have a solution both for int and long arithmetic.)
If you can use third-party libraries, Guava has this: IntMath.divide(int, int, RoundingMode.FLOOR) and LongMath.divide(int, int, RoundingMode.FLOOR). (Disclosure: I contribute to Guava.)
If you don't want to use a third-party library for this, you can still look at the implementation.
(I'm doing everything for longs since the answer for ints is the same, just substitute int for every long and Integer for every Long.)
You could just Math.floor a double division result, otherwise...
Original answer:
return n/d - ( ( n % d != 0 ) && ( (n<0) ^ (d<0) ) ? 1 : 0 );
Optimized answer:
public static long lfloordiv( long n, long d ) {
long q = n/d;
if( q*d == n ) return q;
return q - ((n^d) >>> (Long.SIZE-1));
}
(For completeness, using a BigDecimal with a ROUND_FLOOR rounding mode is also an option.)
New edit: Now I'm just trying to see how far it can be optimized for fun. Using Mark's answer the best I have so far is:
public static long lfloordiv2( long n, long d ){
if( d >= 0 ){
n = -n;
d = -d;
}
long tweak = (n >>> (Long.SIZE-1) ) - 1;
return (n + tweak) / d + tweak;
}
(Uses cheaper operations than the above, but slightly longer bytecode (29 vs. 26)).
There's a rather neat formula for this that works when n < 0 and d > 0: take the bitwise complement of n, do the division, and then take the bitwise complement of the result.
int ifloordiv(int n, int d)
{
if (n >= 0)
return n / d;
else
return ~(~n / d);
}
For the remainder, a similar construction works (compatible with ifloordiv in the sense that the usual invariant ifloordiv(n, d) * d + ifloormod(n, d) == n is satisfied) giving a result that's always in the range [0, d).
int ifloormod(int n, int d)
{
if (n >= 0)
return n % d;
else
return d + ~(~n % d);
}
For negative divisors, the formulas aren't quite so neat. Here are expanded versions of ifloordiv and ifloormod that follow your 'nice-to-have' behavior option (b) for negative divisors.
int ifloordiv(int n, int d)
{
if (d >= 0)
return n >= 0 ? n / d : ~(~n / d);
else
return n <= 0 ? n / d : (n - 1) / d - 1;
}
int ifloormod(int n, int d)
{
if (d >= 0)
return n >= 0 ? n % d : d + ~(~n % d);
else
return n <= 0 ? n % d : d + 1 + (n - 1) % d;
}
For d < 0, there's an unavoidable problem case when d == -1 and n is Integer.MIN_VALUE, since then the mathematical result overflows the type. In that case, the formula above returns the wrapped result, just as the usual Java division does. As far as I'm aware, this is the only corner case where we silently get 'wrong' results.
return BigDecimal.valueOf(n).divide(BigDecimal.valueOf(d), RoundingMode.FLOOR).longValue();

Perceptron training in Matlab

I am trying to create a simple perceptron training function in MATLAB. I want to return the weights when no errors are found.
Here is the data I want to classify.
d = rand(10,2);
figure
labels = ones(10,1);
diff = d(:,1) + d(:,2) - 1;
labels( diff + 1 >= 1) = 2;
pathWidth = 0.05;
labels( abs(diff) < pathWidth) = [];
d(abs(diff) < pathWidth,:) = [];
plot(d(labels == 1,1),d(labels == 1,2),'k.','MarkerSize',10)
plot(d(labels == 2,1),d(labels == 2,2),'r.','MarkerSize',10)
It produces a labelled data set, where the division between the two classes (red, black) are more visible if you increase the number of points for d.
For my perceptron function I pass the data (d) and labels. I have 3 inputs, the x values, y values and bias which is one. Each input has a random weight between 0 and 1 assigned. Note that the dataset d I have named Z in the perceptron function.
I did use a sigmoid activation function but that would run once through the while loop and always return true after that, the sigmoid function also gave me values of either inf or 1. Below I am using just a threshold activation but it seems to continually loop and not returning my weights. I think the problem may lie in the if-statement below
if(v >= 0 && labels(i) == 1 || v < 0 && labels(i) == 2)
Perceptron function:
function perceptron(data,labels)
sizea = numel(data(:,1));
weights = rand(sizea,3);
Z = data(:,:)
eta = 0.5;
errors = 1;
count = 0;
while errors > 0
errors = 0;
v = sum((1*weights(1,1)) + (Z(:,1)*weights(1,2)) + (Z(:,2)*weights(1,3)));
if v >= 1
v = 1;
else
v = 0;
end
count = count + 1
for i = 1:sizea % for each object in dataset
if(v == 1 && labels(i) == 1 || v == 0 && labels(i) == 2)
errors = 1;
weights(1,1) = weights(1,1) - (2*v-1) * eta * 1;
weights(1,2) = weights(1,2) - (2*v-1) * eta * Z(i,1);
weights(1,3) = weights(1,3) - (2*v-1) * eta * Z(i,2);
v = sum((1*weights(1,1)) + (Z(:,1)*weights(1,2)) + (Z(:,2)*weights(1,3)));
if v >= 1
v = 1;
else
v = 0;
end
end
end
end
There are two major problems in your code:
You need to update v in your loop every time your weights vectors are updated.
It seems like you have 10 training set. So you have to update v sequentially in the loop instead of simultaneously. Keep iterating for every training set, update weights, then use the new weights to calculate the v for the next training set, so on and so forth, until there is no error (errors = 0 in your case).
Minor issue:
if(v >= 0 && labels(i) == 1 || v < 0 && labels(i) == 2)
should be
if(v == 1 && labels(i) == 1 || v == 0 && labels(i) == 2)
You may refer to this example to get more details of the algorithm.