Solve equations with substitution method: Difference between revisions

(Created Nim solution.)
 
(2 intermediate revisions by 2 users not shown)
Line 13:
 
 
 
=={{header|ALGOL 68}}==
{{Trans|Phix|second version (translation of Raku)}}
<syntaxhighlight lang="algol68">
BEGIN # solve equations using the substitution method - translation of Phix #
 
PROC solve2 = ( []REAL e1, e2 )[]REAL:
BEGIN
REAL a1 = e1[ 1 ], b1 = e1[ 2 ], c1 = e1[ 3 ];
REAL a2 = e2[ 1 ], b2 = e2[ 2 ], c2 = e2[ 3 ];
REAL x = (b2*c1 - b1*c2) / (b2*a1 - b1*a2);
REAL y = (a1*x - c1)/-b1;
( x, y )
END # solve2 # ;
 
OP FMT = ( REAL v )STRING: # prints v with at most 3 decimal places #
BEGIN
STRING result := fixed( ABS v, 0, 3 );
IF result[ LWB result ] = "." THEN "0" +=: result FI;
WHILE result[ UPB result ] = "0" DO result := result[ : UPB result - 1 ] OD;
IF result[ UPB result ] = "." THEN result := result[ : UPB result - 1 ] FI;
IF v < 0 THEN "-" ELSE "" FI + result
END # FMT # ;
 
[]REAL xy = solve2( ( 3, 1, -1 ), ( 2, -3, -19 ) );
print( ( "x = ", FMT xy[ 1 ], ", y = ", FMT xy[ 2 ], newline ) )
 
END
</syntaxhighlight>
{{out}}
<pre>
x = -2, y = 5
</pre>
 
=={{header|AWK}}==
Line 43 ⟶ 76:
y = 5
</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
Line 498 ⟶ 532:
 
</pre>
 
=={{header|jq}}==
'''Works with jq, the C implementation of jq'''
 
'''Works with gojq, the Go implementation of jq'''
 
The solution presented here handles all the edge cases.
 
With trivial modifications, the following will also work with jaq, the Rust implementation of jq.
<syntaxhighlight lang="jq">
# The equation ax + by = c is represented by the array [a, b, c]
def solve( $e1; $e2 ):
$e1 as [$a1, $b1, $c1]
| $e2 as [$a2, $b2, $c2]
| ($b2 * $a1 - $b1 * $a2 ) as $d
| if $d == 0 then "there is no unique solution as the discriminant is 0" | error
else
{ x : (($b2 * $c1 - $b1 * $c2 ) / $d) }
| if $b1 != 0
then .y = ( $a1 * .x - $c1 ) / -$b1
else .y = ( $a2 * .x - $c2 ) / -$b2
end
end;
 
solve( [3,1,-1]; [2,-3,-19] )
</syntaxhighlight>
{{output}}
<pre>
{
"x": -2,
"y": 5
}
</pre>
 
 
=={{header|Julia}}==
Line 714 ⟶ 782:
 
=={{header|Wren}}==
<syntaxhighlight lang="ecmascriptwren">var solve = Fn.new { |e1, e2|
e2 = e2.toList
for (i in 1..2) e2[i] = e2[i] * e1[0] / e2[0]
2,442

edits