Law of cosines - triples: Difference between revisions

m
syntax highlighting fixup automation
(Added XPL0 example.)
m (syntax highlighting fixup automation)
Line 39:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">-V n = 13
 
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)</langsyntaxhighlight>
 
{{out}}
Line 84:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Test(INT max,angle,coeff)
BYTE count,a,b,c
 
Line 109:
Test(13,60,1)
Test(13,120,-1)
RETURN</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Ada.Containers.Ordered_Maps;
 
Line 196:
Count_Triangles;
Extra_Credit (Limit => 10_000);
end Law_Of_Cosines;</langsyntaxhighlight>
 
{{out}}
Line 228:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN
# 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</langsyntaxhighlight>
{{out}}
<pre>
Line 304:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f LAW_OF_COSINES_-_TRIPLES.AWK
# converted from C
Line 338:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 374:
=={{header|C}}==
=== A brute force algorithm, O(N^3) ===
<syntaxhighlight lang="c">/*
<lang C>/*
* RossetaCode: Law of cosines - triples
*
Line 417:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 426:
 
=== An algorithm with O(N^2) cost ===
<syntaxhighlight lang="c">/*
<lang C>/*
* RossetaCode: Law of cosines - triples
*
Line 470:
return 0;
}
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 481:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <cmath>
#include <iostream>
#include <tuple>
Line 557:
<< min << " to " << max2 << " where the sides are not all of the same length.\n";
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 574:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
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;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 649:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: backtrack formatting kernel locals math math.ranges
sequences sets sorting ;
IN: rosetta-code.law-of-cosines
Line 668:
[ * + ] 120
[ 2drop 0 - ] 90
[ * - ] 60 [ show-solutions ] 2tri@</langsyntaxhighlight>
{{out}}
<pre>
Line 698:
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">MODULE LAW_OF_COSINES
IMPLICIT NONE
 
Line 850:
END DO
 
END PROGRAM LOC</langsyntaxhighlight>
<pre>
90. degree triangles:
Line 885:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 03-03-2019
' compile with: fbc -s console
 
Line 958:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre> 15: 60 degree triangles
Line 993:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,066:
fmt.Print(" For an angle of 60 degrees")
fmt.Println(" there are", len(solutions), "solutions.")
}</langsyntaxhighlight>
 
{{out}}
Line 1,087:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import qualified Data.Map.Strict as Map
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</langsyntaxhighlight>
{{Out}}
<pre>Triangles of maximum side 13
Line 1,171:
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">load 'trig stats'
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
)</langsyntaxhighlight>
'''Example:'''
<langsyntaxhighlight lang="j"> 60 90 120 solve&.> 13
+--------+-------+------+
| 1 1 1|3 4 5|3 5 7|
Line 1,201:
+--------+-------+------+
60 #@(solve -. _3 ]\ 3 # >:@i.@]) 10000 NB. optional extra credit
18394</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">
public class LawOfCosines {
 
Line 1,249:
 
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,285:
 
=={{header|JavaScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,414:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="jq">def squares(n):
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)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,520:
=={{header|Julia}}==
{{trans|zkl}}
<langsyntaxhighlight lang="julia">sqdict(n) = Dict([(x*x, x) for x in 1:n])
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.")
</langsyntaxhighlight> {{output}} <pre>
 
Integer triples for 1 <= side length <= 13:
Line 1,580:
=={{header|Kotlin}}==
{{trans|Go}}
<langsyntaxhighlight lang="scala">// Version 1.2.70
 
val squares13 = mutableMapOf<Int, Int>()
Line 1,647:
print(" For an angle of 60 degrees")
println(" there are ${solutions.size} solutions.")
}</langsyntaxhighlight>
 
{{output}}
Line 1,668:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function solve(angle, maxlen, filter)
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</langsyntaxhighlight>
{{out}}
<pre>90° on 1..13 has 3 solutions
Line 1,722:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Solve[{a^2+b^2==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<=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</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight lang="nim">import strformat
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."</langsyntaxhighlight>
 
{{out}}
Line 1,823:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use utf8;
binmode STDOUT, "utf8:";
use Sort::Naturally;
Line 1,856:
}
 
printf "Non-equilateral n=10000/60°: %d\n", scalar triples(10000,60);</langsyntaxhighlight>
{{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).
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre style="font-size: 11px">
Line 1,923:
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<langsyntaxhighlight lang="prolog">find_solutions(Limit, Solutions):-
find_solutions(Limit, Solutions, Limit, []).
 
Line 1,986:
write_triples(60, Solutions),
write_triples(90, Solutions),
write_triples(120, Solutions).</langsyntaxhighlight>
 
{{out}}
Line 2,002:
=={{header|Python}}==
===Sets===
<langsyntaxhighlight lang="python">N = 13
 
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)</langsyntaxhighlight>
 
{{out}}
Line 2,045:
A variant Python draft based on dictionaries.
(Test functions are passed as parameters to the main function.)
<langsyntaxhighlight lang="python">from itertools import (starmap)
 
 
Line 2,125:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="rsplus">inputs <- cbind(combn(1:13, 2), rbind(seq_len(13), seq_len(13)))
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.")</langsyntaxhighlight>
{{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" perl6line>multi triples (60, $n) {
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);</langsyntaxhighlight>
{{out}}
<pre>Integer triangular triples for sides 1..13:
Line 2,284:
displayed &nbsp; (using the
<br>absolute value of the negative number).
<langsyntaxhighlight lang="rexx">/*REXX pgm finds integer sided triangles that satisfy Law of cosines for 60º, 90º, 120º.*/
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</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default number of sides for the input: &nbsp; &nbsp; <tt> 13 </tt>}}
<pre>
Line 2,384:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">grouped = (1..13).to_a.repeated_permutation(3).group_by do |a,b,c|
sumaabb, ab = a*a + b*b, a*b
case c*c
Line 2,400:
puts v.inspect, "\n"
end
</syntaxhighlight>
</lang>
{{out}}
<pre>For an angle of 60 there are 15 solutions:
Line 2,412:
</pre>
Extra credit:
<langsyntaxhighlight lang="ruby">n = 10_000
ar = (1..n).to_a
squares = {}
Line 2,419:
 
puts "There are #{count} 60° triangles with unequal sides of max size #{n}."
</syntaxhighlight>
</lang>
{{out}}
<pre>There are 18394 60° triangles with unequal sides of max size 10000.
Line 2,427:
=={{header|Wren}}==
{{trans|Go}}
<langsyntaxhighlight lang="ecmascript">var squares13 = {}
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.")</langsyntaxhighlight>
 
{{out}}
Line 2,508:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">proc LawCos(Eqn);
int Eqn;
int Cnt, A, B, C;
Line 2,548:
[for Case:= 1 to 3 do LawCos(Case);
ExtraCredit;
]</langsyntaxhighlight>
 
{{out}}
Line 2,579:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn tritri(N=13){
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(",")
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">N:=13;
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)));
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,617:
</pre>
Extra credit:
<langsyntaxhighlight lang="zkl">fcn tri60(N){ // special case 60*
sqrset:=[1..N].pump(Dictionary().add.fp1(True),fcn(n){ n*n });
n60:=0;
Line 2,625:
}
n60
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">N:=10_000;
println(("60\U00b0; triangle where side lengths are unique,\n"
" side lengths 1..%,d, there are %,d solutions.").fmt(N,tri60(N)));</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits