Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Generate a Factor translation of this C# snippet without changing its computational steps.
using System; using static System.Console; using System.Collections; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>(); var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.O...
USING: combinators.short-circuit formatting grouping io kernel math.primes.factors math.ranges prettyprint sequences sets ; : sq-free-semiprime? ( n -- ? ) factors { [ length 2 = ] [ all-unique? ] } 1&& ; : odd-sfs-upto ( n -- seq ) 1 swap 2 <range> [ sq-free-semiprime? ] filter ; 999 odd-sfs-upto dup length...
Generate a Factor translation of this C# snippet without changing its computational steps.
using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math; class Program { static int ba; static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static string from10(int b) { string res = ""; int re; while (b > 0) { b = Div...
USING: grouping lists lists.lazy math math.primes.lists present prettyprint ; lprimes [ present [ <= ] monotonic? ] lfilter [ 1000 < ] lwhile [ . ] leach
Change the programming language of this snippet from C# to Factor without modifying what it does.
using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math; class Program { static int ba; static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static string from10(int b) { string res = ""; int re; while (b > 0) { b = Div...
USING: grouping lists lists.lazy math math.primes.lists present prettyprint ; lprimes [ present [ <= ] monotonic? ] lfilter [ 1000 < ] lwhile [ . ] leach
Convert this C# block to Factor, preserving its control flow and logic.
using System; class Program { static void Main(string[] args) { int i, d, s, t, n = 50, c = 1; var sw = new int[n]; for (i = d = s = 1; c < n; i++, s += d += 2) for (t = s; t > 0; t /= 10) if (t < n && sw[t] < 1) Console.Write("", sw[t] = ...
USING: arrays combinators.short-circuit.smart formatting io kernel math sequences ; [let 50 :> lim lim 0 <array> :> res 1 0 :> ( n [ found lim 1 - < ] [ n dup * :> n2 [ n2 zero? ] [ { [ n2 lim < ] [ n2 res nth zero? ] } && [ found 1 + found n2 10 /i n...
Rewrite this program in Factor while keeping its functionality equivalent to the C# version.
using System; class Program { static void Main(string[] args) { int i, d, s, t, n = 50, c = 1; var sw = new int[n]; for (i = d = s = 1; c < n; i++, s += d += 2) for (t = s; t > 0; t /= 10) if (t < n && sw[t] < 1) Console.Write("", sw[t] = ...
USING: arrays combinators.short-circuit.smart formatting io kernel math sequences ; [let 50 :> lim lim 0 <array> :> res 1 0 :> ( n [ found lim 1 - < ] [ n dup * :> n2 [ n2 zero? ] [ { [ n2 lim < ] [ n2 res nth zero? ] } && [ found 1 + found n2 10 /i n...
Write the same code in Factor as shown below in C#.
using System; using System.Collections.Generic; using System.Linq; public static class IntersectingNumberWheels { public static void Main() { TurnWheels(('A', "123")).Take(20).Print(); TurnWheels(('A', "1B2"), ('B', "34")).Take(20).Print(); TurnWheels(('A', "1DD"), ('D', "678")).Take(20).Pr...
USING: accessors assocs circular io kernel lists lists.lazy math math.parser multiline peg.ebnf prettyprint prettyprint.custom sequences strings ; IN: rosetta-code.number-wheels TUPLE: group pretty list ; C: <group> group M: group pprint* pretty>> write ; TUPLE: number-wheel seq i ; : <number-wheel> ( seq -- numbe...
Write a version of this C# function in Factor with identical behavior.
using System; using System.Collections.Generic; using System.Linq; public static class IntersectingNumberWheels { public static void Main() { TurnWheels(('A', "123")).Take(20).Print(); TurnWheels(('A', "1B2"), ('B', "34")).Take(20).Print(); TurnWheels(('A', "1DD"), ('D', "678")).Take(20).Pr...
USING: accessors assocs circular io kernel lists lists.lazy math math.parser multiline peg.ebnf prettyprint prettyprint.custom sequences strings ; IN: rosetta-code.number-wheels TUPLE: group pretty list ; C: <group> group M: group pprint* pretty>> write ; TUPLE: number-wheel seq i ; : <number-wheel> ( seq -- numbe...
Change the following C# code into Factor without altering its purpose.
using System; public class CirclesOfGivenRadiusThroughTwoPoints { public static void Main() { double[][] values = new double[][] { new [] { 0.1234, 0.9876, 0.8765, 0.2345, 2 }, new [] { 0.0, 2.0, 0.0, 0.0, 1 }, new [] { 0.1234, 0.9876, 0.1234, 0.9876, ...
USING: accessors combinators combinators.short-circuit formatting io kernel literals locals math math.distances math.functions prettyprint sequences strings ; IN: rosetta-code.circles DEFER: find-circles TUPLE: input p1 p2 r ; CONSTANT: test-cases { T{ input f { 0.1234 0.9876 } { 0.8765 0.2345 } 2 } T{ inpu...
Rewrite this program in Factor while keeping its functionality equivalent to the C# version.
using System; public class CirclesOfGivenRadiusThroughTwoPoints { public static void Main() { double[][] values = new double[][] { new [] { 0.1234, 0.9876, 0.8765, 0.2345, 2 }, new [] { 0.0, 2.0, 0.0, 0.0, 1 }, new [] { 0.1234, 0.9876, 0.1234, 0.9876, ...
USING: accessors combinators combinators.short-circuit formatting io kernel literals locals math math.distances math.functions prettyprint sequences strings ; IN: rosetta-code.circles DEFER: find-circles TUPLE: input p1 p2 r ; CONSTANT: test-cases { T{ input f { 0.1234 0.9876 } { 0.8765 0.2345 } 2 } T{ inpu...
Convert this C# snippet to Factor and keep its semantics consistent.
using System; namespace RosettaVampireNumber { class Program { static void Main(string[] args) { int i, j, n; ulong x; var f = new ulong[16]; var bigs = new ulong[] { 16758243290880UL, 24959017348650UL, 14593825548650UL, 0 }; ulong[] t...
USING: combinators.short-circuit fry io kernel lists lists.lazy math math.combinatorics math.functions math.primes.factors math.statistics math.text.utils prettyprint sequences sets ; IN: rosetta-code.vampire-number : digits ( n -- m ) log10 floor >integer 1 + ; : same-digits? ( n n1 n2 -- ? ) [ 1 digit-group...
Can you help me rewrite this code in Factor instead of C#, keeping it the same logically?
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class PokerHandAnalyzer { private enum Hand { Invalid, High_Card, One_Pair, Two_Pair, Three_Of_A_Kind, Straight, Flush, Full_House, Four_Of_A_Kind, Straight_Flush, Five_Of_A_Kind } private co...
USING: formatting kernel poker sequences ; { "2H 2D 2C KC QD" "2H 5H 7D 8C 9S" "AH 2D 3C 4C 5D" "2H 3H 2D 3C 3D" "2H 7H 2D 3C 3D" "2H 7H 7D 7C 7S" "TH JH QH KH AH" "4H 4S KS 5D TS" "QC TC 7C 6C 4C" } [ dup string>hand-name "%s: %s\n" printf ] each
Ensure the translated Factor code behaves exactly like the original C# snippet.
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class PokerHandAnalyzer { private enum Hand { Invalid, High_Card, One_Pair, Two_Pair, Three_Of_A_Kind, Straight, Flush, Full_House, Four_Of_A_Kind, Straight_Flush, Five_Of_A_Kind } private co...
USING: formatting kernel poker sequences ; { "2H 2D 2C KC QD" "2H 5H 7D 8C 9S" "AH 2D 3C 4C 5D" "2H 3H 2D 3C 3D" "2H 7H 2D 3C 3D" "2H 7H 7D 7C 7S" "TH JH QH KH AH" "4H 4S KS 5D TS" "QC TC 7C 6C 4C" } [ dup string>hand-name "%s: %s\n" printf ] each
Produce a functionally identical Factor code for the snippet given in C#.
using static System.Console; using static System.Threading.Thread; using System; public static class PenneysGame { const int pause = 500; const int N = 3; static Random rng = new Random(); static int Toss() => rng.Next(2); static string AsString(this int sequence) { string s = ""; ...
USING: arrays ascii io kernel math prettyprint random sequences strings ; IN: rosetta-code.penneys-game : t|f ( -- t/f ) 1 random-bits 0 = ; : valid-input? ( seq -- ? ) [ [ CHAR: H = ] [ CHAR: T = ] bi or ] filter length 3 = ; : input-seq ( -- seq ) "Please input a 3-long sequence of H or T (heads or ...
Change the programming language of this snippet from C# to Factor without modifying what it does.
using System; namespace EbanNumbers { struct Interval { public int start, end; public bool print; public Interval(int start, int end, bool print) { this.start = start; this.end = end; this.print = print; } } class Program { stati...
USING: arrays formatting fry io kernel math math.functions math.order math.ranges prettyprint sequences ; : eban? ( n -- ? ) 1000000000 /mod 1000000 /mod 1000 /mod [ dup 30 66 between? [ 10 mod ] when ] tri@ 4array [ { 0 2 4 6 } member? ] all? ; : .eban ( m n -- ) "eban numbers in [%d, %d]: " printf ; : e...
Convert this C# snippet to Factor and keep its semantics consistent.
using System; namespace EbanNumbers { struct Interval { public int start, end; public bool print; public Interval(int start, int end, bool print) { this.start = start; this.end = end; this.print = print; } } class Program { stati...
USING: arrays formatting fry io kernel math math.functions math.order math.ranges prettyprint sequences ; : eban? ( n -- ? ) 1000000000 /mod 1000000 /mod 1000 /mod [ dup 30 66 between? [ 10 mod ] when ] tri@ 4array [ { 0 2 4 6 } member? ] all? ; : .eban ( m n -- ) "eban numbers in [%d, %d]: " printf ; : e...
Write the same algorithm in Factor as shown in this C# implementation.
using System; public static class Angles { public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000); public static void Print(params double[] angles) { string[] names = { "Degrees", "Gradians", "Mils", "Radians" }; Func<double, double> rnd = a => Mat...
USING: accessors combinators formatting inverse kernel math math.constants quotations qw sequences units.si ; IN: rosetta-code.angles ALIAS: degrees arc-deg : gradiens ( n -- d ) 9/10 * degrees ; : mils ( n -- d ) 9/160 * degrees ; : normalize ( d -- d' ) [ 2 pi * mod ] change-value ; CONSTANT: units { degrees gradien...
Port the following code from C# to Factor with equivalent syntax and logic.
XmlReader XReader; XReader = XmlReader.Create(new StringReader("<inventory title=... </inventory>")); XReader = XmlReader.Create("xmlfile.xml"); IXPathNavigable XDocument = new XPathDocument(XReader); XPathNavigator Nav = XDocument.CreateNavigator(); Nav = Nav.SelectSingleNode(" if(Nav.MoveToFirst()) { ...
"""<inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> ...
Port the following code from C# to Factor with equivalent syntax and logic.
using System; using System.Collections.Generic; using System.Linq; namespace RankingMethods { class Program { static void Main(string[] args) { Dictionary<string, int> scores = new Dictionary<string, int> { ["Solomon"] = 44, ["Jason"] = 42, ["Erro...
USING: arrays assocs formatting fry generalizations io kernel math math.ranges math.statistics math.vectors sequences splitting.monotonic ; IN: rosetta-code.ranking CONSTANT: ranks { { 44 "Solomon" } { 42 "Jason" } { 42 "Errol" } { 41 "Garry" } { 41 "Bernard" } { 41 "Barry" } { 39 "Stephen" } } : rank ( s...
Convert this C# block to Factor, preserving its control flow and logic.
using System; using System.Collections.Generic; using System.IO; namespace IBeforeE { class Program { static bool IsOppPlausibleWord(string word) { if (!word.Contains("c") && word.Contains("ei")) { return true; } if (word.Contains("cie")) { ...
USING: combinators formatting generalizations io.encodings.utf8 io.files kernel literals math prettyprint regexp sequences ; IN: rosetta-code.i-before-e : correct ( #correct #incorrect rule-str -- ) pprint " is correct for %d and incorrect for %d.\n" printf ; : plausibility ( #correct #incorrect -- str ) 2 * ...
Transform the following C# implementation into Factor, maintaining the same output and logic.
using System; using System.Collections.Generic; using System.IO; namespace IBeforeE { class Program { static bool IsOppPlausibleWord(string word) { if (!word.Contains("c") && word.Contains("ei")) { return true; } if (word.Contains("cie")) { ...
USING: combinators formatting generalizations io.encodings.utf8 io.files kernel literals math prettyprint regexp sequences ; IN: rosetta-code.i-before-e : correct ( #correct #incorrect rule-str -- ) pprint " is correct for %d and incorrect for %d.\n" printf ; : plausibility ( #correct #incorrect -- str ) 2 * ...
Change the following C# code into Factor without altering its purpose.
using System; using System.Collections.Generic; using System.Linq; public static class FareySequence { public static void Main() { for (int i = 1; i <= 11; i++) { Console.WriteLine($"F{i}: " + string.Join(", ", Generate(i).Select(f => $"{f.num}/{f.den}"))); } for (int i = 100; i...
USING: formatting io kernel math math.primes.factors math.ranges locals prettyprint sequences sequences.extras sets tools.time ; IN: rosetta-code.farey-sequence :: p/q ( n a/b c/d -- p/q ) a/b c/d [ >fraction ] bi@ :> ( a b c d ) n b + d / >integer [ c * a - ] [ d * b - ] bi / ; : print-farey ( order --...
Write the same code in Factor as shown below in C#.
using System; using System.Collections.Generic; using System.Linq; public static class FareySequence { public static void Main() { for (int i = 1; i <= 11; i++) { Console.WriteLine($"F{i}: " + string.Join(", ", Generate(i).Select(f => $"{f.num}/{f.den}"))); } for (int i = 100; i...
USING: formatting io kernel math math.primes.factors math.ranges locals prettyprint sequences sequences.extras sets tools.time ; IN: rosetta-code.farey-sequence :: p/q ( n a/b c/d -- p/q ) a/b c/d [ >fraction ] bi@ :> ( a b c d ) n b + d / >integer [ c * a - ] [ d * b - ] bi / ; : print-farey ( order --...
Maintain the same structure and functionality when rewriting this code in Factor.
using System; using static System.Console; class Program { static bool[] np; static void ms(long lmt) { np = new bool[lmt]; np[0] = np[1] = true; for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n]) for (long k = n * n; k < lmt; k += n) np[k] = true; } static bool is_Mag(long n) { lon...
USING: grouping io kernel lists lists.lazy math math.functions math.primes math.ranges prettyprint sequences ; : magnanimous? ( n -- ? ) dup 10 < [ drop t ] [ dup log10 >integer [1,b] [ 10^ /mod + prime? not ] with find nip >boolean not ] if ; : magnanimous ( n -- seq ) 0 lfrom [ magnanimo...
Generate a Factor translation of this C# snippet without changing its computational steps.
using System; using System.Numerics; namespace MersennePrimes { class Program { static BigInteger Sqrt(BigInteger x) { if (x < 0) throw new ArgumentException("Negative argument."); if (x < 2) return x; BigInteger y = x / 2; while (y > x / y) { ...
USING: formatting math.primes.lucas-lehmer math.ranges sequences ; : mersennes-upto ( n -- seq ) [1,b] [ lucas-lehmer ] filter ; 3500 mersennes-upto [ "2 ^ %d - 1\n" printf ] each
Write the same algorithm in Factor as shown in this C# implementation.
using System; using System.Numerics; namespace MersennePrimes { class Program { static BigInteger Sqrt(BigInteger x) { if (x < 0) throw new ArgumentException("Negative argument."); if (x < 2) return x; BigInteger y = x / 2; while (y > x / y) { ...
USING: formatting math.primes.lucas-lehmer math.ranges sequences ; : mersennes-upto ( n -- seq ) [1,b] [ lucas-lehmer ] filter ; 3500 mersennes-upto [ "2 ^ %d - 1\n" printf ] each
Convert the following code from C# to Factor, ensuring the logic remains intact.
using static System.Console; using static System.Linq.Enumerable; using System; public static class StrongAndWeakPrimes { public static void Main() { var primes = PrimeGenerator(10_000_100).ToList(); var strongPrimes = from i in Range(1, primes.Count - 2) where primes[i] > (primes[i-1] + primes[i+1...
USING: formatting grouping kernel math math.primes sequences tools.memory.private ; IN: rosetta-code.strong-primes : fn ( p-1 p p+1 -- p sum ) rot + 2 / ; : strong? ( p-1 p p+1 -- ? ) fn > ; : weak? ( p-1 p p+1 -- ? ) fn < ; : swprimes ( seq quot -- seq ) [ 3 <clumps> ] dip [ first3 ] prepose filter [ second ] ma...
Keep all operations the same but rewrite the snippet in Factor.
using System; using System.Collections.Generic; using static System.Console; using System.Linq; using DT = System.DateTime; class Program { static void Main(string[] args) { string s; foreach (int lmt in new int[]{ 90, 300, 3000, 30000, 111000 }) { var pr = PG.Primes(lmt).Skip(1).ToList(); DT st = DT.Now; in...
USING: formatting io kernel math math.combinatorics math.primes sequences tools.memory.private ; : .triplet ( seq -- ) "%2d+%2d+%2d = %d\n" vprintf ; : strange ( n -- ) primes-upto 3 [ dup sum dup prime? [ suffix .triplet ] [ 2drop ] if ] each-combination ; : count-strange ( n -- count ) 0 swap prime...
Ensure the translated Factor code behaves exactly like the original C# snippet.
using System; using System.Collections.Generic; using static System.Console; using System.Linq; using DT = System.DateTime; class Program { static void Main(string[] args) { string s; foreach (int lmt in new int[]{ 90, 300, 3000, 30000, 111000 }) { var pr = PG.Primes(lmt).Skip(1).ToList(); DT st = DT.Now; in...
USING: formatting io kernel math math.combinatorics math.primes sequences tools.memory.private ; : .triplet ( seq -- ) "%2d+%2d+%2d = %d\n" vprintf ; : strange ( n -- ) primes-upto 3 [ dup sum dup prime? [ suffix .triplet ] [ 2drop ] if ] each-combination ; : count-strange ( n -- count ) 0 swap prime...
Produce a language-to-language conversion: from C# to Factor, same semantics.
using System; using BI = System.Numerics.BigInteger; class Program { static bool hmf(BI x) { if (x < 4) return x == 1; if ((x & 1) == 0 || x % 3 == 0) return true; int l = (int)Math.Sqrt((double)x); for (int j = 5, d = 4; j <= l; j += d = 6 - d) if (x % j == 0) return x > j; return f...
USING: combinators formatting io kernel math math.primes tools.memory.private ; MEMO: motzkin ( m -- n ) dup 2 < [ drop 1 ] [ { [ 2 * 1 + ] [ 1 - motzkin * ] [ 3 * 3 - ] [ 2 - motzkin * + ] [ 2 + /i ] } cleave ] if ; " n ...
Write the same code in Factor as shown below in C#.
using System; namespace MagicSquareDoublyEven { class Program { static void Main(string[] args) { int n = 8; var result = MagicSquareDoublyEven(n); for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLengt...
USING: arrays combinators.short-circuit formatting fry generalizations kernel math math.matrices prettyprint sequences ; IN: rosetta-code.doubly-even-magic-squares : top? ( loc n -- ? ) [ second ] dip 1/4 * < ; : bottom? ( loc n -- ? ) [ second ] dip 3/4 * >= ; : left? ( loc n -- ? ) [ first ] dip 1/4 * < ; : ...
Translate this program into Factor but keep the logic exactly as in C#.
using System; using System.Linq; using System.Collections.Generic; public class Program { public static void Main() { const int maxSum = 100; var pairs = ( from X in 2.To(maxSum / 2 - 1) from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum) select ...
USING: combinators.short-circuit fry kernel literals math math.ranges memoize prettyprint sequences sets tools.time ; IN: rosetta-code.sum-and-product CONSTANT: s1 $[ 2 100 [a,b] dup cartesian-product concat [ first2 { [ < ] [ + 100 < ] } 2&& ] filter ] : quot-eq ( pair quot -- seq ) [ s1 ] 2dip tuck '[ @...
Maintain the same structure and functionality when rewriting this code in Factor.
using System; using System.Linq; using static System.Console; class Program { static int nxtPrime(int x) { int j = 2; do { if (x % j == 0) { j = 2; x++; } else j += j < 3 ? 1 : 2; } while (j * j <= x); return x; } static void Main(string[] args) { WriteLine("working..."); int[] Nu...
USING: math math.order math.primes prettyprint sequences ; { 5 45 23 21 67 } { 43 22 78 46 38 } { 9 98 12 54 53 } [ max max 1 - next-prime ] 3map .
Produce a functionally identical Factor code for the snippet given in C#.
using System; using System.Collections.Generic; class Program { static List<uint> sieve(uint max, bool ordinary = false) { uint k = ((max - 3) >> 1) + 1, lmt = ((uint)(Math.Sqrt(max++) - 3) >> 1) + 1; var pl = new List<uint> { }; var ic = new bool[k]; for (u...
USING: grouping io lists lists.lazy literals math math.primes numspec prettyprint ; << DIGIT: o 357 DIGIT: q 1379 DIGIT: e 2468 DIGIT: E 02468 NUMSPEC: one-odd-candidates o eq eEq ... ; >> CONSTANT: p $[ one-odd-candidates [ prime? ] lfilter ] "Primes with one odd digit under 1,000:" print p [ 1000 < ] lwhile list>...
Write the same code in Factor as shown below in C#.
using System; using System.Collections.Generic; class Program { static List<uint> sieve(uint max, bool ordinary = false) { uint k = ((max - 3) >> 1) + 1, lmt = ((uint)(Math.Sqrt(max++) - 3) >> 1) + 1; var pl = new List<uint> { }; var ic = new bool[k]; for (u...
USING: grouping io lists lists.lazy literals math math.primes numspec prettyprint ; << DIGIT: o 357 DIGIT: q 1379 DIGIT: e 2468 DIGIT: E 02468 NUMSPEC: one-odd-candidates o eq eEq ... ; >> CONSTANT: p $[ one-odd-candidates [ prime? ] lfilter ] "Primes with one odd digit under 1,000:" print p [ 1000 < ] lwhile list>...
Preserve the algorithm and functionality while converting the code from C# to Factor.
using static System.Console; using System; using System.Collections; using System.Collections.Generic; using System.Linq; public static class SafePrimes { public static void Main() { HashSet<int> primes = Primes(10_000_000).ToHashSet(); WriteLine("First 35 safe primes:"); WriteLine(string.J...
USING: fry interpolate kernel literals math math.primes sequences tools.memory.private ; IN: rosetta-code.safe-primes CONSTANT: primes $[ 10,000,000 primes-upto ] : safe/unsafe ( -- safe unsafe ) primes [ 1 - 2/ prime? ] partition ; : count< ( seq n -- str ) '[ _ < ] count commas ; : seq>commas ( seq -- str ) [...
Change the following C# code into Factor without altering its purpose.
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class Solve24Game { public static void Main2() { var testCases = new [] { new [] { 1,1,2,7 }, new [] { 1,2,3,4 }, new [] { 1,2,4,5 }, new [] { 1,2,7,7 }, ...
USING: continuations grouping io kernel math math.combinatorics prettyprint quotations random sequences sequences.deep ; IN: rosetta-code.24-game : 4digits ( -- seq ) 4 9 random-integers [ 1 + ] map ; : expressions ( digits -- exprs ) all-permutations [ [ + - * / ] 3 selections [ append ] with map ] map flatt...
Generate a Factor translation of this C# snippet without changing its computational steps.
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class Solve24Game { public static void Main2() { var testCases = new [] { new [] { 1,1,2,7 }, new [] { 1,2,3,4 }, new [] { 1,2,4,5 }, new [] { 1,2,7,7 }, ...
USING: continuations grouping io kernel math math.combinatorics prettyprint quotations random sequences sequences.deep ; IN: rosetta-code.24-game : 4digits ( -- seq ) 4 9 random-integers [ 1 + ] map ; : expressions ( digits -- exprs ) all-permutations [ [ + - * / ] 3 selections [ append ] with map ] map flatt...
Rewrite this program in Factor while keeping its functionality equivalent to the C# version.
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; public class TruthTable { enum TokenType { Unknown, WhiteSpace, Constant, Operand, Operator, LeftParenthesis, RightParenthesis } readonly char trueConstant, falseConstant; readonly IDictionary<c...
USING: arrays combinators eval formatting io kernel listener math.combinatorics prettyprint qw sequences splitting vocabs.parser ; IN: rosetta-code.truth-table : prompt ( -- str ) "Please enter a boolean expression using 1-long" print "variable names and postfix notation. Available" print "operators are an...
Convert this C# block to Factor, preserving its control flow and logic.
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; public class TruthTable { enum TokenType { Unknown, WhiteSpace, Constant, Operand, Operator, LeftParenthesis, RightParenthesis } readonly char trueConstant, falseConstant; readonly IDictionary<c...
USING: arrays combinators eval formatting io kernel listener math.combinatorics prettyprint qw sequences splitting vocabs.parser ; IN: rosetta-code.truth-table : prompt ( -- str ) "Please enter a boolean expression using 1-long" print "variable names and postfix notation. Available" print "operators are an...
Port the provided C# code into Factor while preserving the original functionality.
using System; using System.Collections.Generic; using BI = System.Numerics.BigInteger; using lbi = System.Collections.Generic.List<System.Numerics.BigInteger[]>; using static System.Console; class Program { struct LI { public UInt64 lo, ml, mh, hi, tp; } const UInt64 Lm = 1_000_000_000_000_000_000UL; ...
USING: arrays formatting io kernel lists lists.lazy math math.functions math.ranges math.text.utils prettyprint sequences ; IN: rosetta-code.super-d : super-d? ( seq n d -- ? ) tuck ^ * 1 digit-groups subseq? ; : super-d ( d -- list ) [ dup <array> ] [ drop 1 lfrom ] [ ] tri [ super-d? ] curry with lfilter ; ...
Write the same algorithm in Factor as shown in this C# implementation.
using System; using System.Collections.Generic; using BI = System.Numerics.BigInteger; using lbi = System.Collections.Generic.List<System.Numerics.BigInteger[]>; using static System.Console; class Program { struct LI { public UInt64 lo, ml, mh, hi, tp; } const UInt64 Lm = 1_000_000_000_000_000_000UL; ...
USING: arrays formatting io kernel lists lists.lazy math math.functions math.ranges math.text.utils prettyprint sequences ; IN: rosetta-code.super-d : super-d? ( seq n d -- ? ) tuck ^ * 1 digit-groups subseq? ; : super-d ( d -- list ) [ dup <array> ] [ drop 1 lfrom ] [ ] tri [ super-d? ] curry with lfilter ; ...
Rewrite this program in Factor while keeping its functionality equivalent to the C# version.
using System; namespace RosettaMaybe { public abstract class Maybe<T> { public sealed class Some : Maybe<T> { public Some(T value) => Value = value; public T Value { get; } } public sealed class None : Maybe<T> { } } class Program { ...
USING: monads ; FROM: monads => do ; 3 maybe-monad return >>= [ 2 * maybe-monad return ] swap call >>= [ 1 + maybe-monad return ] swap call . nothing >>= [ 2 * maybe-monad return ] swap call >>= [ 1 + maybe-monad return ] swap call .
Can you help me rewrite this code in Factor instead of C#, keeping it the same logically?
using System; using System.Reflection; public class Rosetta { public static void Main() { BindingFlags flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; foreach (var method in typeof(...
USING: io math prettyprint see ; "The list of methods contained in the generic word + :" print \ + methods . nl "The list of methods specializing on the fixnum class:" print fixnum methods .
Produce a functionally identical Factor code for the snippet given in C#.
using System; class Example { public int foo(int x) { return 42 + x; } } class Program { static void Main(string[] args) { var example = new Example(); var method = "foo"; var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5...
USING: accessors kernel math prettyprint sequences words ; IN: rosetta-code.unknown-method-call TUPLE: foo num ; C: <foo> foo GENERIC: add5 ( x -- y ) M: foo add5 num>> 5 + ; 42 <foo> "add" "5" append "rosetta-code.unknown-method-call" lookup-word execute .
Can you help me rewrite this code in Factor instead of C#, keeping it the same logically?
using System; using System.Net; using System.Linq; public class Program { public static void Main() { string[] tests = { "87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29", "67.137.119.181/4", "161.214.74.21/24", ...
USING: command-line formatting grouping io kernel math.parser namespaces prettyprint sequences splitting ; IN: rosetta-code.canonicalize-cidr command-line get [ lines ] when-empty [ "/" split first2 string>number swap "." split [ string>number "%08b" sprintf ] map "" join over cut length ...
Rewrite the snippet below in Factor so it works the same as the original C# code.
using System; using System.Net; using System.Linq; public class Program { public static void Main() { string[] tests = { "87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29", "67.137.119.181/4", "161.214.74.21/24", ...
USING: command-line formatting grouping io kernel math.parser namespaces prettyprint sequences splitting ; IN: rosetta-code.canonicalize-cidr command-line get [ lines ] when-empty [ "/" split first2 string>number swap "." split [ string>number "%08b" sprintf ] map "" join over cut length ...
Port the following code from C# to Factor with equivalent syntax and logic.
using System; using System.Collections.Generic; using System.Linq; public static class LongPrimes { public static void Main() { var primes = SomePrimeGenerator.Primes(64000).Skip(1).Where(p => Period(p) == p - 1).Append(99999); Console.WriteLine(string.Join(" ", primes.TakeWhile(p => p <= 500))); ...
USING: formatting fry io kernel math math.functions math.primes math.primes.factors memoize prettyprint sequences ; IN: rosetta-code.long-primes : period-length ( p -- len ) [ 1 - divisors ] [ '[ 10 swap _ ^mod 1 = ] ] bi find nip ; MEMO: long-prime? ( p -- ? ) [ period-length ] [ 1 - ] bi = ; : .lp<=500 ( -- ) ...
Transform the following C# implementation into Factor, maintaining the same output and logic.
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace EgyptianFractions { class Program { class Rational : IComparable<Rational>, IComparable<int> { public BigInteger Num { get; } public B...
USING: backtrack formatting fry kernel locals make math math.functions math.ranges sequences ; IN: rosetta-code.egyptian-fractions : >improper ( r -- str ) >fraction "%d/%d" sprintf ; : improper ( x y -- a b ) [ /i ] [ [ rem ] [ nip ] 2bi / ] 2bi ; :: proper ( x y -- a b ) y x / ceiling :> d1 1 d1 / y neg x rem ...
Change the programming language of this snippet from C# to Factor without modifying what it does.
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace EgyptianFractions { class Program { class Rational : IComparable<Rational>, IComparable<int> { public BigInteger Num { get; } public B...
USING: backtrack formatting fry kernel locals make math math.functions math.ranges sequences ; IN: rosetta-code.egyptian-fractions : >improper ( r -- str ) >fraction "%d/%d" sprintf ; : improper ( x y -- a b ) [ /i ] [ [ rem ] [ nip ] 2bi / ] 2bi ; :: proper ( x y -- a b ) y x / ceiling :> d1 1 d1 / y neg x rem ...
Rewrite the snippet below in Factor so it works the same as the original C# code.
using System; using System.Collections.Generic; using System.Linq; static class Program { static List<long> primes = new List<long>() { 3, 5 }; static void Main(string[] args) { const int cutOff = 200; const int bigUn = 100000; const int chunks = 50; const int little = big...
USING: formatting grouping io kernel lists lists.lazy math math.primes sequences tools.memory.private ; IN: rosetta-code.cuban-primes : cuban-primes ( n -- seq ) 1 lfrom [ [ 3 * ] [ 1 + * ] bi 1 + ] <lazy-map> [ prime? ] <lazy-filter> ltake list>array ; 200 cuban-primes 10 <groups> [ [ commas ] map [ "%10s" p...
Produce a functionally identical Factor code for the snippet given in C#.
using System; using BI = System.Numerics.BigInteger; using static System.Console; class Program { static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) { q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }   static string dump(int digs, bool show = false) {...
USING: continuations formatting io kernel locals math math.factorials math.functions sequences ; :: integer-term ( n -- m ) 32 6 n * factorial * 532 n sq * 126 n * + 9 + * n factorial 6 ^ 3 * / ; : exponent-term ( n -- m ) 6 * 3 + neg ; : nth-term ( n -- x ) [ integer-term ] [ exponent-term 10^ * ] bi ; ...
Generate a Factor translation of this C# snippet without changing its computational steps.
using System; using BI = System.Numerics.BigInteger; using static System.Console; class Program { static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) { q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }   static string dump(int digs, bool show = false) {...
USING: continuations formatting io kernel locals math math.factorials math.functions sequences ; :: integer-term ( n -- m ) 32 6 n * factorial * 532 n sq * 126 n * + 9 + * n factorial 6 ^ 3 * / ; : exponent-term ( n -- m ) 6 * 3 + neg ; : nth-term ( n -- x ) [ integer-term ] [ exponent-term 10^ * ] bi ; ...
Maintain the same structure and functionality when rewriting this code in Factor.
using System; class Program { static long js(int l, int n) { long res = 0, f = 1; double lf = Math.Log10(2); for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * Math.Pow(10, ++res * lf % 1)) == l) n--; return res; } static ...
USING: formatting fry generalizations kernel literals math math.functions math.parser sequences tools.time ; CONSTANT: ld10 $[ 2 log 10 log / ] : p ( L n -- m ) swap [ 0 0 ] [ '[ over _ >= ] ] [ [ log10 >integer 10^ ] keep ] tri* '[ 1 + dup ld10 * dup >integer - 10 log * e^ _ * truncate ...
Can you help me rewrite this code in Factor instead of C#, keeping it the same logically?
using System; class Program { static long js(int l, int n) { long res = 0, f = 1; double lf = Math.Log10(2); for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * Math.Pow(10, ++res * lf % 1)) == l) n--; return res; } static ...
USING: formatting fry generalizations kernel literals math math.functions math.parser sequences tools.time ; CONSTANT: ld10 $[ 2 log 10 log / ] : p ( L n -- m ) swap [ 0 0 ] [ '[ over _ >= ] ] [ [ log10 >integer 10^ ] keep ] tri* '[ 1 + dup ld10 * dup >integer - 10 log * e^ _ * truncate ...
Produce a functionally identical Factor code for the snippet given in C#.
using System; using System.Numerics; namespace CipollaAlgorithm { class Program { static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151; private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) { BigInteger n = BigInteger.Parse(ns); BigInteger p = ...
USING: accessors assocs interpolate io kernel literals locals math math.extras math.functions ; TUPLE: point x y ; C: <point> point :: (cipolla) ( n p -- m ) 0 0 :> ( a [ ω2 p legendere -1 = ] [ a sq n - p rem ω2 [| a b | a x>> b x>> * a y>> b y>> ω2 * * + p mod a x>> b y>> * b x>> a ...
Keep all operations the same but rewrite the snippet in Factor.
using System; using System.Numerics; namespace CipollaAlgorithm { class Program { static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151; private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) { BigInteger n = BigInteger.Parse(ns); BigInteger p = ...
USING: accessors assocs interpolate io kernel literals locals math math.extras math.functions ; TUPLE: point x y ; C: <point> point :: (cipolla) ( n p -- m ) 0 0 :> ( a [ ω2 p legendere -1 = ] [ a sq n - p rem ω2 [| a b | a x>> b x>> * a y>> b y>> ω2 * * + p mod a x>> b y>> * b x>> a ...
Translate the given C# code snippet into Factor without altering its behavior.
using System; using System.Collections.Generic; using System.Numerics; namespace PierpontPrimes { public static class Helper { private static readonly Random rand = new Random(); private static readonly List<int> primeList = new List<int>() { 2, 3, 5, 7, 11, 13, 17, 19, 23,...
USING: fry grouping io kernel locals make math math.functions math.primes prettyprint sequences sorting ; : pierpont ( ulim vlim quot -- seq ) '[ _ <iota> _ <iota> [ [ 2 ] [ 3 ] bi* [ swap ^ ] 2bi@ * 1 @ dup prime? [ , ] [ drop ] if ] cartesian-each ] { } make natural-so...
Ensure the translated Factor code behaves exactly like the original C# snippet.
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; namespace NSmooth { class Program { static readonly List<BigInteger> primes = new List<BigInteger>(); static readonly List<int> smallPrimes = new List<int>(); static Program() { primes.Add...
USING: deques dlists formatting fry io kernel locals make math math.order math.primes math.text.english namespaces prettyprint sequences tools.memory.private ; IN: rosetta-code.n-smooth-numbers SYMBOL: primes : ns ( n -- seq ) primes-upto [ primes set ] [ length [ 1 1dlist ] replicate ] bi ; : enqueue ( n ...
Generate an equivalent Factor version of this C# code.
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable; public static class Rosetta { static void Main() { foreach ((int x, int n) in new [] { (99809, 1), (18, 2), (19, 3), (20, 4), (2017,...
USING: formatting fry grouping kernel math.combinatorics math.parser math.primes sequences ; : partition ( x n -- str ) over [ primes-upto ] 2dip '[ sum _ = ] find-combination [ number>string ] map "+" join ; : print-partition ( x n seq -- ) [ "no solution" ] when-empty "Partitioned %5d with %2d p...
Ensure the translated Factor code behaves exactly like the original C# snippet.
using System; using System.Collections.Generic; using System.Linq; namespace RosettaVectors { public class Vector { public double[] store; public Vector(IEnumerable<double> init) { store = init.ToArray(); } public Vector(double x, double y) { ...
(scratchpad) USE: math.vectors (scratchpad) { 1 2 } { 3 4 } v+ --- Data stack: { 4 6 }
Transform the following C# implementation into Factor, maintaining the same output and logic.
using System; using System.Collections.Generic; using System.Linq; namespace BurrowsWheeler { class Program { const char STX = (char)0x02; const char ETX = (char)0x03; private static void Rotate(ref char[] a) { char t = a.Last(); for (int i = a.Length - 1; i > 0; --...
USING: formatting io kernel math.transforms.bwt sequences ; { "banana" "dogwood" "TO BE OR NOT TO BE OR WANT TO BE OR NOT?" "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES" } [ [ print ] [ bwt ] bi 2dup " bwt-->%3d %u\n" printf ibwt " ibwt-> %u\n" printf nl ] each
Write the same code in Factor as shown below in C#.
using System; using System.Collections.Generic; using System.Linq; namespace BurrowsWheeler { class Program { const char STX = (char)0x02; const char ETX = (char)0x03; private static void Rotate(ref char[] a) { char t = a.Last(); for (int i = a.Length - 1; i > 0; --...
USING: formatting io kernel math.transforms.bwt sequences ; { "banana" "dogwood" "TO BE OR NOT TO BE OR WANT TO BE OR NOT?" "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES" } [ [ print ] [ bwt ] bi 2dup " bwt-->%3d %u\n" printf ibwt " ibwt-> %u\n" printf nl ] each
Translate this program into Factor but keep the logic exactly as in C#.
using System; namespace FaulhabersTriangle { internal class Frac { private long num; private long denom; public static readonly Frac ZERO = new Frac(0, 1); public static readonly Frac ONE = new Frac(1, 1); public Frac(long n, long d) { if (d == 0) { ...
USING: kernel math math.combinatorics math.extras math.functions math.ranges prettyprint sequences ; : faulhaber ( p -- seq ) 1 + dup recip swap dup 0 (a,b] [ [ nCk ] [ -1 swap ^ ] [ bernoulli ] tri * * * ] 2with map ; 10 [ faulhaber . ] each-integer
Maintain the same structure and functionality when rewriting this code in Factor.
using System; namespace FaulhabersFormula { internal class Frac { private long num; private long denom; public static readonly Frac ZERO = new Frac(0, 1); public static readonly Frac ONE = new Frac(1, 1); public Frac(long n, long d) { if (d == 0) { ...
USING: formatting kernel math math.combinatorics math.extras math.functions regexp sequences ; : faulhaber ( p -- seq ) 1 + dup recip swap dup <iota> [ [ nCk ] [ -1 swap ^ ] [ bernoulli ] tri * * * ] 2with map ; : (poly>str) ( seq -- str ) reverse [ 1 + "%un^%d" sprintf ] map-index reverse " + " join ; :...
Maintain the same structure and functionality when rewriting this code in Factor.
using System; namespace PrimeConspiracy { class Program { static void Main(string[] args) { const int limit = 1_000_000; const int sieveLimit = 15_500_000; int[,] buckets = new int[10, 10]; int prevDigit = 2; bool[] notPrime = Sieve(sieveLimit); ...
USING: assocs formatting grouping kernel math math.primes math.statistics sequences sorting ; IN: rosetta-code.prime-conspiracy : transitions ( n -- alist ) nprimes [ 10 mod ] map 2 clump histogram >alist natural-sort ; : t-values ( transition -- i j count freq ) first2 [ first2 ] dip dup 10000. / ; : print-...
Write the same code in Factor as shown below in C#.
using System; using MathNet.Numerics.Distributions; using MathNet.Numerics.Statistics; class Program { static void RunNormal(int sampleSize) { double[] X = new double[sampleSize]; var norm = new Normal(new Random()); norm.Samples(X); const int numBuckets = 10; var histo...
USING: assocs formatting kernel math math.functions math.statistics random sequences sorting ; 2,000,000 [ 0 1 normal-random-float ] replicate dup [ mean ] [ population-std ] bi "Mean: %f\nStdev: %f\n\n" printf [ 10 * floor 10 / ] map histogram >alist [ first ] ...
Translate this program into Factor but keep the logic exactly as in C#.
using System; using System.Collections.Generic; using static System.Console; class Program { static string B10(int n) { int[] pow = new int[n + 1], val = new int[29]; for (int count = 0, ten = 1, x = 1; x <= n; x++) { val[x] = ten; for (int j = 0, t; j <= n; j++) if (pow[j] != 0 && pow...
: is-1-or-0 ( char -- ? ) dup CHAR: 0 = [ drop t ] [ CHAR: 1 = ] if ; : int-is-B10 ( n -- ? ) unparse [ is-1-or-0 ] all? ; : B10-step ( x x -- x x ? ) dup int-is-B10 [ f ] [ over + t ] if ; : find-B10 ( x -- x ) dup [ B10-step ] loop nip ;
Rewrite the snippet below in Factor so it works the same as the original C# code.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WeirdNumbers { class Program { static List<int> Divisors(int n) { List<int> divs = new List<int> { 1 }; List<int> divs2 = new List<int>(); for (...
USING: combinators.short-circuit io kernel lists lists.lazy locals math math.primes.factors prettyprint sequences ; IN: rosetta-code.weird-numbers :: has-sum? ( n seq -- ? ) seq [ f ] [ unclip-slice :> ( xs x ) n x < [ n xs has-sum? ] [ { [ n x = ] [ n x ...
Produce a functionally identical Factor code for the snippet given in C#.
using System; using System.Numerics; namespace MontgomeryReduction { public static class Helper { public static int BitLength(this BigInteger v) { if (v < 0) { v *= -1; } int result = 0; while (v > 0) { v >>= 1; ...
USING: io kernel locals math math.bitwise math.functions prettyprint ; : montgomery-reduce ( m a -- n ) over bit-length [ dup odd? [ over + ] when 2/ ] times swap mod ; CONSTANT: m 750791094644726559640638407699 CONSTANT: t1 323165824550862327179367294465482435542970161392400401329100 CONSTANT: r1 4401600251...
Generate an equivalent Factor version of this C# code.
using System; using System.Collections.Generic; using System.Linq; namespace ZumkellerNumbers { class Program { static List<int> GetDivisors(int n) { List<int> divs = new List<int> { 1, n }; for (int i = 2; i * i <= n; i++) { if (n % i == ...
USING: combinators grouping io kernel lists lists.lazy math math.primes.factors memoize prettyprint sequences ; MEMO: psum? ( seq n -- ? ) { { [ dup zero? ] [ 2drop t ] } { [ over length zero? ] [ 2drop f ] } { [ over last over > ] [ [ but-last ] dip psum? ] } [ [ [ but-...
Generate a Factor translation of this C# snippet without changing its computational steps.
static string[] inputs = { "pi=3.14159265358979323846264338327950288419716939937510582097494459231", "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "\"-in Aus$+1411.8millions\"", "===US$0017440 millions=== (in 2000 dollars)" }; void Main() { inputs.Select(s => Commatize(s, 0, 3, ",")) ...
USING: accessors grouping io kernel math regexp sequences splitting strings unicode ; : numeric ( str -- new-str ) R/ [1-9][0-9]*/ first-match >string ; : commas ( numeric-str period separator -- str ) [ reverse ] [ group ] [ reverse join reverse ] tri* ; : (commatize) ( text from period separator -- str ) ...
Change the following C# code into Factor without altering its purpose.
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; public static class Reflection { public static void Main() { var t = new TestClass(); var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; foreach (var prop in GetPropert...
USING: assocs kernel math mirrors prettyprint strings ; TUPLE: foo { bar string } { baz string initial: "hi" } { baxx integer initial: 50 read-only } ; C: <foo> foo "apple" "banana" 200 <foo> <mirror> [ >alist ] [ object-slots ] bi [ . ] bi@
Ensure the translated Factor code behaves exactly like the original C# snippet.
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace MarkovChainTextGenerator { class Program { static string Join(string a, string b) { return a + " " + b; } static string Markov(string filePath, int keySize, int outputSize) { ...
USING: assocs fry grouping io io.encodings.ascii io.files kernel make math random sequences splitting ; : build-markov-assoc ( path n -- assoc ) [ ascii file-contents " " split harvest ] dip 1 + clump H{ } clone tuck [ [ unclip-last swap ] dip push-at ] curry each ; : first-word ( assoc -- next-key ) rand...
Write the same algorithm in Factor as shown in this C# implementation.
using System; class Program { const long Lm = (long)1e18; const string Fm = "D18"; struct LI { public long lo, ml, mh, hi, tp; } static void inc(ref LI d, LI s) { if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; } if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; } if ((d....
USING: kernel lists lists.lazy math sequences sequences.extras ; : penta ( n -- m ) [ sq 3 * ] [ - 2/ ] bi ; : seq ( -- list ) 1 lfrom [ penta 1 - ] <lazy-map> 1 lfrom [ neg penta 1 - ] <lazy-map> lmerge ; : ++-- ( seq -- n ) 0 [ 2/ odd? [ - ] [ + ] if ] reduce-index ; : step ( seq pseq -- seq 'pseq )...
Convert the following code from C# to Factor, ensuring the logic remains intact.
using System; namespace SpecialDivisors { class Program { static int Reverse(int n) { int result = 0; while (n > 0) { result = 10 * result + n % 10; n /= 10; } return result; } static void Main() { ...
USING: grouping kernel math.functions math.parser math.primes.factors math.ranges prettyprint sequences ; : reverse-number ( n -- reversed ) 10 >base reverse dec> ; : special? ( n -- ? ) [ reverse-number ] [ divisors ] bi [ reverse-number divisor? ] with all? ; 200 [1..b] [ special? ] filter 18 group simple-...
Convert this C# block to Factor, preserving its control flow and logic.
using System.Linq; using System.Collections.Generic; using TG = System.Tuple<int, int>; using static System.Console; class Program { static void Main(string[] args) { const int mil = (int)1e6; foreach (var amt in new int[] { 1, 2, 6, 12, 18 }) { int lmt = mil * amt, lg = 0, ...
USING: arrays assocs formatting grouping io kernel literals math math.primes math.statistics sequences sequences.extras tools.memory.private ; << CONSTANT: limit 1,000,000 >> CONSTANT: primes $[ limit primes-upto ] : run ( n quot -- seq quot ) [ primes ] [ <clumps> ] [ ] tri* '[ differences _ monotonic? ] ; ...
Maintain the same structure and functionality when rewriting this code in Factor.
using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static BI IntSqRoot(BI v, BI res) { BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1; dl = d; d = term - res; } return term; } static stri...
USING: combinators decimals formatting generalizations io kernel math prettyprint qw sequences ; IN: rosetta-code.metallic-ratios : lucas ( n a b -- n a' b' ) tuck reach * + ; : lucas. ( n -- ) 1 pprint bl 1 1 14 [ lucas over pprint bl ] times 3drop nl ; : approx ( a b -- d ) swap [ 0 <decimal> ] bi@ 32 D/ ; : ...
Generate a Factor translation of this C# snippet without changing its computational steps.
using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static BI IntSqRoot(BI v, BI res) { BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1; dl = d; d = term - res; } return term; } static stri...
USING: combinators decimals formatting generalizations io kernel math prettyprint qw sequences ; IN: rosetta-code.metallic-ratios : lucas ( n a b -- n a' b' ) tuck reach * + ; : lucas. ( n -- ) 1 pprint bl 1 1 14 [ lucas over pprint bl ] times 3drop nl ; : approx ( a b -- d ) swap [ 0 <decimal> ] bi@ 32 D/ ; : ...
Generate a Factor translation of this C# snippet without changing its computational steps.
using System; namespace Rosetta { internal class Vector { private double[] b; internal readonly int rows; internal Vector(int rows) { this.rows = rows; b = new double[rows]; } internal Vector(double[] initArray) { b =...
USING: kernel math.matrices math.matrices.elimination prettyprint sequences ; : augment-identity ( matrix -- new-matrix ) dup first length <identity-matrix> [ flip ] bi@ append flip ; : gauss-jordan-invert ( matrix -- inverted ) dup square-matrix? [ "Matrix must be square." throw ] unless aug...
Change the programming language of this snippet from C# to Factor without modifying what it does.
using System; namespace Rosetta { internal class Vector { private double[] b; internal readonly int rows; internal Vector(int rows) { this.rows = rows; b = new double[rows]; } internal Vector(double[] initArray) { b =...
USING: kernel math.matrices math.matrices.elimination prettyprint sequences ; : augment-identity ( matrix -- new-matrix ) dup first length <identity-matrix> [ flip ] bi@ append flip ; : gauss-jordan-invert ( matrix -- inverted ) dup square-matrix? [ "Matrix must be square." throw ] unless aug...
Produce a functionally identical Factor code for the snippet given in C#.
using System; class Program { static bool dc8(uint n) { uint res = 1, count, p, d; for ( ; (n & 1) == 0; n >>= 1) res++; for (count = 1; n % 3 == 0; n /= 3) count++; for (p = 5, d = 4; p * p <= n; p += d = 6 - d) for (res *= count, count = 1; n % p == 0; n /= p) count++; return n > 1 ? re...
USING: formatting grouping io kernel lists lists.lazy math prettyprint project-euler.common ; : A111398 ( -- list ) L{ 1 } 2 lfrom [ tau 8 = ] lfilter lappend-lazy ; 50 A111398 ltake list>array 10 group simple-table. nl 499 4999 49999 [ [ 1 + ] keep A111398 lnth "%5dth: %d\n" printf ] tri@
Port the following code from C# to Factor with equivalent syntax and logic.
using System; class Program { static void fun(char sp) { var sw = System.Diagnostics.Stopwatch.StartNew(); for (int x = sp == '1' ? 7654321 : 76543201; ; x -= 18) { var s = x.ToString(); for (var ch = sp; ch < '8'; ch++) if (s.IndexOf(ch) < 0)...
USING: io kernel math math.combinatorics math.functions math.primes math.ranges present sequences sequences.cords ; { 4 7 } [ [1,b] <permutations> ] [ cord-append ] map-reduce [ reverse 0 [ 10^ * + ] reduce-index prime? ] find-last nip "The largest pandigital decimal prime is: " print [ present write ] each nl
Please provide an equivalent version of this C# code in Factor.
using System; class Program { static void fun(char sp) { var sw = System.Diagnostics.Stopwatch.StartNew(); for (int x = sp == '1' ? 7654321 : 76543201; ; x -= 18) { var s = x.ToString(); for (var ch = sp; ch < '8'; ch++) if (s.IndexOf(ch) < 0)...
USING: io kernel math math.combinatorics math.functions math.primes math.ranges present sequences sequences.cords ; { 4 7 } [ [1,b] <permutations> ] [ cord-append ] map-reduce [ reverse 0 [ 10^ * + ] reduce-index prime? ] find-last nip "The largest pandigital decimal prime is: " print [ present write ] each nl
Change the programming language of this snippet from Go to REXX without modifying what it does.
package main import ( "fmt" "rcu" "sort" ) func main() { const LIMIT = 99 primes := rcu.Primes(LIMIT) rmap := make(map[int]bool) for _, p := range primes { for _, q := range primes { var pq int if q < 10 { pq = p*10 + q } else { ...
parse arg hip cols . if hip=='' | hip=="," then hip= 100 if cols=='' | cols=="," then cols= 10 call genP title= ' concatenation of two neighbor primes (P1, P2) in base ten that results in' , ...
Write the same code in REXX as shown below in Go.
func assert(t bool, s string) { if !t { panic(s) } } assert(c == 0, "some text here")
parse arg top . if top=='' | top=="," then top= 100 _= left('', 9) w= length(top) + 1 do #=1 for 666 a= random(1, top) b= random(1, ...
Produce a functionally identical REXX code for the snippet given in Go.
func assert(t bool, s string) { if !t { panic(s) } } assert(c == 0, "some text here")
parse arg top . if top=='' | top=="," then top= 100 _= left('', 9) w= length(top) + 1 do #=1 for 666 a= random(1, top) b= random(1, ...
Rewrite this program in REXX while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "runtime" "sync" ) func main() { p := sync.Pool{New: func() interface{} { fmt.Println("pool empty") return new(int) }} i := new(int) j := new(int) *i = 1 *j = 2 fmt.Println(*i + *j) p.P...
stemmed_array.= 0 stemmed_array.1 = '1st entry' stemmed_array.2 = '2nd entry' stemmed_array.6000 = 12 ** 2 stemmed_array.dog = stemmed_array.6000 / 2 drop stemmed_array.
Convert this Go block to REXX, preserving its control flow and logic.
package main import ( "fmt" "runtime" "sync" ) func main() { p := sync.Pool{New: func() interface{} { fmt.Println("pool empty") return new(int) }} i := new(int) j := new(int) *i = 1 *j = 2 fmt.Println(*i + *j) p.P...
stemmed_array.= 0 stemmed_array.1 = '1st entry' stemmed_array.2 = '2nd entry' stemmed_array.6000 = 12 ** 2 stemmed_array.dog = stemmed_array.6000 / 2 drop stemmed_array.
Translate the given Go code snippet into REXX without altering its behavior.
package main import ( "fmt" "sort" "sync" "time" ) type history struct { timestamp tsFunc hs []hset } type tsFunc func() time.Time type hset struct { int t time.Time } func newHistory(ts tsFunc) history { return history{ts, []hset{{t: ts()}}} } ...
varSet!.=0 call varSet 'fluid',min(0,-5/2,-1) ; say 'fluid=' fluid call varSet 'fluid',3.14159 ; say 'fluid=' fluid call varSet 'fluid',' Santa Claus' ; say 'fluid=' fluid call varSet 'fluid',,999 say 'There were' result "assignments (sets) for the FLU...
Keep all operations the same but rewrite the snippet in REXX.
package main import ( "bytes" "fmt" "io/ioutil" "log" "runtime" ) func main() { fileName1 := "rodgers.txt" fileName2 := "rodgers_reversed.txt" lineBreak := "\n" if runtime.GOOS == "windows" { lineBreak = "\r\n" } b, err := ioutil.ReadFile(fileName1) if err ...
parse arg iFID . if iFID=='' | iFID=="," then iFID='REVERSEF.TXT' call lineout iFID do #=1 while lines(iFID)>0 @.#= linein(iFID) end recs= # - 1 ...
Keep all operations the same but rewrite the snippet in REXX.
func multiply(a, b float64) float64 { return a * b }
options replace format comments java crossref savelog symbols binary pi = 3.14159265358979323846264338327950 radiusY = 10 in2ft = 12 ft2yds = 3 in2mm = 25.4 mm2m = 1 / 1000 radiusM = multiply(multiply(radiusY, multiply(multiply(ft2yds, in2ft), in2mm)), mm2m) say "Area of a circle" radiusY "yds radius: "...
Produce a language-to-language conversion: from Go to REXX, same semantics.
package main import ( "fmt" "rcu" ) func main() { fmt.Println("Decimal numbers under 1,000 whose digits include two 1's:") var results []int for i := 11; i <= 911; i++ { digits := rcu.Digits(i, 10) count := 0 for _, d := range digits { if d == 1 { ...
parse arg hi cols . if hi=='' | hi=="," then hi= 1000 if cols=='' | cols=="," then cols= 10 w= 10 title= ' positive decimal integers which contain exactly two ones (1s) which are <' hi say ' index │'center(title, ...
Can you help me rewrite this code in REXX instead of Go, keeping it the same logically?
package main import ( "fmt" "sort" ) func main() { strings := []string{"1a3c52debeffd", "2b6178c97a938stf", "3ycxdb1fgxa2yz"} u := make(map[rune]int) for _, s := range strings { m := make(map[rune]int) for _, c := range s { m[c]++ } for k, v := range m {...
parse arg $ if $='' | $="," then $= '1a3c52debeffd' "2b6178c97a938stf" '3ycxdb1fgxa2yz' if $='' then do; say "***error*** no lists were specified."; exit 13; end #= words($); $$= do i=1 for #; !.i= word($, i) ...
Change the programming language of this snippet from Go to REXX without modifying what it does.
package main import "fmt" func sieve(limit int) []int { primes := []int{2} c := make([]bool, limit+1) p := 3 for { p2 := p * p if p2 > limit { break } for i := p2; i <= limit; i += 2 * p { c[i] = true } for { p +...
parse arg H . 1 . difs if H=='' | H=="," then H= 1000000 if difs='' then difs= 2 1 2.2 2.4 4.2 6.4.2 call genP H do j=1 for words(difs) dif= translate( word(difs, j),,.); dw= words(dif) do i=1 for dw; dif.i...
Produce a language-to-language conversion: from Go to REXX, same semantics.
package main import ( "fmt" "rcu" ) func main() { var numbers []int for i := 2; i < 200; i++ { bds := rcu.DigitSum(i, 2) if rcu.IsPrime(bds) { tds := rcu.DigitSum(i, 3) if rcu.IsPrime(tds) { numbers = append(numbers, i) } } ...
parse arg n cols . if n=='' | n=="," then n= 200 if cols=='' | cols=="," then cols= 10 call genP w= 10 title= ' positive integers whose binary and ternary digit sums are pr...
Generate an equivalent REXX version of this Go code.
package main import "fmt" func isPrime(n int) bool { if n == 1 { return false } i := 2 for i*i <= n { if n%i == 0 { return false } i++ } return true } func main() { var final, pNum int for i := 1; pNum < 10001; i++ { if isPrime(i) {...
Parse Version v Say v Call Time 'R' z=1 p.0=3 p.1=2 p.2=3 p.3=5 Do n=5 By 2 Until z=10001 If right(n,1)=5 Then Iterate Do i=2 To p.0 Until b**2>n b=p.i If n//b=0 Then Leave End If b**2>n Then Do z=p.0+1 p.z=n p.0=z End End Say z n time('E')
Rewrite the snippet below in REXX so it works the same as the original Go code.
package main import "fmt" func isPrime(n int) bool { if n == 1 { return false } i := 2 for i*i <= n { if n%i == 0 { return false } i++ } return true } func main() { var final, pNum int for i := 1; pNum < 10001; i++ { if isPrime(i) {...
Parse Version v Say v Call Time 'R' z=1 p.0=3 p.1=2 p.2=3 p.3=5 Do n=5 By 2 Until z=10001 If right(n,1)=5 Then Iterate Do i=2 To p.0 Until b**2>n b=p.i If n//b=0 Then Leave End If b**2>n Then Do z=p.0+1 p.z=n p.0=z End End Say z n time('E')
Convert the following code from Go to REXX, ensuring the logic remains intact.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(999) sum, n, c := 0, 0, 0 fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:") fmt.Println(" n cumulative sum") for _, p := range primes { n++ sum += p if rcu.IsPri...
parse arg hi . if hi=='' | hi=="," then hi= 1000 call genP w= 30; w2= w*2%3; pad= left('',w-w2) title= ' summation primes which the sum of primes up to P is also prime, P < ' , ...
Translate the given Go code snippet into REXX without altering its behavior.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(999) sum, n, c := 0, 0, 0 fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:") fmt.Println(" n cumulative sum") for _, p := range primes { n++ sum += p if rcu.IsPri...
parse arg hi . if hi=='' | hi=="," then hi= 1000 call genP w= 30; w2= w*2%3; pad= left('',w-w2) title= ' summation primes which the sum of primes up to P is also prime, P < ' , ...
Convert the following code from Go to REXX, ensuring the logic remains intact.
package main import ( "fmt" "os" "golang.org/x/crypto/ssh/terminal" ) func main() { w, h, err := terminal.GetSize(int(os.Stdout.Fd())) if err != nil { fmt.Println(err) return } fmt.Println(h, w) }
width = 'tput'( 'cols' ) height = 'tput'( 'lines' ) say 'The terminal is' width 'characters wide' say 'and has' height 'lines'