Law of cosines - triples: Difference between revisions
m
syntax highlighting fixup automation
(Added XPL0 example.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 39:
{{trans|Python}}
<
F method1(n)
Line 69:
V t60 = method1(10'000)[1]
V notsame = sum(t60.filter((a, b, c) -> a != b | b != c).map((a, b, c) -> 1))
print(‘Extra credit: ’notsame)</
{{out}}
Line 84:
=={{header|Action!}}==
<
BYTE count,a,b,c
Line 109:
Test(13,60,1)
Test(13,120,-1)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Law_of_cosines_-_triples.png Screenshot from Atari 8-bit computer]
Line 127:
=={{header|Ada}}==
<
with Ada.Containers.Ordered_Maps;
Line 196:
Count_Triangles;
Extra_Credit (Limit => 10_000);
end Law_Of_Cosines;</
{{out}}
Line 228:
=={{header|ALGOL 68}}==
<
# find all integer sided 90, 60 and 120 degree triangles by finding integer solutions for #
# a^2 + b^2 = c^2, a^2 + b^2 - ab = c^2, a^2 + b^2 + ab = c^2 where a, b, c in 1 .. 13 #
Line 275:
print triangles( 90 );
print triangles( 120 )
END</
{{out}}
<pre>
Line 304:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f LAW_OF_COSINES_-_TRIPLES.AWK
# converted from C
Line 338:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 374:
=={{header|C}}==
=== A brute force algorithm, O(N^3) ===
<syntaxhighlight lang="c">/*
* RossetaCode: Law of cosines - triples
*
Line 417:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 426:
=== An algorithm with O(N^2) cost ===
<syntaxhighlight lang="c">/*
* RossetaCode: Law of cosines - triples
*
Line 470:
return 0;
}
</syntaxhighlight>
{{output}}
<pre>
Line 481:
=={{header|C++}}==
<
#include <iostream>
#include <tuple>
Line 557:
<< min << " to " << max2 << " where the sides are not all of the same length.\n";
return 0;
}</
{{out}}
Line 574:
=={{header|C sharp}}==
<
using System.Collections.Generic;
using static System.Linq.Enumerable;
Line 616:
private static bool NotAllTheSameLength((int a, int b, int c) triple) => triple.a != triple.b || triple.a != triple.c;
}</
{{out}}
<pre>
Line 649:
=={{header|Factor}}==
<
sequences sets sorting ;
IN: rosetta-code.law-of-cosines
Line 668:
[ * + ] 120
[ 2drop 0 - ] 90
[ * - ] 60 [ show-solutions ] 2tri@</
{{out}}
<pre>
Line 698:
=={{header|Fortran}}==
<
IMPLICIT NONE
Line 850:
END DO
END PROGRAM LOC</
<pre>
90. degree triangles:
Line 885:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 958:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre> 15: 60 degree triangles
Line 993:
=={{header|Go}}==
<
import "fmt"
Line 1,066:
fmt.Print(" For an angle of 60 degrees")
fmt.Println(" there are", len(solutions), "solutions.")
}</
{{out}}
Line 1,087:
=={{header|Haskell}}==
<
import qualified Data.Set as Set
import Data.Monoid ((<>))
Line 1,135:
[120, 90, 60])
putStrLn "60 degrees - uneven triangles of maximum side 10000. Total:"
print $ length $ triangles f60ne 10000</
{{Out}}
<pre>Triangles of maximum side 13
Line 1,171:
=={{header|J}}==
'''Solution:'''
<
RHS=: *: NB. right-hand-side of Cosine Law
LHS=: +/@:*:@] - cos@rfd@[ * 2 * */@] NB. Left-hand-side of Cosine Law
Line 1,180:
idx=. (RHS oppside) i. x LHS"1 adjsides
adjsides ((#~ idx ~: #) ,. ({~ idx -. #)@]) oppside
)</
'''Example:'''
<
+--------+-------+------+
| 1 1 1|3 4 5|3 5 7|
Line 1,201:
+--------+-------+------+
60 #@(solve -. _3 ]\ 3 # >:@i.@]) 10000 NB. optional extra credit
18394</
=={{header|Java}}==
<
public class LawOfCosines {
Line 1,249:
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,285:
=={{header|JavaScript}}==
<
'use strict';
Line 1,414:
// MAIN ---
return main();
})();</
{{Out}}
<pre>Triangles of maximum side 13:
Line 1,454:
To save space, we define `squares` as a hash rather than as a JSON array.
<
reduce range(1; 1+n) as $i ({}; .[$i*$i|tostring] = $i);
Line 1,501:
| " For an angle of \(degrees) degrees, there are \(.) solutions.") ;
task1([90, 60, 120]), "", task2(60; 10000)</
{{out}}
<pre>
Line 1,520:
=={{header|Julia}}==
{{trans|zkl}}
<
numnotsame(arrarr) = sum(map(x -> !all(y -> y == x[1], x), arrarr))
Line 1,547:
println("Angle 120:"); for t in tri120 println(t) end
println("\nFor sizes N through 10000, there are $(numnotsame(filtertriangles(10000)[1])) 60 degree triples with nonequal sides.")
</
Integer triples for 1 <= side length <= 13:
Line 1,580:
=={{header|Kotlin}}==
{{trans|Go}}
<
val squares13 = mutableMapOf<Int, Int>()
Line 1,647:
print(" For an angle of 60 degrees")
println(" there are ${solutions.size} solutions.")
}</
{{output}}
Line 1,668:
=={{header|Lua}}==
<
local squares, roots, solutions = {}, {}, {}
local cos2 = ({[60]=-1,[90]=0,[120]=1})[angle]
Line 1,692:
solve(60, 10000, fexcr) -- extra credit
solve(90, 10000, fexcr) -- more extra credit
solve(120, 10000, fexcr) -- even more extra credit</
{{out}}
<pre>90° on 1..13 has 3 solutions
Line 1,722:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
Length[%]
Solve[{a^2+b^2-a b==c^2,1<=a<=13,1<=b<=13,1<=c<=13,a<=b},{a,b,c},Integers]
Line 1,728:
Solve[{a^2+b^2+a b==c^2,1<=a<=13,1<=b<=13,1<=c<=13,a<=b},{a,b,c},Integers]
Length[%]
Solve[{a^2+b^2-a b==c^2,1<=a<=10000,1<=b<=10000,1<=c<=10000,a<=b,a!=b,b!=c,a!=c},{a,b,c},Integers]//Length</
{{out}}
<pre>{{a->3,b->4,c->5},{a->5,b->12,c->13},{a->6,b->8,c->10}}
Line 1,739:
=={{header|Nim}}==
<
import tables
Line 1,797:
echo "\nFor sides in the range [1, 10000] where they cannot ALL be of the same length:\n"
var solutions = solve(60, 10000, false)
echo fmt" For an angle of 60 degrees there are {len(solutions)} solutions."</
{{out}}
Line 1,823:
=={{header|Perl}}==
{{trans|Raku}}
<
binmode STDOUT, "utf8:";
use Sort::Naturally;
Line 1,856:
}
printf "Non-equilateral n=10000/60°: %d\n", scalar triples(10000,60);</
{{out}}
<pre>Integer triangular triples for sides 1..13:
Line 1,866:
=={{header|Phix}}==
Using a simple flat sequence of 100 million elements (well within the desktop language limits, but beyond JavaScript) proved significantly faster than a dictionary (5x or so).
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #000080;font-style:italic;">--constant lim = iff(platform()=JS?13:10000)</span>
Line 1,910:
<span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Non-equilateral angle 60 triangles for sides 1..10000: %d%s\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">solve</span><span style="color: #0000FF;">(</span><span style="color: #000000;">60</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10000</span><span style="color: #0000FF;">,</span><span style="color: #004600;">false</span><span style="color: #0000FF;">),</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">--end if</span>
<!--</
{{out}}
<pre style="font-size: 11px">
Line 1,923:
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<
find_solutions(Limit, Solutions, Limit, []).
Line 1,986:
write_triples(60, Solutions),
write_triples(90, Solutions),
write_triples(120, Solutions).</
{{out}}
Line 2,002:
=={{header|Python}}==
===Sets===
<
def method1(N=N):
Line 2,030:
_, t60, _ = method1(10_000)
notsame = sum(1 for a, b, c in t60 if a != b or b != c)
print('Extra credit:', notsame)</
{{out}}
Line 2,045:
A variant Python draft based on dictionaries.
(Test functions are passed as parameters to the main function.)
<
Line 2,125:
if __name__ == '__main__':
main()</
{{Out}}
<pre>Triangles of maximum side 13
Line 2,161:
=={{header|R}}==
This looks a bit messy, but it really pays off when you see how nicely the output prints.
<
inputs <- cbind(A = inputs[1, ], B = inputs[2, ])[sort.list(inputs[1, ]),]
Pythagoras <- inputs[, "A"]^2 + inputs[, "B"]^2
Line 2,175:
sum(!is.na(output[, 3])), "solutions in the 90º case,",
sum(!is.na(output[, 4])), "solutions in the 60º case, and",
sum(!is.na(output[, 5])), "solutions in the 120º case.")</
{{out}}
<pre> A B C (90º) C (60º) C (120º)
Line 2,203:
(formerly Perl 6)
In each routine, <tt>race</tt> is used to allow concurrent operations, requiring the use of the atomic increment operator, <tt>⚛++</tt>, to safely update <tt>@triples</tt>, which must be declared fixed-sized, as an auto-resizing array is not thread-safe. At exit, default values in <tt>@triples</tt> are filtered out with the test <code>!eqv Any</code>.
<syntaxhighlight lang="raku"
my %sq = (1..$n).map: { .² => $_ };
my atomicint $i = 0;
Line 2,254:
my ($angle, $count) = 60, 10_000;
say "\nExtra credit:";
say "$angle° integer triples in the range 1..$count where the sides are not all the same length: ", +triples($angle, $count);</
{{out}}
<pre>Integer triangular triples for sides 1..13:
Line 2,284:
displayed (using the
<br>absolute value of the negative number).
<
parse arg os1 os2 os3 os4 . /*obtain optional arguments from the CL*/
if os1=='' | os1=="," then os1= 13; s1=abs(os1) /*Not specified? Then use the default.*/
Line 2,343:
end /*b*/
end /*a*/
call foot s4; return</
{{out|output|text= when using the default number of sides for the input: <tt> 13 </tt>}}
<pre>
Line 2,384:
=={{header|Ruby}}==
<
sumaabb, ab = a*a + b*b, a*b
case c*c
Line 2,400:
puts v.inspect, "\n"
end
</syntaxhighlight>
{{out}}
<pre>For an angle of 60 there are 15 solutions:
Line 2,412:
</pre>
Extra credit:
<
ar = (1..n).to_a
squares = {}
Line 2,419:
puts "There are #{count} 60° triangles with unequal sides of max size #{n}."
</syntaxhighlight>
{{out}}
<pre>There are 18394 60° triangles with unequal sides of max size 10000.
Line 2,427:
=={{header|Wren}}==
{{trans|Go}}
<
var squares10000 = {}
Line 2,487:
solutions = solve.call(60, 10000, false)
System.write(" For an angle of 60 degrees")
System.print(" there are %(solutions.count) solutions.")</
{{out}}
Line 2,508:
=={{header|XPL0}}==
<
int Eqn;
int Cnt, A, B, C;
Line 2,548:
[for Case:= 1 to 3 do LawCos(Case);
ExtraCredit;
]</
{{out}}
Line 2,579:
=={{header|zkl}}==
<
sqrset:=[0..N].pump(Dictionary().add.fp1(True),fcn(n){ n*n });
tri90, tri60, tri120 := List(),List(),List();
Line 2,599:
tri.sort(fcn(t1,t2){ t1[0]<t2[0] })
.apply("concat",",").apply("(%s)".fmt).concat(",")
}</
<
println("Integer triangular triples for sides 1..%d:".fmt(N));
foreach angle, triples in (T(60,90,120).zip(tritri(N))){
println(" %3d\U00B0; has %d solutions:\n %s"
.fmt(angle,triples.len(),triToStr(triples)));
}</
{{out}}
<pre>
Line 2,617:
</pre>
Extra credit:
<
sqrset:=[1..N].pump(Dictionary().add.fp1(True),fcn(n){ n*n });
n60:=0;
Line 2,625:
}
n60
}</
<
println(("60\U00b0; triangle where side lengths are unique,\n"
" side lengths 1..%,d, there are %,d solutions.").fmt(N,tri60(N)));</
{{out}}
<pre>
|