Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Maintain the same structure and functionality when rewriting this code in J.
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 { static void Main() { Interval[] intervals = { new Interval(2, 1_000, true), new Interval(1_000, 4_000, true), new Interval(2, 10_000, false), new Interval(2, 100_000, false), new Interval(2, 1_000_000, false), new Interval(2, 10_000_000, false), new Interval(2, 100_000_000, false), new Interval(2, 1_000_000_000, false), }; foreach (var intv in intervals) { if (intv.start == 2) { Console.WriteLine("eban numbers up to and including {0}:", intv.end); } else { Console.WriteLine("eban numbers between {0} and {1} (inclusive):", intv.start, intv.end); } int count = 0; for (int i = intv.start; i <= intv.end; i += 2) { int b = i / 1_000_000_000; int r = i % 1_000_000_000; int m = r / 1_000_000; r = i % 1_000_000; int t = r / 1_000; r %= 1_000; if (m >= 30 && m <= 66) m %= 10; if (t >= 30 && t <= 66) t %= 10; if (r >= 30 && r <= 66) r %= 10; if (b == 0 || b == 2 || b == 4 || b == 6) { if (m == 0 || m == 2 || m == 4 || m == 6) { if (t == 0 || t == 2 || t == 4 || t == 6) { if (r == 0 || r == 2 || r == 4 || r == 6) { if (intv.print) Console.Write("{0} ", i); count++; } } } } } if (intv.print) { Console.WriteLine(); } Console.WriteLine("count = {0}\n", count); } } } }
Filter =: (#~`)(`:6) itemAmend =: (29&< *. <&67)`(,: 10&|)} iseban =: [: *./ 0 2 4 6 e.~ [: itemAmend [: |: (4#1000)&#: (;~ #) iseban Filter >: i. 1000 β”Œβ”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚19β”‚2 4 6 30 32 34 36 40 42 44 46 50 52 54 56 60 62 64 66β”‚ β””β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ({. , {:) INPUT =: 1000 + i. 3001 1000 4000 (;~ #) iseban Filter INPUT β”Œβ”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚21β”‚2000 2002 2004 2006 2030 2032 2034 2036 2040 2042 2044 2046 2050 2052 2054 2056 2060 2062 2064 2066 4000β”‚ β””β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ (, ([: +/ [: iseban [: >: i.))&> 10000 * 10 ^ i. +:2 10000 79 100000 399 1e6 399 1e7 1599
Convert this C# block to J, preserving its control flow and logic.
class Test { static bool valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) { if (nuts % n != 1) { return false; } } return nuts != 0 && (nuts % n == 0); } static void Main(string[] args) { int x = 0; for (int n = 2; n < 10; n++) { while (!valid(n, x)) x++; System.Console.WriteLine(n + ": " + x); } } }
I.(=<.)%&5 verb def'4*(y-1)%5'^:5 i.10000 3121
Change the programming language of this snippet from C# to J without modifying what it does.
class Test { static bool valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) { if (nuts % n != 1) { return false; } } return nuts != 0 && (nuts % n == 0); } static void Main(string[] args) { int x = 0; for (int n = 2; n < 10; n++) { while (!valid(n, x)) x++; System.Console.WriteLine(n + ": " + x); } } }
I.(=<.)%&5 verb def'4*(y-1)%5'^:5 i.10000 3121
Preserve the algorithm and functionality while converting the code from C# to J.
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Windows.Threading; namespace Polyspiral { public partial class Form1 : Form { private double inc; public Form1() { Width = Height = 640; StartPosition = FormStartPosition.CenterScreen; SetStyle( ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true); var timer = new DispatcherTimer(); timer.Tick += (s, e) => { inc = (inc + 0.05) % 360; Refresh(); }; timer.Interval = new TimeSpan(0, 0, 0, 0, 40); timer.Start(); } private void DrawSpiral(Graphics g, int len, double angleIncrement) { double x1 = Width / 2; double y1 = Height / 2; double angle = angleIncrement; for (int i = 0; i < 150; i++) { double x2 = x1 + Math.Cos(angle) * len; double y2 = y1 - Math.Sin(angle) * len; g.DrawLine(Pens.Blue, (int)x1, (int)y1, (int)x2, (int)y2); x1 = x2; y1 = y2; len += 3; angle = (angle + angleIncrement) % (Math.PI * 2); } } protected override void OnPaint(PaintEventArgs args) { var g = args.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; g.Clear(Color.White); DrawSpiral(g, 5, ToRadians(inc)); } private double ToRadians(double angle) { return Math.PI * angle / 180.0; } } }
require 'gl2 trig media/imagekit' coinsert 'jgl2' DT =: %30 ANGLE =: 0.025p1 DIRECTION=: 0 POLY=: noun define pc poly;pn "Poly Spiral"; minwh 320 320; cc isi isigraph; ) poly_run=: verb define wd POLY,'pshow' wd 'timer ',":DT * 1000 ) poly_close=: verb define wd 'timer 0; pclose' ) sys_timer_z_=: verb define recalcAngle_base_ '' wd 'psel poly; set isi invalid' ) poly_isi_paint=: verb define drawPolyspiral DIRECTION ) recalcAngle=: verb define DIRECTION=: 2p1 | DIRECTION + ANGLE ) drawPolyspiral=: verb define glclear'' x1y1 =. (glqwh'')%2 a=. -DIRECTION len=. 5 for_i. i.150 do. glpen glrgb Hue a % 2p1 x2y2=. x1y1 + len*(cos,sin) a gllines <.x1y1,x2y2 x1y1=. x2y2 len=. len+3 a=. 2p1 | a - DIRECTION end. ) poly_run''
Convert the following code from C# to J, ensuring the logic remains intact.
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Windows.Threading; namespace Polyspiral { public partial class Form1 : Form { private double inc; public Form1() { Width = Height = 640; StartPosition = FormStartPosition.CenterScreen; SetStyle( ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true); var timer = new DispatcherTimer(); timer.Tick += (s, e) => { inc = (inc + 0.05) % 360; Refresh(); }; timer.Interval = new TimeSpan(0, 0, 0, 0, 40); timer.Start(); } private void DrawSpiral(Graphics g, int len, double angleIncrement) { double x1 = Width / 2; double y1 = Height / 2; double angle = angleIncrement; for (int i = 0; i < 150; i++) { double x2 = x1 + Math.Cos(angle) * len; double y2 = y1 - Math.Sin(angle) * len; g.DrawLine(Pens.Blue, (int)x1, (int)y1, (int)x2, (int)y2); x1 = x2; y1 = y2; len += 3; angle = (angle + angleIncrement) % (Math.PI * 2); } } protected override void OnPaint(PaintEventArgs args) { var g = args.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; g.Clear(Color.White); DrawSpiral(g, 5, ToRadians(inc)); } private double ToRadians(double angle) { return Math.PI * angle / 180.0; } } }
require 'gl2 trig media/imagekit' coinsert 'jgl2' DT =: %30 ANGLE =: 0.025p1 DIRECTION=: 0 POLY=: noun define pc poly;pn "Poly Spiral"; minwh 320 320; cc isi isigraph; ) poly_run=: verb define wd POLY,'pshow' wd 'timer ',":DT * 1000 ) poly_close=: verb define wd 'timer 0; pclose' ) sys_timer_z_=: verb define recalcAngle_base_ '' wd 'psel poly; set isi invalid' ) poly_isi_paint=: verb define drawPolyspiral DIRECTION ) recalcAngle=: verb define DIRECTION=: 2p1 | DIRECTION + ANGLE ) drawPolyspiral=: verb define glclear'' x1y1 =. (glqwh'')%2 a=. -DIRECTION len=. 5 for_i. i.150 do. glpen glrgb Hue a % 2p1 x2y2=. x1y1 + len*(cos,sin) a gllines <.x1y1,x2y2 x1y1=. x2y2 len=. len+3 a=. 2p1 | a - DIRECTION end. ) poly_run''
Rewrite this program in J while keeping its functionality equivalent to the C# version.
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.Serialization; public static class MergeAndAggregateDatasets { public static void Main() { string patientsCsv = @" PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz"; string visitsCsv = @" PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3"; string format = "yyyy-MM-dd"; var formatProvider = new DateTimeFormat(format).FormatProvider; var patients = ParseCsv( patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries), line => (PatientId: int.Parse(line[0]), LastName: line[1])); var visits = ParseCsv( visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries), line => ( PatientId: int.Parse(line[0]), VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?), Score: double.TryParse(line[2], out double score) ? score : default(double?) ) ); var results = patients.GroupJoin(visits, p => p.PatientId, v => v.PatientId, (p, vs) => ( p.PatientId, p.LastName, LastVisit: vs.Max(v => v.VisitDate), ScoreSum: vs.Sum(v => v.Score), ScoreAvg: vs.Average(v => v.Score) ) ).OrderBy(r => r.PatientId); Console.WriteLine("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |"); foreach (var r in results) { Console.WriteLine($"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format)Β ?? "",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |"); } } private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor) { for (int i = 1; i < contents.Length; i++) { var line = contents[i].Split(','); yield return constructor(line); } } }
require'jd pacman' load JDP,'tools/csv_load.ijs' F=: jpath '~temp/rosettacode/example/CSV' jdcreatefolder_jd_ CSVFOLDER=: F assert 0<{{)n PATIENTID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz }} fwrite F,'patients.csv' assert 0<{{)n PATIENTID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3 }} fwrite F,'visits.csv' csvprepare 'patients';F,'patients.csv' csvprepare 'visits';F,'visits.csv' csvload 'patients';1 csvload 'visits';1 jd'ref patients PATIENTID visits PATIENTID'
Maintain the same structure and functionality when rewriting this code in J.
using System; class program { static void Main() { knapSack(40); var sw = System.Diagnostics.Stopwatch.StartNew(); Console.Write(knapSack(400) + "\n" + sw.Elapsed); Console.Read(); } static string knapSack(uint w1) { init(); change(); uint n = (uint)w.Length; var K = new uint[n + 1, w1 + 1]; for (uint vi, wi, w0, x, i = 0; i < n; i++) for (vi = v[i], wi = w[i], w0 = 1; w0 <= w1; w0++) { x = K[i, w0]; if (wi <= w0) x = max(vi + K[i, w0 - wi], x); K[i + 1, w0] = x; } string str = ""; for (uint v1 = K[n, w1]; v1 > 0; n--) if (v1 != K[n - 1, w1]) { v1 -= v[n - 1]; w1 -= w[n - 1]; str += items[n - 1] + "\n"; } return str; } static uint max(uint a, uint b) { return a > b ? a : b; } static byte[] w, v; static string[] items; static byte[] p = { 1, 1, 2, 2, 2, 3, 3, 3, 1, 3, 1, 1, 2, 2, 1, 1, 1, 1, 1, 2, 1, 2 }; static void init() { w = new byte[] { 9, 13, 153, 50, 15, 68, 27, 39, 23, 52, 11, 32, 24, 48, 73, 42, 43, 22, 7, 18, 4, 30 }; v = new byte[] { 150, 35, 200, 60, 60, 45, 60, 40, 30, 10, 70, 30, 15, 10, 40, 70, 75, 80, 20, 12, 50, 10 }; items = new string[] {"map","compass","water","sandwich","glucose","tin", "banana","apple","cheese","beer","suntan cream", "camera","T-shirt","trousers","umbrella", "waterproof trousers","waterproof overclothes", "note-case","sunglasses","towel","socks","book"}; } static void change() { int n = w.Length, s = 0, i, j, k; byte xi; for (i = 0; i < n; i++) s += p[i]; { byte[] x = new byte[s]; for (k = i = 0; i < n; i++) for (xi = w[i], j = p[i]; j > 0; j--) x[k++] = xi; w = x; } { byte[] x = new byte[s]; for (k = i = 0; i < n; i++) for (xi = v[i], j = p[i]; j > 0; j--) x[k++] = xi; v = x; } string[] pItems = new string[s]; string itemI; for (k = i = 0; i < n; i++) for (itemI = items[i], j = p[i]; j > 0; j--) pItems[k++] = itemI; items = pItems; } }
'names numbers'=:|:".;._2]0 :0 'map'; 9 150 1 'compass'; 13 35 1 'water'; 153 200 2 'sandwich'; 50 60 2 'glucose'; 15 60 2 'tin'; 68 45 3 'banana'; 27 60 3 'apple'; 39 40 3 'cheese'; 23 30 1 'beer'; 52 10 3 'suntan cream'; 11 70 1 'camera'; 32 30 1 'T-shirt'; 24 15 2 'trousers'; 48 10 2 'umbrella'; 73 40 1 'waterproof trousers'; 42 70 1 'waterproof overclothes'; 43 75 1 'note-case'; 22 80 1 'sunglasses'; 7 20 1 'towel'; 18 12 2 'socks'; 4 50 1 'book'; 30 10 2 ) 'weights values pieces'=:|:numbers decode=: (pieces+1)&#: pickBest=:4 :0 n=. decode y weight=. n+/ .*weights value=. (x >: weight) * n+/ .*values (value = >./value)#y ) bestCombo=:3 :0 limit=. */pieces+1 i=. 0 step=. 1e6 best=. '' while.i<limit do. best=. 400 pickBest best,(#~ limit&>)i+i.step i=. i+step end. best ) bestCombo'' 978832641
Produce a functionally identical J code for the snippet given in C#.
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, ["Errol"] = 42, ["Gary"] = 41, ["Bernard"] = 41, ["Barry"] = 41, ["Stephen"] = 39, }; StandardRank(scores); ModifiedRank(scores); DenseRank(scores); OrdinalRank(scores); FractionalRank(scores); } static void StandardRank(Dictionary<string, int> data) { Console.WriteLine("Standard Rank"); var list = data.Values.Distinct().ToList(); list.Sort((a, b) => b.CompareTo(a)); int rank = 1; foreach (var value in list) { int temp = rank; foreach (var k in data.Keys) { if (data[k] == value) { Console.WriteLine("{0} {1} {2}", temp, value, k); rank++; } } } Console.WriteLine(); } static void ModifiedRank(Dictionary<string, int> data) { Console.WriteLine("Modified Rank"); var list = data.Values.Distinct().ToList(); list.Sort((a, b) => b.CompareTo(a)); int rank = 0; foreach (var value in list) { foreach (var k in data.Keys) { if (data[k] == value) { rank++; } } foreach (var k in data.Keys) { if (data[k] == value) { Console.WriteLine("{0} {1} {2}", rank, data[k], k); } } } Console.WriteLine(); } static void DenseRank(Dictionary<string, int> data) { Console.WriteLine("Dense Rank"); var list = data.Values.Distinct().ToList(); list.Sort((a, b) => b.CompareTo(a)); int rank = 1; foreach (var value in list) { foreach (var k in data.Keys) { if (data[k] == value) { Console.WriteLine("{0} {1} {2}", rank, data[k], k); } } rank++; } Console.WriteLine(); } static void OrdinalRank(Dictionary<string, int> data) { Console.WriteLine("Ordinal Rank"); var list = data.Values.Distinct().ToList(); list.Sort((a, b) => b.CompareTo(a)); int rank = 1; foreach (var value in list) { foreach (var k in data.Keys) { if (data[k] == value) { Console.WriteLine("{0} {1} {2}", rank, data[k], k); rank++; } } } Console.WriteLine(); } static void FractionalRank(Dictionary<string, int> data) { Console.WriteLine("Fractional Rank"); var list = data.Values.Distinct().ToList(); list.Sort((a, b) => b.CompareTo(a)); int rank = 0; foreach (var value in list) { double avg = 0; int cnt = 0; foreach (var k in data.Keys) { if (data[k] == value) { rank++; cnt++; avg += rank; } } avg /= cnt; foreach (var k in data.Keys) { if (data[k] == value) { Console.WriteLine("{0:F1} {1} {2}", avg, data[k], k); } } } Console.WriteLine(); } } }
competitors=:<;._1;._2]0 :0 44 Solomon 42 Jason 42 Errol 41 Garry 41 Bernard 41 Barry 39 Stephen ) scores=: {."1 standard=: 1+i.~ modified=: 1+i:~ dense=: #/.~ # #\@~. ordinal=: #\ fractional=: #/.~ # ] (+/%#)/. #\ rank=:1 :'<"0@u@:scores,.]'
Produce a functionally identical J code for the snippet given in C#.
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace StraddlingCheckerboard { class Program { public readonly static IReadOnlyDictionary<char, string> val2Key; public readonly static IReadOnlyDictionary<string, char> key2Val; static Program() { val2Key = new Dictionary<char, string> { {'A',"30"}, {'B',"31"}, {'C',"32"}, {'D',"33"}, {'E',"5"}, {'F',"34"}, {'G',"35"}, {'H',"0"}, {'I',"36"}, {'J',"37"}, {'K',"38"}, {'L',"2"}, {'M',"4"}, {'.',"78"}, {'N',"39"}, {'/',"79"}, {'O',"1"}, {'0',"790"}, {'P',"70"}, {'1',"791"}, {'Q',"71"}, {'2',"792"}, {'R',"8"}, {'3',"793"}, {'S',"6"}, {'4',"794"}, {'T',"9"}, {'5',"795"}, {'U',"72"}, {'6',"796"},{'V',"73"}, {'7',"797"}, {'W',"74"}, {'8',"798"}, {'X',"75"}, {'9',"799"}, {'Y',"76"}, {'Z',"77"}}; key2Val = val2Key.ToDictionary(kv => kv.Value, kv => kv.Key); } public static string Encode(string s) { return string.Concat(s.ToUpper().ToCharArray() .Where(c => val2Key.ContainsKey(c)).Select(c => val2Key[c])); } public static string Decode(string s) { return string.Concat(Regex.Matches(s, "79.|7.|3.|.").Cast<Match>() .Where(m => key2Val.ContainsKey(m.Value)).Select(m => key2Val[m.Value])); } static void Main(string[] args) { var enc = Encode("One night-it was on the twentieth of March, 1888-I was returning"); Console.WriteLine(enc); Console.WriteLine(Decode(enc)); Console.ReadLine(); } } }
'Esc Stop'=: '/.' 'Nums Alpha'=: '0123456789';'ABCDEFGHIJKLMNOPQRSTUVWXYZ' Charset=: Nums,Alpha,Stop escapenum=: (,@:((; Esc&,)&>) Nums) rplc~ ] unescapenum=: ((, ; ' '&,@])"1 0 Nums"_) rplc~ ] expandKeyatUV=: 0:`[`(1 #~ 2 + #@])} #inv ] makeChkBrd=: Nums , expandKeyatUV chkbrd=: conjunction define 'uv key'=. n board=. uv makeChkBrd key select. m case. 0 do. digits=. board 10&#.inv@i. escapenum y ' ' -.~ ,(":@{:"1 digits) ,.~ (1 1 0 2{":uv) {~ {."1 digits case. 1 do. esc=. 0 chkbrd (uv;key) Esc tmp=. esc unescapenum esc,'0',y tmp=. ((":uv) ((-.@e.~ _1&|.) *. e.~) tmp) <;.1 tmp idx=. (}. ,~ (1 1 0 2{":uv) ":@i. {.) each tmp idx=. ;(2&{. , [: ((0 1 $~ +:@#) #inv!.'1' ]) 2&}.) each idx }.board {~ _2 (_&".)\ idx end. )
Produce a language-to-language conversion: from C# to J, same semantics.
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")) { return true; } return false; } static bool IsPlausibleWord(string word) { if (!word.Contains("c") && word.Contains("ie")) { return true; } if (word.Contains("cei")) { return true; } return false; } static bool IsPlausibleRule(string filename) { IEnumerable<string> wordSource = File.ReadLines(filename); int trueCount = 0; int falseCount = 0; foreach (string word in wordSource) { if (IsPlausibleWord(word)) { trueCount++; } else if (IsOppPlausibleWord(word)) { falseCount++; } } Console.WriteLine("Plausible count: {0}", trueCount); Console.WriteLine("Implausible count: {0}", falseCount); return trueCount > 2 * falseCount; } static void Main(string[] args) { if (IsPlausibleRule("unixdict.txt")) { Console.WriteLine("Rule is plausible."); } else { Console.WriteLine("Rule is not plausible."); } } } }
dict=:tolower fread '/tmp/unixdict.txt'
Translate the given C# code snippet into J without altering its behavior.
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")) { return true; } return false; } static bool IsPlausibleWord(string word) { if (!word.Contains("c") && word.Contains("ie")) { return true; } if (word.Contains("cei")) { return true; } return false; } static bool IsPlausibleRule(string filename) { IEnumerable<string> wordSource = File.ReadLines(filename); int trueCount = 0; int falseCount = 0; foreach (string word in wordSource) { if (IsPlausibleWord(word)) { trueCount++; } else if (IsOppPlausibleWord(word)) { falseCount++; } } Console.WriteLine("Plausible count: {0}", trueCount); Console.WriteLine("Implausible count: {0}", falseCount); return trueCount > 2 * falseCount; } static void Main(string[] args) { if (IsPlausibleRule("unixdict.txt")) { Console.WriteLine("Rule is plausible."); } else { Console.WriteLine("Rule is not plausible."); } } } }
dict=:tolower fread '/tmp/unixdict.txt'
Translate the given C# code snippet into J without altering its behavior.
using System; using System.Dynamic; class Example : DynamicObject { public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { result = null; Console.WriteLine("This is {0}.", binder.Name); return true; } } class Program { static void Main(string[] args) { dynamic ex = new Example(); ex.Foo(); ex.Bar(); } }
example=:3 :0 doSomething_z_=: assert&0 bind 'doSomething was not implemented' doSomething__y '' ) doSomething_adhoc1_=: smoutput bind 'hello world' dSomethingElse_adhoc2_=: smoutput bind 'hello world'
Can you help me rewrite this code in J instead of C#, keeping it the same logically?
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChemicalCalculator { class Program { static Dictionary<string, double> atomicMass = new Dictionary<string, double>() { {"H", 1.008 }, {"He", 4.002602}, {"Li", 6.94}, {"Be", 9.0121831}, {"B", 10.81}, {"C", 12.011}, {"N", 14.007}, {"O", 15.999}, {"F", 18.998403163}, {"Ne", 20.1797}, {"Na", 22.98976928}, {"Mg", 24.305}, {"Al", 26.9815385}, {"Si", 28.085}, {"P", 30.973761998}, {"S", 32.06}, {"Cl", 35.45}, {"Ar", 39.948}, {"K", 39.0983}, {"Ca", 40.078}, {"Sc", 44.955908}, {"Ti", 47.867}, {"V", 50.9415}, {"Cr", 51.9961}, {"Mn", 54.938044}, {"Fe", 55.845}, {"Co", 58.933194}, {"Ni", 58.6934}, {"Cu", 63.546}, {"Zn", 65.38}, {"Ga", 69.723}, {"Ge", 72.630}, {"As", 74.921595}, {"Se", 78.971}, {"Br", 79.904}, {"Kr", 83.798}, {"Rb", 85.4678}, {"Sr", 87.62}, {"Y", 88.90584}, {"Zr", 91.224}, {"Nb", 92.90637}, {"Mo", 95.95}, {"Ru", 101.07}, {"Rh", 102.90550}, {"Pd", 106.42}, {"Ag", 107.8682}, {"Cd", 112.414}, {"In", 114.818}, {"Sn", 118.710}, {"Sb", 121.760}, {"Te", 127.60}, {"I", 126.90447}, {"Xe", 131.293}, {"Cs", 132.90545196}, {"Ba", 137.327}, {"La", 138.90547}, {"Ce", 140.116}, {"Pr", 140.90766}, {"Nd", 144.242}, {"Pm", 145}, {"Sm", 150.36}, {"Eu", 151.964}, {"Gd", 157.25}, {"Tb", 158.92535}, {"Dy", 162.500}, {"Ho", 164.93033}, {"Er", 167.259}, {"Tm", 168.93422}, {"Yb", 173.054}, {"Lu", 174.9668}, {"Hf", 178.49}, {"Ta", 180.94788}, {"W", 183.84}, {"Re", 186.207}, {"Os", 190.23}, {"Ir", 192.217}, {"Pt", 195.084}, {"Au", 196.966569}, {"Hg", 200.592}, {"Tl", 204.38}, {"Pb", 207.2}, {"Bi", 208.98040}, {"Po", 209}, {"At", 210}, {"Rn", 222}, {"Fr", 223}, {"Ra", 226}, {"Ac", 227}, {"Th", 232.0377}, {"Pa", 231.03588}, {"U", 238.02891}, {"Np", 237}, {"Pu", 244}, {"Am", 243}, {"Cm", 247}, {"Bk", 247}, {"Cf", 251}, {"Es", 252}, {"Fm", 257}, {"Uue", 315}, {"Ubn", 299}, }; static double Evaluate(string s) { s += "["; double sum = 0.0; string symbol = ""; string number = ""; for (int i = 0; i < s.Length; ++i) { var c = s[i]; if ('@' <= c && c <= '[') { int n = 1; if (number != "") { n = int.Parse(number); } if (symbol != "") { sum += atomicMass[symbol] * n; } if (c == '[') { break; } symbol = c.ToString(); number = ""; } else if ('a' <= c && c <= 'z') { symbol += c; } else if ('0' <= c && c <= '9') { number += c; } else { throw new Exception(string.Format("Unexpected symbol {0} in molecule", c)); } } return sum; } static string ReplaceFirst(string text, string search, string replace) { int pos = text.IndexOf(search); if (pos < 0) { return text; } return text.Substring(0, pos) + replace + text.Substring(pos + search.Length); } static string ReplaceParens(string s) { char letter = 's'; while (true) { var start = s.IndexOf('('); if (start == -1) { break; } for (int i = start + 1; i < s.Length; ++i) { if (s[i] == ')') { var expr = s.Substring(start + 1, i - start - 1); var symbol = string.Format("@{0}", letter); s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol); atomicMass[symbol] = Evaluate(expr); letter++; break; } if (s[i] == '(') { start = i; continue; } } } return s; } static void Main() { var molecules = new string[]{ "H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue" }; foreach (var molecule in molecules) { var mass = Evaluate(ReplaceParens(molecule)); Console.WriteLine("{0,17} -> {1,7:0.000}", molecule, mass); } } } }
do{{)n H: 1.008, He: 4.002602, Li: 6.94, Be: 9.0121831, B: 10.81, C: 12.011, N: 14.007, O: 15.999, F: 18.998403163, Ne: 20.1797, Na: 22.98976928, Mg: 24.305, Al: 26.9815385, Si: 28.085, P: 30.973761998, S: 32.06, Cl: 35.45, K: 39.0983, Ar: 39.948, Ca: 40.078, Sc: 44.955908, Ti: 47.867, V: 50.9415, Cr: 51.9961, Mn: 54.938044, Fe: 55.845, Ni: 58.6934, Co: 58.933194, Cu: 63.546, Zn: 65.38, Ga: 69.723, Ge: 72.63, As: 74.921595, Se: 78.971, Br: 79.904, Kr: 83.798, Rb: 85.4678, Sr: 87.62, Y: 88.90584, Zr: 91.224, Nb: 92.90637, Mo: 95.95, Ru: 101.07, Rh: 102.9055, Pd: 106.42, Ag: 107.8682, Cd: 112.414, In: 114.818, Sn: 118.71, Sb: 121.76, I: 126.90447, Te: 127.6, Xe: 131.293, Cs: 132.90545196, Ba: 137.327, La: 138.90547, Ce: 140.116, Pr: 140.90766, Nd: 144.242, Pm: 145, Sm: 150.36, Eu: 151.964, Gd: 157.25, Tb: 158.92535, Dy: 162.5, Ho: 164.93033, Er: 167.259, Tm: 168.93422, Yb: 173.054, Lu: 174.9668, Hf: 178.49, Ta: 180.94788, W: 183.84, Re: 186.207, Os: 190.23, Ir: 192.217, Pt: 195.084, Au: 196.966569, Hg: 200.592, Tl: 204.38, Pb: 207.2, Bi: 208.9804, Po: 209, At: 210, Rn: 222, Fr: 223, Ra: 226, Ac: 227, Pa: 231.03588, Th: 232.0377, Np: 237, U: 238.02891, Am: 243, Pu: 244, Cm: 247, Bk: 247, Cf: 251, Es: 252, Fm: 257, Ubn: 299, Uue: 315 }} rplc ':';'=:'; ',';'['; LF;'' ctyp=: e.&'0123456789' + (2*]~:tolower) + 3*]~:toupper tokenize=: (0;(0 10#:10*do;._2{{)n 1.1 2.1 3.1 4.1 1.2 2.2 3.2 4.2 1.2 2 3.2 4.2 1.2 2.2 3.2 4 1.2 2.2 3.2 4 }});ctyp a.)&;: molar_mass=: {{ W=.,0 M=.,1 digit=. (1=ctyp a.)#<"0 a. alpha=. (2=ctyp a.)#<"0 a. for_t.|.tokenize y do. select. {.;t case. '(' do. W=. (M #.&(2&{.) W), 2}.W M=. 1,2}.M case. ')' do. W=. 0,W M=. 1,M case. digit do. M=. (do;t),}.M case. alpha do. W=. (({.W)+({.M)*do;t),}.W M=. 1,}.M case. do. end. end. assert. 1=#W <.@+&0.5&.(*&1000){.W }} assert 1.008 = molar_mass('H') assert 2.016 = molar_mass('H2') assert 18.015 = molar_mass('H2O') assert 34.014 = molar_mass('H2O2') assert 34.014 = molar_mass('(HO)2') assert 142.036 = molar_mass('Na2SO4') assert 84.162 = molar_mass('C6H12') assert 186.295 = molar_mass('COOH(C(CH3)2)3CH3') assert 176.124 = molar_mass('C6H4O2(OH)4') assert 386.664 = molar_mass('C27H46O') assert 315 = molar_mass('Uue')
Change the programming language of this snippet from C# to J without modifying what it does.
using System; using System.Collections.Generic; namespace SnakeAndLadder { class Program { private static Dictionary<int, int> snl = new Dictionary<int, int>() { {4, 14}, {9, 31}, {17, 7}, {20, 38}, {28, 84}, {40, 59}, {51, 67}, {54, 34}, {62, 19}, {63, 81}, {64, 60}, {71, 91}, {87, 24}, {93, 73}, {95, 75}, {99, 78}, }; private static Random rand = new Random(); private const bool sixesThrowAgain = true; static int Turn(int player, int square) { while (true) { int roll = rand.Next(1, 6); Console.Write("Player {0}, on square {1}, rolls a {2}", player, square, roll); if (square + roll > 100) { Console.WriteLine(" but cannot move."); } else { square += roll; Console.WriteLine(" and moves to square {0}", square); if (square == 100) return 100; int next = square; if (snl.ContainsKey(square)) { next = snl[square]; } if (square < next) { Console.WriteLine("Yay! Landed on a ladder. Climb up to {0}.", next); if (next == 100) return 100; square = next; } else if (square > next) { Console.WriteLine("Oops! Landed on a snake. Slither down to {0}.", next); } } if (roll < 6 || !sixesThrowAgain) return square; Console.WriteLine("Rolled a 6 so roll again."); } } static void Main(string[] args) { int[] players = { 1, 1, 1 }; while (true) { for (int i = 0; i < players.Length; i++) { int ns = Turn(i + 1, players[i]); if (ns == 100) { Console.WriteLine("Player {0} wins!", i + 1); return; } players[i] = ns; Console.WriteLine(); } } } } }
require 'format/printf general/misc/prompt' SnakesLadders=: _2 ]\ 4 14 9 31 17 7 20 38 28 84 40 59 51 67 54 34 62 19 63 81 64 60 71 91 87 24 93 73 95 75 99 78 'idx val'=: |: SnakesLadders Board=: val idx} i. >: 100 rollDice=: 1 + $ ?@$ 6: playTurn=: Board {~ 100 <. rollDice + ] runGame=: [: playTurn^:(100 -.@e. ])^:(<_) $&0 report=: ('Player %d won!' sprintf 100 >:@i.~ {:) , echo start=: >:@".@prompt&'How many players to play against?' [ echo bind 'You are Player 1!' playSnakesLadders=: [: report@runGame start
Maintain the same structure and functionality when rewriting this code in J.
using System; using System.Collections.Generic; namespace SnakeAndLadder { class Program { private static Dictionary<int, int> snl = new Dictionary<int, int>() { {4, 14}, {9, 31}, {17, 7}, {20, 38}, {28, 84}, {40, 59}, {51, 67}, {54, 34}, {62, 19}, {63, 81}, {64, 60}, {71, 91}, {87, 24}, {93, 73}, {95, 75}, {99, 78}, }; private static Random rand = new Random(); private const bool sixesThrowAgain = true; static int Turn(int player, int square) { while (true) { int roll = rand.Next(1, 6); Console.Write("Player {0}, on square {1}, rolls a {2}", player, square, roll); if (square + roll > 100) { Console.WriteLine(" but cannot move."); } else { square += roll; Console.WriteLine(" and moves to square {0}", square); if (square == 100) return 100; int next = square; if (snl.ContainsKey(square)) { next = snl[square]; } if (square < next) { Console.WriteLine("Yay! Landed on a ladder. Climb up to {0}.", next); if (next == 100) return 100; square = next; } else if (square > next) { Console.WriteLine("Oops! Landed on a snake. Slither down to {0}.", next); } } if (roll < 6 || !sixesThrowAgain) return square; Console.WriteLine("Rolled a 6 so roll again."); } } static void Main(string[] args) { int[] players = { 1, 1, 1 }; while (true) { for (int i = 0; i < players.Length; i++) { int ns = Turn(i + 1, players[i]); if (ns == 100) { Console.WriteLine("Player {0} wins!", i + 1); return; } players[i] = ns; Console.WriteLine(); } } } } }
require 'format/printf general/misc/prompt' SnakesLadders=: _2 ]\ 4 14 9 31 17 7 20 38 28 84 40 59 51 67 54 34 62 19 63 81 64 60 71 91 87 24 93 73 95 75 99 78 'idx val'=: |: SnakesLadders Board=: val idx} i. >: 100 rollDice=: 1 + $ ?@$ 6: playTurn=: Board {~ 100 <. rollDice + ] runGame=: [: playTurn^:(100 -.@e. ])^:(<_) $&0 report=: ('Player %d won!' sprintf 100 >:@i.~ {:) , echo start=: >:@".@prompt&'How many players to play against?' [ echo bind 'You are Player 1!' playSnakesLadders=: [: report@runGame start
Port the provided C# code into J while preserving the original functionality.
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 <= 1000; i+=100) { Console.WriteLine($"F{i} has {Generate(i).Count()} terms."); } } public static IEnumerable<(int num, int den)> Generate(int i) { var comparer = Comparer<(int n, int d)>.Create((a, b) => (a.n * b.d).CompareTo(a.d * b.n)); var seq = new SortedSet<(int n, int d)>(comparer); for (int d = 1; d <= i; d++) { for (int n = 0; n <= d; n++) { seq.Add((n, d)); } } return seq; } }
Farey=: x:@/:~@(0 , ~.)@(#~ <:&1)@:,@(%/~@(1 + i.)) displayFarey=: ('r/' charsub '0r' , ,&'r1')@": order=: ': ' ,~ ":
Produce a functionally identical J code for the snippet given 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 <= 1000; i+=100) { Console.WriteLine($"F{i} has {Generate(i).Count()} terms."); } } public static IEnumerable<(int num, int den)> Generate(int i) { var comparer = Comparer<(int n, int d)>.Create((a, b) => (a.n * b.d).CompareTo(a.d * b.n)); var seq = new SortedSet<(int n, int d)>(comparer); for (int d = 1; d <= i; d++) { for (int n = 0; n <= d; n++) { seq.Add((n, d)); } } return seq; } }
Farey=: x:@/:~@(0 , ~.)@(#~ <:&1)@:,@(%/~@(1 + i.)) displayFarey=: ('r/' charsub '0r' , ,&'r1')@": order=: ': ' ,~ ":
Convert this C# block to J, preserving its control flow and logic.
byte aByte = 2; short aShort = aByte; int anInt = aShort; long aLong = anInt; float aFloat = 1.2f; double aDouble = aFloat; BigInteger b = 5; Complex c = 2.5;
datatype 3Β : 0 n=. 1 2 4 8 16 32 64 128 1024 2048 4096 8192 16384 32768 65536 131072 t=. '/boolean/literal/integer/floating/complex/boxed/extended/rational' t=. t,'/sparse boolean/sparse literal/sparse integer/sparse floating' t=. t,'/sparse complex/sparse boxed/symbol/unicode' (n i. 3!:0 y) pick <;._1 t ) [A =: 0 1 ; 0 1 2 ; (!24x) ; 1r2 ; 1.2 ; 1j2 ; (<'boxed') ; (s:'`symbol') ; 'literal' ; (u: 16b263a) β”Œβ”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β” β”‚0 1β”‚0 1 2β”‚620448401733239439360000β”‚1r2β”‚1.2β”‚1j2β”‚β”Œβ”€β”€β”€β”€β”€β”β”‚`symbolβ”‚literalβ”‚β˜Ίβ”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚β”‚boxedβ”‚β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚β””β”€β”€β”€β”€β”€β”˜β”‚ β”‚ β”‚ β”‚ β””β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”˜ datatype&.>A β”Œβ”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚booleanβ”‚integerβ”‚extendedβ”‚rationalβ”‚floatingβ”‚complexβ”‚boxedβ”‚symbolβ”‚literalβ”‚unicodeβ”‚ β””β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜ [I =: =i.4 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 datatype I boolean $. I 0 0 β”‚ 1 1 1 β”‚ 1 2 2 β”‚ 1 3 3 β”‚ 1 datatype $. I sparse boolean (+ $.)I 0 0 β”‚ 2 1 1 β”‚ 2 2 2 β”‚ 2 3 3 β”‚ 2
Write the same code in J as shown below in C#.
byte aByte = 2; short aShort = aByte; int anInt = aShort; long aLong = anInt; float aFloat = 1.2f; double aDouble = aFloat; BigInteger b = 5; Complex c = 2.5;
datatype 3Β : 0 n=. 1 2 4 8 16 32 64 128 1024 2048 4096 8192 16384 32768 65536 131072 t=. '/boolean/literal/integer/floating/complex/boxed/extended/rational' t=. t,'/sparse boolean/sparse literal/sparse integer/sparse floating' t=. t,'/sparse complex/sparse boxed/symbol/unicode' (n i. 3!:0 y) pick <;._1 t ) [A =: 0 1 ; 0 1 2 ; (!24x) ; 1r2 ; 1.2 ; 1j2 ; (<'boxed') ; (s:'`symbol') ; 'literal' ; (u: 16b263a) β”Œβ”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β” β”‚0 1β”‚0 1 2β”‚620448401733239439360000β”‚1r2β”‚1.2β”‚1j2β”‚β”Œβ”€β”€β”€β”€β”€β”β”‚`symbolβ”‚literalβ”‚β˜Ίβ”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚β”‚boxedβ”‚β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚β””β”€β”€β”€β”€β”€β”˜β”‚ β”‚ β”‚ β”‚ β””β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”˜ datatype&.>A β”Œβ”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚booleanβ”‚integerβ”‚extendedβ”‚rationalβ”‚floatingβ”‚complexβ”‚boxedβ”‚symbolβ”‚literalβ”‚unicodeβ”‚ β””β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜ [I =: =i.4 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 datatype I boolean $. I 0 0 β”‚ 1 1 1 β”‚ 1 2 2 β”‚ 1 3 3 β”‚ 1 datatype $. I sparse boolean (+ $.)I 0 0 β”‚ 2 1 1 β”‚ 2 2 2 β”‚ 2 3 3 β”‚ 2
Port the provided C# code into J while preserving the original functionality.
using System; using System.Numerics; namespace LeftFactorial { class Program { static void Main(string[] args) { for (int i = 0; i <= 10; i++) { Console.WriteLine(string.Format("!{0} = {1}", i, LeftFactorial(i))); } for (int j = 20; j <= 110; j += 10) { Console.WriteLine(string.Format("!{0} = {1}", j, LeftFactorial(j))); } for (int k = 1000; k <= 10000; k += 1000) { Console.WriteLine(string.Format("!{0} has {1} digits", k, LeftFactorial(k).ToString().Length)); } Console.ReadKey(); } private static BigInteger Factorial(int number) { BigInteger accumulator = 1; for (int factor = 1; factor <= number; factor++) { accumulator *= factor; } return accumulator; } private static BigInteger LeftFactorial(int n) { BigInteger result = 0; for (int i = 0; i < n; i++) { result += Factorial(i); } return result; } } }
leftFact=: +/@:!@i."0
Port the provided C# code into J while preserving the original functionality.
using System; using System.Numerics; namespace LeftFactorial { class Program { static void Main(string[] args) { for (int i = 0; i <= 10; i++) { Console.WriteLine(string.Format("!{0} = {1}", i, LeftFactorial(i))); } for (int j = 20; j <= 110; j += 10) { Console.WriteLine(string.Format("!{0} = {1}", j, LeftFactorial(j))); } for (int k = 1000; k <= 10000; k += 1000) { Console.WriteLine(string.Format("!{0} has {1} digits", k, LeftFactorial(k).ToString().Length)); } Console.ReadKey(); } private static BigInteger Factorial(int number) { BigInteger accumulator = 1; for (int factor = 1; factor <= number; factor++) { accumulator *= factor; } return accumulator; } private static BigInteger LeftFactorial(int n) { BigInteger result = 0; for (int i = 0; i < n; i++) { result += Factorial(i); } return result; } } }
leftFact=: +/@:!@i."0
Write a version of this C# function in J with identical behavior.
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 false; } static void Main(string[] args) { BI a = 0, b = 1, t; int n = 1, s = 0, d = 1, c = 0, f = 1; while (n <= 80) Console.WriteLine("{0,46:n0} {1}", t = b / n++, hmf(t) ? "" : "is prime.", t = b, b = ((c += d * 3 + 3) * a + (f += d * 2 + 3) * b) / (s += d += 2), a = t); } }
nextMotzkin=: , (({:*1+2*#) + _2&{*3*#-1:)%2+#
Write the same code in J 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.GetLength(1); j++) Console.Write("{0,2} ", result[i, j]); Console.WriteLine(); } Console.WriteLine("\nMagic constant: {0} ", (n * n + 1) * n / 2); Console.ReadLine(); } private static int[,] MagicSquareDoublyEven(int n) { if (n < 4 || n % 4 != 0) throw new ArgumentException("base must be a positive " + "multiple of 4"); int bits = 0b1001_0110_0110_1001; int size = n * n; int mult = n / 4; int[,] result = new int[n, n]; for (int r = 0, i = 0; r < n; r++) { for (int c = 0; c < n; c++, i++) { int bitPos = c / mult + (r / mult) * 4; result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } return result; } } }
masksq=: >:@#@, | _1&^ * 1 + i.@$ pat4=: ,:(+.|.)=i.4 mask=: ,/@(,./"3@$&pat4)@] ,~ % 4: demsq=: masksq@mask
Please provide an equivalent version of this C# code in J.
using System; namespace PythagoreanQuadruples { class Program { const int MAX = 2200; const int MAX2 = MAX * MAX * 2; static void Main(string[] args) { bool[] found = new bool[MAX + 1]; bool[] a2b2 = new bool[MAX2 + 1]; int s = 3; for(int a = 1; a <= MAX; a++) { int a2 = a * a; for (int b=a; b<=MAX; b++) { a2b2[a2 + b * b] = true; } } for (int c = 1; c <= MAX; c++) { int s1 = s; s += 2; int s2 = s; for (int d = c + 1; d <= MAX; d++) { if (a2b2[s1]) found[d] = true; s1 += s2; s2 += 2; } } Console.WriteLine("The values of d <= {0} which can't be represented:", MAX); for (int d = 1; d < MAX; d++) { if (!found[d]) Console.Write("{0} ", d); } Console.WriteLine(); } } }
Filter =: (#~`)(`:6) B =: *: A =: i. >: i. 2200 S1 =: , B +/ B S1 =: <:&({:B)Filter S1 S1 =: ~. S1 S2 =: , B +/ S1 S2 =: <:&({:B)Filter S2 S2 =: ~. S2 RESULT =: (B -.@:e. S2) # A RESULT 1 2 4 5 8 10 16 20 32 40 64 80 128 160 256 320 512 640 1024 1280 2048
Convert this C# snippet to J and keep its semantics consistent.
var prevIdle = 0f; var prevTotal = 0f; while (true) { var cpuLine = File .ReadAllLines("/proc/stat") .First() .Split(' ', StringSplitOptions.RemoveEmptyEntries) .Skip(1) .Select(float.Parse) .ToArray(); var idle = cpuLine[3]; var total = cpuLine.Sum(); var percent = 100.0 * (1.0 - (idle - prevIdle) / (total - prevTotal)); Console.WriteLine($"{percent:0.00}%"); prevIdle = idle; prevTotal = total; Thread.Sleep(1000); }
cputpct=:3 :0 if. 0>nc<'PREVCPUTPCT' do. PREVCPUTPCT=:0 end. old=. PREVCPUTPCT PREVCPUTPCT=: (1+i.8){0".}:2!:0{{)nsed '2,$d' /proc/stat}} 100*1-(3&{ % +/) PREVCPUTPCT - old )
Transform the following C# implementation into J, maintaining the same output and logic.
using System; namespace TypeDetection { class C { } struct S { } enum E { NONE, } class Program { static void ShowType<T>(T t) { Console.WriteLine("The type of '{0}' is {1}", t, t.GetType()); } static void Main() { ShowType(5); ShowType(7.5); ShowType('d'); ShowType(true); ShowType("Rosetta"); ShowType(new C()); ShowType(new S()); ShowType(E.NONE); ShowType(new int[] { 1, 2, 3 }); } } }
echo 'one' one echo 1 1
Translate this program into J but keep the logic exactly as in C#.
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.Join(" ", primes.Where(IsSafe).Take(35))); WriteLine($"There are {primes.TakeWhile(p => p < 1_000_000).Count(IsSafe):n0} safe primes below {1_000_000:n0}"); WriteLine($"There are {primes.TakeWhile(p => p < 10_000_000).Count(IsSafe):n0} safe primes below {10_000_000:n0}"); WriteLine("First 40 unsafe primes:"); WriteLine(string.Join(" ", primes.Where(IsUnsafe).Take(40))); WriteLine($"There are {primes.TakeWhile(p => p < 1_000_000).Count(IsUnsafe):n0} unsafe primes below {1_000_000:n0}"); WriteLine($"There are {primes.TakeWhile(p => p < 10_000_000).Count(IsUnsafe):n0} unsafe primes below {10_000_000:n0}"); bool IsSafe(int prime) => primes.Contains(prime / 2); bool IsUnsafe(int prime) => !primes.Contains(prime / 2); } static IEnumerable<int> Primes(int bound) { if (bound < 2) yield break; yield return 2; BitArray composite = new BitArray((bound - 1) / 2); int limit = ((int)(Math.Sqrt(bound)) - 1) / 2; for (int i = 0; i < limit; i++) { if (composite[i]) continue; int prime = 2 * i + 3; yield return prime; for (int j = (prime * prime - 2) / 2; j < composite.Count; j += prime) composite[j] = true; } for (int i = limit; i < composite.Count; i++) { if (!composite[i]) yield return 2 * i + 3; } } }
primeQ =: 1&p: safeQ =: primeQ@:-:@:<: Filter =: (#~`)(`:6) K =: adverb def 'm * 1000' PRIMES =: i.&.:(p:inv) 10 K K SAFE =: safeQ Filter PRIMES UNSAFE =: PRIMES -. SAFE
Write a version of this C# function in J with identical behavior.
using System; using System.Collections.Generic; using System.Linq; namespace HashJoin { public class AgeName { public AgeName(byte age, string name) { Age = age; Name = name; } public byte Age { get; private set; } public string Name { get; private set; } } public class NameNemesis { public NameNemesis(string name, string nemesis) { Name = name; Nemesis = nemesis; } public string Name { get; private set; } public string Nemesis { get; private set; } } public class DataContext { public DataContext() { AgeName = new List<AgeName>(); NameNemesis = new List<NameNemesis>(); } public List<AgeName> AgeName { get; set; } public List<NameNemesis> NameNemesis { get; set; } } public class AgeNameNemesis { public AgeNameNemesis(byte age, string name, string nemesis) { Age = age; Name = name; Nemesis = nemesis; } public byte Age { get; private set; } public string Name { get; private set; } public string Nemesis { get; private set; } } class Program { public static void Main() { var data = GetData(); var result = ExecuteHashJoin(data); WriteResultToConsole(result); } private static void WriteResultToConsole(List<AgeNameNemesis> result) { result.ForEach(ageNameNemesis => Console.WriteLine("Age: {0}, Name: {1}, Nemesis: {2}", ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis)); } private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data) { return (data.AgeName.Join(data.NameNemesis, ageName => ageName.Name, nameNemesis => nameNemesis.Name, (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis))) .ToList(); } private static DataContext GetData() { var context = new DataContext(); context.AgeName.AddRange(new [] { new AgeName(27, "Jonah"), new AgeName(18, "Alan"), new AgeName(28, "Glory"), new AgeName(18, "Popeye"), new AgeName(28, "Alan") }); context.NameNemesis.AddRange(new[] { new NameNemesis("Jonah", "Whales"), new NameNemesis("Jonah", "Spiders"), new NameNemesis("Alan", "Ghosts"), new NameNemesis("Alan", "Zombies"), new NameNemesis("Glory", "Buffy") }); return context; } } }
table1=: ;:;._2(0 :0) 27 Jonah 18 Alan 28 Glory 18 Popeye 28 Alan ) table2=: ;:;._2(0 :0) Jonah Whales Jonah Spiders Alan Ghosts Alan Zombies Glory Buffy )
Convert this C# snippet to J and keep its semantics consistent.
using Mpir.NET; using System; using System.Collections.Generic; class MaxLftTrP_B { static void Main() { mpz_t p; var sw = System.Diagnostics.Stopwatch.StartNew(); L(3); for (uint b = 3; b < 13; b++) { sw.Restart(); p = L(b); Console.WriteLine("{0} {1,2} {2}", sw.Elapsed, b, p); } Console.Read(); } static mpz_t L(uint b) { var p = new List<mpz_t>(); mpz_t np = 0; while ((np = nxtP(np)) < b) p.Add(np); int i0 = 0, i = 0, i1 = p.Count - 1; mpz_t n0 = b, n, n1 = b * (b - 1); for (; i < p.Count; n0 *= b, n1 *= b, i0 = i1 + 1, i1 = p.Count - 1) for (n = n0; n <= n1; n += n0) for (i = i0; i <= i1; i++) if (mpir.mpz_probab_prime_p(np = n + p[i], 15) > 0) p.Add(np); return p[p.Count - 1]; } static mpz_t nxtP(mpz_t n) { mpz_t p = 0; mpir.mpz_nextprime(p, n); return p; } }
ltp=:3 :0 probe=. i.1 0 while. #probe do. probe=. (#~ 1 p: y #.]),/(}.i.y),"0 _1/have=. probe end. >./y#.have )
Write the same algorithm in J as shown in this C# implementation.
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 }, new [] { 1,4,5,6 }, new [] { 3,3,8,8 }, new [] { 4,4,5,9 }, new [] { 5,5,5,5 }, new [] { 5,6,7,8 }, new [] { 6,6,6,6 }, new [] { 6,7,8,9 }, }; foreach (var t in testCases) Test(24, t); Test(100, 9,9,9,9,9,9); static void Test(int target, params int[] numbers) { foreach (var eq in GenerateEquations(target, numbers)) Console.WriteLine(eq); Console.WriteLine(); } } static readonly char[] ops = { '*', '/', '+', '-' }; public static IEnumerable<string> GenerateEquations(int target, params int[] numbers) { var operators = Repeat(ops, numbers.Length - 1).CartesianProduct().Select(e => e.ToArray()).ToList(); return ( from pattern in Patterns(numbers.Length) let expression = CreateExpression(pattern) from ops in operators where expression.WithOperators(ops).HasPreferredTree() from permutation in Permutations(numbers) let expr = expression.WithValues(permutation) where expr.Value == target && expr.HasPreferredValues() select $"{expr.ToString()} = {target}") .Distinct() .DefaultIfEmpty($"Cannot make {target} with {string.Join(", ", numbers)}"); } static IEnumerable<int> Patterns(int length) { if (length == 1) yield return 0; if (length == 2) yield return 1; if (length < 3) yield break; length -= 2; int len = length * 2 + 3; foreach (int permutation in BinaryPatterns(length, length * 2)) { (int p, int l) = ((permutation << 1) + 1, len); if (IsValidPattern(ref p, ref l)) yield return (permutation << 1) + 1; } } static IEnumerable<int> BinaryPatterns(int ones, int length) { int initial = (1 << ones) - 1; int blockMask = (1 << length) - 1; for (int v = initial; v >= initial; ) { yield return v; int w = (v | (v - 1)) + 1; w |= (((w & -w) / (v & -v)) >> 1) - 1; v = w & blockMask; } } static bool IsValidPattern(ref int pattern, ref int len) { bool isNumber = (pattern & 1) == 0; pattern >>= 1; len--; if (isNumber) return true; IsValidPattern(ref pattern, ref len); IsValidPattern(ref pattern, ref len); return len == 0; } static Expr CreateExpression(int pattern) { return Create(); Expr Create() { bool isNumber = (pattern & 1) == 0; pattern >>= 1; if (isNumber) return new Const(0); Expr right = Create(); Expr left = Create(); return new Binary('*', left, right); } } static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } private static List<int> helper = new List<int>(); public static IEnumerable<T[]> Permutations<T>(params T[] input) { if (input == null || input.Length == 0) yield break; helper.Clear(); for (int i = 0; i < input.Length; i++) helper.Add(i); while (true) { yield return input; int cursor = helper.Count - 2; while (cursor >= 0 && helper[cursor] > helper[cursor + 1]) cursor--; if (cursor < 0) break; int i = helper.Count - 1; while (i > cursor && helper[i] < helper[cursor]) i--; (helper[cursor], helper[i]) = (helper[i], helper[cursor]); (input[cursor], input[i]) = (input[i], input[cursor]); int firstIndex = cursor + 1; for (int lastIndex = helper.Count - 1; lastIndex > firstIndex; ++firstIndex, --lastIndex) { (helper[firstIndex], helper[lastIndex]) = (helper[lastIndex], helper[firstIndex]); (input[firstIndex], input[lastIndex]) = (input[lastIndex], input[firstIndex]); } } } static Expr WithOperators(this Expr expr, char[] operators) { int i = 0; SetOperators(expr, operators, ref i); return expr; static void SetOperators(Expr expr, char[] operators, ref int i) { if (expr is Binary b) { b.Symbol = operators[i++]; SetOperators(b.Right, operators, ref i); SetOperators(b.Left, operators, ref i); } } } static Expr WithValues(this Expr expr, int[] values) { int i = 0; SetValues(expr, values, ref i); return expr; static void SetValues(Expr expr, int[] values, ref int i) { if (expr is Binary b) { SetValues(b.Left, values, ref i); SetValues(b.Right, values, ref i); } else { expr.Value = values[i++]; } } } static bool HasPreferredTree(this Expr expr) => expr switch { Const _ => true, ((_, '/' ,_), '*', _) => false, (var l, '+', (_, '*' ,_) r) when l.Depth < r.Depth => false, (var l, '+', (_, '/' ,_) r) when l.Depth < r.Depth => false, (var l, '*', (_, '+' ,_) r) when l.Depth < r.Depth => false, (var l, '*', (_, '-' ,_) r) when l.Depth < r.Depth => false, ((_, var p, _), '+', (_, var q, _)) when "+-".Contains(p) && "*/".Contains(q) => false, (var l, '+', (_, '+' ,_) r) => false, (var l, '+', (_, '-' ,_) r) => false, (_, '-', (_, '+', _)) => false, (var l, '*', (_, '*' ,_) r) => false, (var l, '*', (_, '/' ,_) r) => false, (var l, '/', (_, '/' ,_) r) => false, (_, '-', ((_, '-' ,_), '*', _)) => false, (_, '-', ((_, '-' ,_), '/', _)) => false, (_, '-', (_, '-', _)) => false, ((_, '-', var b), '+', var c) => false, (var l, _, var r) => l.HasPreferredTree() && r.HasPreferredTree() }; static bool HasPreferredValues(this Expr expr) => expr switch { Const _ => true, (var l, '+', var r) when l.Value < 0 && r.Value >= 0 => false, (var l, '*', var r) when l.Depth == r.Depth && l.Value > r.Value => false, (var l, '+', var r) when l.Depth == r.Depth && l.Value > r.Value => false, ((var a, _, _) l, '*', (var c, _, _) r) when l.Value == r.Value && l.Depth == r.Depth && a.Value < c.Value => false, ((var a, var p, _) l, '+', (var c, var q, _) r) when l.Value == r.Value && l.Depth == r.Depth && a.Value < c.Value => false, ((_, '*', var c), '*', var b) when b.Value < c.Value => false, ((_, '+', var c), '+', var b) when b.Value < c.Value => false, ((_, '-', var b), '-', var c) when b.Value < c.Value => false, (_, '/', var b) when b.Value == 1 => false, ((_, '*', var b), '/', var c) when b.Value == c.Value => false, ((_, '*', var b), '*', var c) when b.Value == 1 && c.Value == 1 => false, (var l, _, var r) => l.HasPreferredValues() && r.HasPreferredValues() }; private struct Fraction : IEquatable<Fraction>, IComparable<Fraction> { public readonly int Numerator, Denominator; public Fraction(int numerator, int denominator) => (Numerator, Denominator) = (numerator, denominator) switch { (_, 0) => (Math.Sign(numerator), 0), (0, _) => (0, 1), (_, var d) when d < 0 => (-numerator, -denominator), _ => (numerator, denominator) }; public static implicit operator Fraction(int i) => new Fraction(i, 1); public static Fraction operator +(Fraction a, Fraction b) => new Fraction(a.Numerator * b.Denominator + a.Denominator * b.Numerator, a.Denominator * b.Denominator); public static Fraction operator -(Fraction a, Fraction b) => new Fraction(a.Numerator * b.Denominator + a.Denominator * -b.Numerator, a.Denominator * b.Denominator); public static Fraction operator *(Fraction a, Fraction b) => new Fraction(a.Numerator * b.Numerator, a.Denominator * b.Denominator); public static Fraction operator /(Fraction a, Fraction b) => new Fraction(a.Numerator * b.Denominator, a.Denominator * b.Numerator); public static bool operator ==(Fraction a, Fraction b) => a.CompareTo(b) == 0; public static bool operator !=(Fraction a, Fraction b) => a.CompareTo(b) != 0; public static bool operator <(Fraction a, Fraction b) => a.CompareTo(b) < 0; public static bool operator >(Fraction a, Fraction b) => a.CompareTo(b) > 0; public static bool operator <=(Fraction a, Fraction b) => a.CompareTo(b) <= 0; public static bool operator >=(Fraction a, Fraction b) => a.CompareTo(b) >= 0; public bool Equals(Fraction other) => Numerator == other.Numerator && Denominator == other.Denominator; public override string ToString() => Denominator == 1 ? Numerator.ToString() : $"[{Numerator}/{Denominator}]"; public int CompareTo(Fraction other) => (Numerator, Denominator, other.Numerator, other.Denominator) switch { var ( n1, d1, n2, d2) when n1 == n2 && d1 == d2 => 0, ( 0, 0, _, _) => (-1), ( _, _, 0, 0) => 1, var ( n1, d1, n2, d2) when d1 == d2 => n1.CompareTo(n2), (var n1, 0, _, _) => Math.Sign(n1), ( _, _, var n2, 0) => Math.Sign(n2), var ( n1, d1, n2, d2) => (n1 * d2).CompareTo(n2 * d1) }; } private abstract class Expr { protected Expr(char symbol) => Symbol = symbol; public char Symbol { get; set; } public abstract Fraction Value { get; set; } public abstract int Depth { get; } public abstract void Deconstruct(out Expr left, out char symbol, out Expr right); } private sealed class Const : Expr { public Const(Fraction value) : base('c') => Value = value; public override Fraction Value { get; set; } public override int Depth => 0; public override void Deconstruct(out Expr left, out char symbol, out Expr right) => (left, symbol, right) = (this, Symbol, this); public override string ToString() => Value.ToString(); } private sealed class Binary : Expr { public Binary(char symbol, Expr left, Expr right) : base(symbol) => (Left, Right) = (left, right); public Expr Left { get; } public Expr Right { get; } public override int Depth => Math.Max(Left.Depth, Right.Depth) + 1; public override void Deconstruct(out Expr left, out char symbol, out Expr right) => (left, symbol, right) = (Left, Symbol, Right); public override Fraction Value { get => Symbol switch { '*' => Left.Value * Right.Value, '/' => Left.Value / Right.Value, '+' => Left.Value + Right.Value, '-' => Left.Value - Right.Value, _ => throw new InvalidOperationException() }; set {} } public override string ToString() => Symbol switch { '*' => ToString("+-".Contains(Left.Symbol), "+-".Contains(Right.Symbol)), '/' => ToString("+-".Contains(Left.Symbol), "*/+-".Contains(Right.Symbol)), '+' => ToString(false, false), '-' => ToString(false, "+-".Contains(Right.Symbol)), _ => $"[{Value}]" }; private string ToString(bool wrapLeft, bool wrapRight) => $"{(wrapLeftΒ ? $"({Left})"Β : $"{Left}")} {Symbol} {(wrapRightΒ ? $"({Right})"Β : $"{Right}")}"; } }
perm=: (A.&i.~ !) 4 ops=: ' ',.'+-*%' {~ >,{i.each 4 4 4 cmask=: 1 + 0j1 * i.@{:@$@[ e. ] left=: [ #!.'('~"1 cmask right=: [ #!.')'~"1 cmask paren=: 2 :'[: left&m right&n' parens=: ], 0 paren 3, 0 paren 5, 2 paren 5, [: 0 paren 7 (0 paren 3) all=: [: parens [:,/ ops ,@,."1/ perm { [:;":each answer=: ({.@#~ 24 = ".)@all
Write the same algorithm in J as shown in this C# implementation.
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 }, new [] { 1,4,5,6 }, new [] { 3,3,8,8 }, new [] { 4,4,5,9 }, new [] { 5,5,5,5 }, new [] { 5,6,7,8 }, new [] { 6,6,6,6 }, new [] { 6,7,8,9 }, }; foreach (var t in testCases) Test(24, t); Test(100, 9,9,9,9,9,9); static void Test(int target, params int[] numbers) { foreach (var eq in GenerateEquations(target, numbers)) Console.WriteLine(eq); Console.WriteLine(); } } static readonly char[] ops = { '*', '/', '+', '-' }; public static IEnumerable<string> GenerateEquations(int target, params int[] numbers) { var operators = Repeat(ops, numbers.Length - 1).CartesianProduct().Select(e => e.ToArray()).ToList(); return ( from pattern in Patterns(numbers.Length) let expression = CreateExpression(pattern) from ops in operators where expression.WithOperators(ops).HasPreferredTree() from permutation in Permutations(numbers) let expr = expression.WithValues(permutation) where expr.Value == target && expr.HasPreferredValues() select $"{expr.ToString()} = {target}") .Distinct() .DefaultIfEmpty($"Cannot make {target} with {string.Join(", ", numbers)}"); } static IEnumerable<int> Patterns(int length) { if (length == 1) yield return 0; if (length == 2) yield return 1; if (length < 3) yield break; length -= 2; int len = length * 2 + 3; foreach (int permutation in BinaryPatterns(length, length * 2)) { (int p, int l) = ((permutation << 1) + 1, len); if (IsValidPattern(ref p, ref l)) yield return (permutation << 1) + 1; } } static IEnumerable<int> BinaryPatterns(int ones, int length) { int initial = (1 << ones) - 1; int blockMask = (1 << length) - 1; for (int v = initial; v >= initial; ) { yield return v; int w = (v | (v - 1)) + 1; w |= (((w & -w) / (v & -v)) >> 1) - 1; v = w & blockMask; } } static bool IsValidPattern(ref int pattern, ref int len) { bool isNumber = (pattern & 1) == 0; pattern >>= 1; len--; if (isNumber) return true; IsValidPattern(ref pattern, ref len); IsValidPattern(ref pattern, ref len); return len == 0; } static Expr CreateExpression(int pattern) { return Create(); Expr Create() { bool isNumber = (pattern & 1) == 0; pattern >>= 1; if (isNumber) return new Const(0); Expr right = Create(); Expr left = Create(); return new Binary('*', left, right); } } static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } private static List<int> helper = new List<int>(); public static IEnumerable<T[]> Permutations<T>(params T[] input) { if (input == null || input.Length == 0) yield break; helper.Clear(); for (int i = 0; i < input.Length; i++) helper.Add(i); while (true) { yield return input; int cursor = helper.Count - 2; while (cursor >= 0 && helper[cursor] > helper[cursor + 1]) cursor--; if (cursor < 0) break; int i = helper.Count - 1; while (i > cursor && helper[i] < helper[cursor]) i--; (helper[cursor], helper[i]) = (helper[i], helper[cursor]); (input[cursor], input[i]) = (input[i], input[cursor]); int firstIndex = cursor + 1; for (int lastIndex = helper.Count - 1; lastIndex > firstIndex; ++firstIndex, --lastIndex) { (helper[firstIndex], helper[lastIndex]) = (helper[lastIndex], helper[firstIndex]); (input[firstIndex], input[lastIndex]) = (input[lastIndex], input[firstIndex]); } } } static Expr WithOperators(this Expr expr, char[] operators) { int i = 0; SetOperators(expr, operators, ref i); return expr; static void SetOperators(Expr expr, char[] operators, ref int i) { if (expr is Binary b) { b.Symbol = operators[i++]; SetOperators(b.Right, operators, ref i); SetOperators(b.Left, operators, ref i); } } } static Expr WithValues(this Expr expr, int[] values) { int i = 0; SetValues(expr, values, ref i); return expr; static void SetValues(Expr expr, int[] values, ref int i) { if (expr is Binary b) { SetValues(b.Left, values, ref i); SetValues(b.Right, values, ref i); } else { expr.Value = values[i++]; } } } static bool HasPreferredTree(this Expr expr) => expr switch { Const _ => true, ((_, '/' ,_), '*', _) => false, (var l, '+', (_, '*' ,_) r) when l.Depth < r.Depth => false, (var l, '+', (_, '/' ,_) r) when l.Depth < r.Depth => false, (var l, '*', (_, '+' ,_) r) when l.Depth < r.Depth => false, (var l, '*', (_, '-' ,_) r) when l.Depth < r.Depth => false, ((_, var p, _), '+', (_, var q, _)) when "+-".Contains(p) && "*/".Contains(q) => false, (var l, '+', (_, '+' ,_) r) => false, (var l, '+', (_, '-' ,_) r) => false, (_, '-', (_, '+', _)) => false, (var l, '*', (_, '*' ,_) r) => false, (var l, '*', (_, '/' ,_) r) => false, (var l, '/', (_, '/' ,_) r) => false, (_, '-', ((_, '-' ,_), '*', _)) => false, (_, '-', ((_, '-' ,_), '/', _)) => false, (_, '-', (_, '-', _)) => false, ((_, '-', var b), '+', var c) => false, (var l, _, var r) => l.HasPreferredTree() && r.HasPreferredTree() }; static bool HasPreferredValues(this Expr expr) => expr switch { Const _ => true, (var l, '+', var r) when l.Value < 0 && r.Value >= 0 => false, (var l, '*', var r) when l.Depth == r.Depth && l.Value > r.Value => false, (var l, '+', var r) when l.Depth == r.Depth && l.Value > r.Value => false, ((var a, _, _) l, '*', (var c, _, _) r) when l.Value == r.Value && l.Depth == r.Depth && a.Value < c.Value => false, ((var a, var p, _) l, '+', (var c, var q, _) r) when l.Value == r.Value && l.Depth == r.Depth && a.Value < c.Value => false, ((_, '*', var c), '*', var b) when b.Value < c.Value => false, ((_, '+', var c), '+', var b) when b.Value < c.Value => false, ((_, '-', var b), '-', var c) when b.Value < c.Value => false, (_, '/', var b) when b.Value == 1 => false, ((_, '*', var b), '/', var c) when b.Value == c.Value => false, ((_, '*', var b), '*', var c) when b.Value == 1 && c.Value == 1 => false, (var l, _, var r) => l.HasPreferredValues() && r.HasPreferredValues() }; private struct Fraction : IEquatable<Fraction>, IComparable<Fraction> { public readonly int Numerator, Denominator; public Fraction(int numerator, int denominator) => (Numerator, Denominator) = (numerator, denominator) switch { (_, 0) => (Math.Sign(numerator), 0), (0, _) => (0, 1), (_, var d) when d < 0 => (-numerator, -denominator), _ => (numerator, denominator) }; public static implicit operator Fraction(int i) => new Fraction(i, 1); public static Fraction operator +(Fraction a, Fraction b) => new Fraction(a.Numerator * b.Denominator + a.Denominator * b.Numerator, a.Denominator * b.Denominator); public static Fraction operator -(Fraction a, Fraction b) => new Fraction(a.Numerator * b.Denominator + a.Denominator * -b.Numerator, a.Denominator * b.Denominator); public static Fraction operator *(Fraction a, Fraction b) => new Fraction(a.Numerator * b.Numerator, a.Denominator * b.Denominator); public static Fraction operator /(Fraction a, Fraction b) => new Fraction(a.Numerator * b.Denominator, a.Denominator * b.Numerator); public static bool operator ==(Fraction a, Fraction b) => a.CompareTo(b) == 0; public static bool operator !=(Fraction a, Fraction b) => a.CompareTo(b) != 0; public static bool operator <(Fraction a, Fraction b) => a.CompareTo(b) < 0; public static bool operator >(Fraction a, Fraction b) => a.CompareTo(b) > 0; public static bool operator <=(Fraction a, Fraction b) => a.CompareTo(b) <= 0; public static bool operator >=(Fraction a, Fraction b) => a.CompareTo(b) >= 0; public bool Equals(Fraction other) => Numerator == other.Numerator && Denominator == other.Denominator; public override string ToString() => Denominator == 1 ? Numerator.ToString() : $"[{Numerator}/{Denominator}]"; public int CompareTo(Fraction other) => (Numerator, Denominator, other.Numerator, other.Denominator) switch { var ( n1, d1, n2, d2) when n1 == n2 && d1 == d2 => 0, ( 0, 0, _, _) => (-1), ( _, _, 0, 0) => 1, var ( n1, d1, n2, d2) when d1 == d2 => n1.CompareTo(n2), (var n1, 0, _, _) => Math.Sign(n1), ( _, _, var n2, 0) => Math.Sign(n2), var ( n1, d1, n2, d2) => (n1 * d2).CompareTo(n2 * d1) }; } private abstract class Expr { protected Expr(char symbol) => Symbol = symbol; public char Symbol { get; set; } public abstract Fraction Value { get; set; } public abstract int Depth { get; } public abstract void Deconstruct(out Expr left, out char symbol, out Expr right); } private sealed class Const : Expr { public Const(Fraction value) : base('c') => Value = value; public override Fraction Value { get; set; } public override int Depth => 0; public override void Deconstruct(out Expr left, out char symbol, out Expr right) => (left, symbol, right) = (this, Symbol, this); public override string ToString() => Value.ToString(); } private sealed class Binary : Expr { public Binary(char symbol, Expr left, Expr right) : base(symbol) => (Left, Right) = (left, right); public Expr Left { get; } public Expr Right { get; } public override int Depth => Math.Max(Left.Depth, Right.Depth) + 1; public override void Deconstruct(out Expr left, out char symbol, out Expr right) => (left, symbol, right) = (Left, Symbol, Right); public override Fraction Value { get => Symbol switch { '*' => Left.Value * Right.Value, '/' => Left.Value / Right.Value, '+' => Left.Value + Right.Value, '-' => Left.Value - Right.Value, _ => throw new InvalidOperationException() }; set {} } public override string ToString() => Symbol switch { '*' => ToString("+-".Contains(Left.Symbol), "+-".Contains(Right.Symbol)), '/' => ToString("+-".Contains(Left.Symbol), "*/+-".Contains(Right.Symbol)), '+' => ToString(false, false), '-' => ToString(false, "+-".Contains(Right.Symbol)), _ => $"[{Value}]" }; private string ToString(bool wrapLeft, bool wrapRight) => $"{(wrapLeftΒ ? $"({Left})"Β : $"{Left}")} {Symbol} {(wrapRightΒ ? $"({Right})"Β : $"{Right}")}"; } }
perm=: (A.&i.~ !) 4 ops=: ' ',.'+-*%' {~ >,{i.each 4 4 4 cmask=: 1 + 0j1 * i.@{:@$@[ e. ] left=: [ #!.'('~"1 cmask right=: [ #!.')'~"1 cmask paren=: 2 :'[: left&m right&n' parens=: ], 0 paren 3, 0 paren 5, 2 paren 5, [: 0 paren 7 (0 paren 3) all=: [: parens [:,/ ops ,@,."1/ perm { [:;":each answer=: ({.@#~ 24 = ".)@all
Generate a J translation of this C# snippet without changing its computational steps.
using System; using System.Collections.Generic; using System.Numerics; namespace TonelliShanks { class Solution { private readonly BigInteger root1, root2; private readonly bool exists; public Solution(BigInteger root1, BigInteger root2, bool exists) { this.root1 = root1; this.root2 = root2; this.exists = exists; } public BigInteger Root1() { return root1; } public BigInteger Root2() { return root2; } public bool Exists() { return exists; } } class Program { static Solution Ts(BigInteger n, BigInteger p) { if (BigInteger.ModPow(n, (p - 1) / 2, p) != 1) { return new Solution(0, 0, false); } BigInteger q = p - 1; BigInteger ss = 0; while ((q & 1) == 0) { ss = ss + 1; q = q >> 1; } if (ss == 1) { BigInteger r1 = BigInteger.ModPow(n, (p + 1) / 4, p); return new Solution(r1, p - r1, true); } BigInteger z = 2; while (BigInteger.ModPow(z, (p - 1) / 2, p) != p - 1) { z = z + 1; } BigInteger c = BigInteger.ModPow(z, q, p); BigInteger r = BigInteger.ModPow(n, (q + 1) / 2, p); BigInteger t = BigInteger.ModPow(n, q, p); BigInteger m = ss; while (true) { if (t == 1) { return new Solution(r, p - r, true); } BigInteger i = 0; BigInteger zz = t; while (zz != 1 && i < (m - 1)) { zz = zz * zz % p; i = i + 1; } BigInteger b = c; BigInteger e = m - i - 1; while (e > 0) { b = b * b % p; e = e - 1; } r = r * b % p; c = b * b % p; t = t * c % p; m = i; } } static void Main(string[] args) { List<Tuple<long, long>> pairs = new List<Tuple<long, long>>() { new Tuple<long, long>(10, 13), new Tuple<long, long>(56, 101), new Tuple<long, long>(1030, 10009), new Tuple<long, long>(1032, 10009), new Tuple<long, long>(44402, 100049), new Tuple<long, long>(665820697, 1000000009), new Tuple<long, long>(881398088036, 1000000000039), }; foreach (var pair in pairs) { Solution sol = Ts(pair.Item1, pair.Item2); Console.WriteLine("n = {0}", pair.Item1); Console.WriteLine("p = {0}", pair.Item2); if (sol.Exists()) { Console.WriteLine("root1 = {0}", sol.Root1()); Console.WriteLine("root2 = {0}", sol.Root2()); } else { Console.WriteLine("No solution exists"); } Console.WriteLine(); } BigInteger bn = BigInteger.Parse("41660815127637347468140745042827704103445750172002"); BigInteger bp = BigInteger.Pow(10, 50) + 577; Solution bsol = Ts(bn, bp); Console.WriteLine("n = {0}", bn); Console.WriteLine("p = {0}", bp); if (bsol.Exists()) { Console.WriteLine("root1 = {0}", bsol.Root1()); Console.WriteLine("root2 = {0}", bsol.Root2()); } else { Console.WriteLine("No solution exists"); } } } }
leg=: dyad define x (y&|)@^ (y-1)%2 ) tosh=:dyad define assert. 1=1 p: y [ 'y must be prime' assert. 1=x leg y [ 'x must be square mod y' pow=. y&|@^ if. 1=m=. {.1 q: y-1 do. r=. x pow (y+1)%4 else. z=. 1x while. 1>: z leg y do. z=.z+1 end. c=. z pow q=. (y-1)%2^m r=. x pow (q+1)%2 t=. x pow q while. t~:1 do. n=. t i=. 0 whilst. 1~:n do. n=. n pow 2 i=. i+1 end. r=. y|r*b=. c pow 2^m-i+1 m=. i t=. y|t*c=. b pow 2 end. end. y|(,-)r )
Write the same code in J as shown below in C#.
using System; using System.Collections.Generic; using System.Numerics; namespace TonelliShanks { class Solution { private readonly BigInteger root1, root2; private readonly bool exists; public Solution(BigInteger root1, BigInteger root2, bool exists) { this.root1 = root1; this.root2 = root2; this.exists = exists; } public BigInteger Root1() { return root1; } public BigInteger Root2() { return root2; } public bool Exists() { return exists; } } class Program { static Solution Ts(BigInteger n, BigInteger p) { if (BigInteger.ModPow(n, (p - 1) / 2, p) != 1) { return new Solution(0, 0, false); } BigInteger q = p - 1; BigInteger ss = 0; while ((q & 1) == 0) { ss = ss + 1; q = q >> 1; } if (ss == 1) { BigInteger r1 = BigInteger.ModPow(n, (p + 1) / 4, p); return new Solution(r1, p - r1, true); } BigInteger z = 2; while (BigInteger.ModPow(z, (p - 1) / 2, p) != p - 1) { z = z + 1; } BigInteger c = BigInteger.ModPow(z, q, p); BigInteger r = BigInteger.ModPow(n, (q + 1) / 2, p); BigInteger t = BigInteger.ModPow(n, q, p); BigInteger m = ss; while (true) { if (t == 1) { return new Solution(r, p - r, true); } BigInteger i = 0; BigInteger zz = t; while (zz != 1 && i < (m - 1)) { zz = zz * zz % p; i = i + 1; } BigInteger b = c; BigInteger e = m - i - 1; while (e > 0) { b = b * b % p; e = e - 1; } r = r * b % p; c = b * b % p; t = t * c % p; m = i; } } static void Main(string[] args) { List<Tuple<long, long>> pairs = new List<Tuple<long, long>>() { new Tuple<long, long>(10, 13), new Tuple<long, long>(56, 101), new Tuple<long, long>(1030, 10009), new Tuple<long, long>(1032, 10009), new Tuple<long, long>(44402, 100049), new Tuple<long, long>(665820697, 1000000009), new Tuple<long, long>(881398088036, 1000000000039), }; foreach (var pair in pairs) { Solution sol = Ts(pair.Item1, pair.Item2); Console.WriteLine("n = {0}", pair.Item1); Console.WriteLine("p = {0}", pair.Item2); if (sol.Exists()) { Console.WriteLine("root1 = {0}", sol.Root1()); Console.WriteLine("root2 = {0}", sol.Root2()); } else { Console.WriteLine("No solution exists"); } Console.WriteLine(); } BigInteger bn = BigInteger.Parse("41660815127637347468140745042827704103445750172002"); BigInteger bp = BigInteger.Pow(10, 50) + 577; Solution bsol = Ts(bn, bp); Console.WriteLine("n = {0}", bn); Console.WriteLine("p = {0}", bp); if (bsol.Exists()) { Console.WriteLine("root1 = {0}", bsol.Root1()); Console.WriteLine("root2 = {0}", bsol.Root2()); } else { Console.WriteLine("No solution exists"); } } } }
leg=: dyad define x (y&|)@^ (y-1)%2 ) tosh=:dyad define assert. 1=1 p: y [ 'y must be prime' assert. 1=x leg y [ 'x must be square mod y' pow=. y&|@^ if. 1=m=. {.1 q: y-1 do. r=. x pow (y+1)%4 else. z=. 1x while. 1>: z leg y do. z=.z+1 end. c=. z pow q=. (y-1)%2^m r=. x pow (q+1)%2 t=. x pow q while. t~:1 do. n=. t i=. 0 whilst. 1~:n do. n=. n pow 2 i=. i+1 end. r=. y|r*b=. c pow 2^m-i+1 m=. i t=. y|t*c=. b pow 2 end. end. y|(,-)r )
Change the following C# code into J without altering its purpose.
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<char, Operator> operators = new Dictionary<char, Operator>(); public TruthTable(char falseConstant, char trueConstant) { this.trueConstant = trueConstant; this.falseConstant = falseConstant; Operators = new OperatorCollection(operators); } public OperatorCollection Operators { get; } public void PrintTruthTable(string expression, bool isPostfix = false) { try { foreach (string line in GetTruthTable(expression, isPostfix)) { Console.WriteLine(line); } } catch (ArgumentException ex) { Console.WriteLine(expression + " " + ex.Message); } } public IEnumerable<string> GetTruthTable(string expression, bool isPostfix = false) { if (string.IsNullOrWhiteSpace(expression)) throw new ArgumentException("Invalid expression."); var parameters = expression .Where(c => TypeOf(c) == TokenType.Operand) .Distinct() .Reverse() .Select((c, i) => (symbol: c, index: i)) .ToDictionary(p => p.symbol, p => p.index); int count = parameters.Count; if (count > 32) throw new ArgumentException("Cannot have more than 32 parameters."); string header = count == 0 ? expression : string.Join(" ", parameters.OrderByDescending(p => p.Value).Select(p => p.Key)) + " " + expression; if (!isPostfix) expression = ConvertToPostfix(expression); var values = default(BitSet); var stack = new Stack<char>(expression.Length); for (int loop = 1 << count; loop > 0; loop--) { foreach (char token in expression) stack.Push(token); bool result = Evaluate(stack, values, parameters); if (header != null) { if (stack.Count > 0) throw new ArgumentException("Invalid expression."); yield return header; header = null; } string line = (count == 0 ? "" : " ") + (result ? trueConstant : falseConstant); line = string.Join(" ", Enumerable.Range(0, count) .Select(i => values[count - i - 1] ? trueConstant : falseConstant)) + line; yield return line; values++; } } public string ConvertToPostfix(string infix) { var stack = new Stack<char>(); var postfix = new StringBuilder(); foreach (char c in infix) { switch (TypeOf(c)) { case TokenType.WhiteSpace: continue; case TokenType.Constant: case TokenType.Operand: postfix.Append(c); break; case TokenType.Operator: int precedence = Precedence(c); while (stack.Count > 0 && Precedence(stack.Peek()) > precedence) { postfix.Append(stack.Pop()); } stack.Push(c); break; case TokenType.LeftParenthesis: stack.Push(c); break; case TokenType.RightParenthesis: char top = default(char); while (stack.Count > 0) { top = stack.Pop(); if (top == '(') break; else postfix.Append(top); } if (top != '(') throw new ArgumentException("No matching left parenthesis."); break; default: throw new ArgumentException("Invalid character: " + c); } } while (stack.Count > 0) { char top = stack.Pop(); if (top == '(') throw new ArgumentException("No matching right parenthesis."); postfix.Append(top); } return postfix.ToString(); } private bool Evaluate(Stack<char> expression, BitSet values, IDictionary<char, int> parameters) { if (expression.Count == 0) throw new ArgumentException("Invalid expression."); char c = expression.Pop(); TokenType type = TypeOf(c); while (type == TokenType.WhiteSpace) type = TypeOf(c = expression.Pop()); switch (type) { case TokenType.Constant: return c == trueConstant; case TokenType.Operand: return values[parameters[c]]; case TokenType.Operator: bool right = Evaluate(expression, values, parameters); Operator op = operators[c]; if (op.Arity == 1) return op.Function(right, right); bool left = Evaluate(expression, values, parameters); return op.Function(left, right); default: throw new ArgumentException("Invalid character: " + c); } } private TokenType TypeOf(char c) { if (char.IsWhiteSpace(c)) return TokenType.WhiteSpace; if (c == '(') return TokenType.LeftParenthesis; if (c == ')') return TokenType.RightParenthesis; if (c == trueConstant || c == falseConstant) return TokenType.Constant; if (operators.ContainsKey(c)) return TokenType.Operator; if (char.IsLetter(c)) return TokenType.Operand; return TokenType.Unknown; } private int Precedence(char op) => operators.TryGetValue(op, out var o) ? o.Precedence : int.MinValue; } struct Operator { public Operator(char symbol, int precedence, Func<bool, bool> function) : this(symbol, precedence, 1, (l, r) => function(r)) { } public Operator(char symbol, int precedence, Func<bool, bool, bool> function) : this(symbol, precedence, 2, function) { } private Operator(char symbol, int precedence, int arity, Func<bool, bool, bool> function) : this() { Symbol = symbol; Precedence = precedence; Arity = arity; Function = function; } public char Symbol { get; } public int Precedence { get; } public int Arity { get; } public Func<bool, bool, bool> Function { get; } } public class OperatorCollection : IEnumerable { readonly IDictionary<char, Operator> operators; internal OperatorCollection(IDictionary<char, Operator> operators) { this.operators = operators; } public void Add(char symbol, int precedence, Func<bool, bool> function) => operators[symbol] = new Operator(symbol, precedence, function); public void Add(char symbol, int precedence, Func<bool, bool, bool> function) => operators[symbol] = new Operator(symbol, precedence, function); public void Remove(char symbol) => operators.Remove(symbol); IEnumerator IEnumerable.GetEnumerator() => operators.Values.GetEnumerator(); } struct BitSet { private int bits; private BitSet(int bits) { this.bits = bits; } public static BitSet operator ++(BitSet bitSet) => new BitSet(bitSet.bits + 1); public bool this[int index] => (bits & (1 << index)) != 0; } class Program { public static void Main() { TruthTable tt = new TruthTable('F', 'T') { Operators = { { '!', 6, r => !r }, { '&', 5, (l, r) => l && r }, { '^', 4, (l, r) => l ^ r }, { '|', 3, (l, r) => l || r } } }; var rng = new Random(); tt.Operators.Add('?', 6, r => rng.NextDouble() < 0.5); string[] expressions = { "!!!T", "?T", "F & x | T", "F & (x | T", "F & x | T)", "aΒ ! (a & a)", "a | (a * a)", "a ^ T & (b & !c)", }; foreach (string expression in expressions) { tt.PrintTruthTable(expression); Console.WriteLine(); } tt = new TruthTable('0', '1') { Operators = { { '-', 6, r => !r }, { '^', 5, (l, r) => l && r }, { 'v', 3, (l, r) => l || r }, { '>', 2, (l, r) => !l || r }, { '=', 1, (l, r) => l == r }, } }; expressions = new[] { "-X v 0 = X ^ 1", "(H > M) ^ (S > H) > (S > M)" }; foreach (string expression in expressions) { tt.PrintTruthTable(expression); Console.WriteLine(); } } }
truthTable=:3 :0 assert. -. 1 e. 'data expr names table' e.&;: y names=. ~. (#~ _1 <: nc) ;:expr=. y data=. #:i.2^#names (names)=. |:data (' ',;:inv names,<expr),(1+#@>names,<expr)":data,.".expr )
Maintain the same structure and functionality when rewriting this code in J.
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<char, Operator> operators = new Dictionary<char, Operator>(); public TruthTable(char falseConstant, char trueConstant) { this.trueConstant = trueConstant; this.falseConstant = falseConstant; Operators = new OperatorCollection(operators); } public OperatorCollection Operators { get; } public void PrintTruthTable(string expression, bool isPostfix = false) { try { foreach (string line in GetTruthTable(expression, isPostfix)) { Console.WriteLine(line); } } catch (ArgumentException ex) { Console.WriteLine(expression + " " + ex.Message); } } public IEnumerable<string> GetTruthTable(string expression, bool isPostfix = false) { if (string.IsNullOrWhiteSpace(expression)) throw new ArgumentException("Invalid expression."); var parameters = expression .Where(c => TypeOf(c) == TokenType.Operand) .Distinct() .Reverse() .Select((c, i) => (symbol: c, index: i)) .ToDictionary(p => p.symbol, p => p.index); int count = parameters.Count; if (count > 32) throw new ArgumentException("Cannot have more than 32 parameters."); string header = count == 0 ? expression : string.Join(" ", parameters.OrderByDescending(p => p.Value).Select(p => p.Key)) + " " + expression; if (!isPostfix) expression = ConvertToPostfix(expression); var values = default(BitSet); var stack = new Stack<char>(expression.Length); for (int loop = 1 << count; loop > 0; loop--) { foreach (char token in expression) stack.Push(token); bool result = Evaluate(stack, values, parameters); if (header != null) { if (stack.Count > 0) throw new ArgumentException("Invalid expression."); yield return header; header = null; } string line = (count == 0 ? "" : " ") + (result ? trueConstant : falseConstant); line = string.Join(" ", Enumerable.Range(0, count) .Select(i => values[count - i - 1] ? trueConstant : falseConstant)) + line; yield return line; values++; } } public string ConvertToPostfix(string infix) { var stack = new Stack<char>(); var postfix = new StringBuilder(); foreach (char c in infix) { switch (TypeOf(c)) { case TokenType.WhiteSpace: continue; case TokenType.Constant: case TokenType.Operand: postfix.Append(c); break; case TokenType.Operator: int precedence = Precedence(c); while (stack.Count > 0 && Precedence(stack.Peek()) > precedence) { postfix.Append(stack.Pop()); } stack.Push(c); break; case TokenType.LeftParenthesis: stack.Push(c); break; case TokenType.RightParenthesis: char top = default(char); while (stack.Count > 0) { top = stack.Pop(); if (top == '(') break; else postfix.Append(top); } if (top != '(') throw new ArgumentException("No matching left parenthesis."); break; default: throw new ArgumentException("Invalid character: " + c); } } while (stack.Count > 0) { char top = stack.Pop(); if (top == '(') throw new ArgumentException("No matching right parenthesis."); postfix.Append(top); } return postfix.ToString(); } private bool Evaluate(Stack<char> expression, BitSet values, IDictionary<char, int> parameters) { if (expression.Count == 0) throw new ArgumentException("Invalid expression."); char c = expression.Pop(); TokenType type = TypeOf(c); while (type == TokenType.WhiteSpace) type = TypeOf(c = expression.Pop()); switch (type) { case TokenType.Constant: return c == trueConstant; case TokenType.Operand: return values[parameters[c]]; case TokenType.Operator: bool right = Evaluate(expression, values, parameters); Operator op = operators[c]; if (op.Arity == 1) return op.Function(right, right); bool left = Evaluate(expression, values, parameters); return op.Function(left, right); default: throw new ArgumentException("Invalid character: " + c); } } private TokenType TypeOf(char c) { if (char.IsWhiteSpace(c)) return TokenType.WhiteSpace; if (c == '(') return TokenType.LeftParenthesis; if (c == ')') return TokenType.RightParenthesis; if (c == trueConstant || c == falseConstant) return TokenType.Constant; if (operators.ContainsKey(c)) return TokenType.Operator; if (char.IsLetter(c)) return TokenType.Operand; return TokenType.Unknown; } private int Precedence(char op) => operators.TryGetValue(op, out var o) ? o.Precedence : int.MinValue; } struct Operator { public Operator(char symbol, int precedence, Func<bool, bool> function) : this(symbol, precedence, 1, (l, r) => function(r)) { } public Operator(char symbol, int precedence, Func<bool, bool, bool> function) : this(symbol, precedence, 2, function) { } private Operator(char symbol, int precedence, int arity, Func<bool, bool, bool> function) : this() { Symbol = symbol; Precedence = precedence; Arity = arity; Function = function; } public char Symbol { get; } public int Precedence { get; } public int Arity { get; } public Func<bool, bool, bool> Function { get; } } public class OperatorCollection : IEnumerable { readonly IDictionary<char, Operator> operators; internal OperatorCollection(IDictionary<char, Operator> operators) { this.operators = operators; } public void Add(char symbol, int precedence, Func<bool, bool> function) => operators[symbol] = new Operator(symbol, precedence, function); public void Add(char symbol, int precedence, Func<bool, bool, bool> function) => operators[symbol] = new Operator(symbol, precedence, function); public void Remove(char symbol) => operators.Remove(symbol); IEnumerator IEnumerable.GetEnumerator() => operators.Values.GetEnumerator(); } struct BitSet { private int bits; private BitSet(int bits) { this.bits = bits; } public static BitSet operator ++(BitSet bitSet) => new BitSet(bitSet.bits + 1); public bool this[int index] => (bits & (1 << index)) != 0; } class Program { public static void Main() { TruthTable tt = new TruthTable('F', 'T') { Operators = { { '!', 6, r => !r }, { '&', 5, (l, r) => l && r }, { '^', 4, (l, r) => l ^ r }, { '|', 3, (l, r) => l || r } } }; var rng = new Random(); tt.Operators.Add('?', 6, r => rng.NextDouble() < 0.5); string[] expressions = { "!!!T", "?T", "F & x | T", "F & (x | T", "F & x | T)", "aΒ ! (a & a)", "a | (a * a)", "a ^ T & (b & !c)", }; foreach (string expression in expressions) { tt.PrintTruthTable(expression); Console.WriteLine(); } tt = new TruthTable('0', '1') { Operators = { { '-', 6, r => !r }, { '^', 5, (l, r) => l && r }, { 'v', 3, (l, r) => l || r }, { '>', 2, (l, r) => !l || r }, { '=', 1, (l, r) => l == r }, } }; expressions = new[] { "-X v 0 = X ^ 1", "(H > M) ^ (S > H) > (S > M)" }; foreach (string expression in expressions) { tt.PrintTruthTable(expression); Console.WriteLine(); } } }
truthTable=:3 :0 assert. -. 1 e. 'data expr names table' e.&;: y names=. ~. (#~ _1 <: nc) ;:expr=. y data=. #:i.2^#names (names)=. |:data (' ',;:inv names,<expr),(1+#@>names,<expr)":data,.".expr )
Port the following code from C# to J with equivalent syntax and logic.
using System; namespace RosettaCode.SetOfRealNumbers { public class Set<TValue> { public Set(Predicate<TValue> contains) { Contains = contains; } public Predicate<TValue> Contains { get; private set; } public Set<TValue> Union(Set<TValue> set) { return new Set<TValue>(value => Contains(value) || set.Contains(value)); } public Set<TValue> Intersection(Set<TValue> set) { return new Set<TValue>(value => Contains(value) && set.Contains(value)); } public Set<TValue> Difference(Set<TValue> set) { return new Set<TValue>(value => Contains(value) && !set.Contains(value)); } } }
has=: 1 :'(interval m)`:6' ing=: `'' interval=: 3 :0 if.0<L.y do.y return.end. assert. 5=#words=. ;:y assert. (0 { words) e. ;:'[(' assert. (2 { words) e. ;:',' assert. (4 { words) e. ;:'])' 'lo hi'=.(1 3{0".L:0 words) 'cL cH'=.0 4{words e.;:'[]' (lo&(<`<:@.cL) *. hi&(>`>:@.cH))ing ) union=: 4 :'(x has +. y has)ing' intersect=: 4 :'(x has *. y has)ing' without=: 4 :'(x has *. [: -. y has)ing'
Write a version of this C# function in J with identical behavior.
using System; namespace RosettaCode.SetOfRealNumbers { public class Set<TValue> { public Set(Predicate<TValue> contains) { Contains = contains; } public Predicate<TValue> Contains { get; private set; } public Set<TValue> Union(Set<TValue> set) { return new Set<TValue>(value => Contains(value) || set.Contains(value)); } public Set<TValue> Intersection(Set<TValue> set) { return new Set<TValue>(value => Contains(value) && set.Contains(value)); } public Set<TValue> Difference(Set<TValue> set) { return new Set<TValue>(value => Contains(value) && !set.Contains(value)); } } }
has=: 1 :'(interval m)`:6' ing=: `'' interval=: 3 :0 if.0<L.y do.y return.end. assert. 5=#words=. ;:y assert. (0 { words) e. ;:'[(' assert. (2 { words) e. ;:',' assert. (4 { words) e. ;:'])' 'lo hi'=.(1 3{0".L:0 words) 'cL cH'=.0 4{words e.;:'[]' (lo&(<`<:@.cL) *. hi&(>`>:@.cH))ing ) union=: 4 :'(x has +. y has)ing' intersect=: 4 :'(x has *. y has)ing' without=: 4 :'(x has *. [: -. y has)ing'
Keep all operations the same but rewrite the snippet in J.
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 { static Maybe<double> MonadicSquareRoot(double x) { if (x >= 0) { return new Maybe<double>.Some(Math.Sqrt(x)); } else { return new Maybe<double>.None(); } } static void Main(string[] args) { foreach (double x in new double[] { 4.0D, 8.0D, -15.0D, 16.23D, -42 }) { Maybe<double> maybe = MonadicSquareRoot(x); if (maybe is Maybe<double>.Some some) { Console.WriteLine($"The square root of {x} is " + some.Value); } else { Console.WriteLine($"Square root of {x} is undefined."); } } } } }
unit=: < bind=: (@>)( :: ]) safeVersion=: (<@) ( ::((<_.)"_)) safeCompose=:dyad define dyad def 'x`:6 bind y'/x,unit y ) subtractFromSelf=: -~ divideBySelf=: %~ safeSubtractFromSelf=: subtractFromSelf safeVersion safeDivideBySelf=: divideBySelf safeVersion safeSubtractFromSelf bind safeDivideBySelf 1 β”Œβ”€β” β”‚0β”‚ β””β”€β”˜ safeSubtractFromSelf bind safeDivideBySelf _ β”Œβ”€β”€β” β”‚_.β”‚ β””β”€β”€β”˜
Write the same algorithm in J as shown in this C# implementation.
using System; using System.Drawing; using System.Windows.Forms; class MineFieldModel { public int RemainingMinesCount{ get{ var count = 0; ForEachCell((i,j)=>{ if (Mines[i,j] && !Marked[i,j]) count++; }); return count; } } public bool[,] Mines{get; private set;} public bool[,] Opened{get;private set;} public bool[,] Marked{get; private set;} public int[,] Values{get;private set; } public int Width{ get{return Mines.GetLength(1);} } public int Height{ get{return Mines.GetLength(0);} } public MineFieldModel(bool[,] mines) { this.Mines = mines; this.Opened = new bool[Height, Width]; this.Marked = new bool[Height, Width]; this.Values = CalculateValues(); } private int[,] CalculateValues() { int[,] values = new int[Height, Width]; ForEachCell((i,j) =>{ var value = 0; ForEachNeighbor(i,j, (i1,j1)=>{ if (Mines[i1,j1]) value++; }); values[i,j] = value; }); return values; } public void ForEachCell(Action<int,int> action) { for (var i = 0; i < Height; i++) for (var j = 0; j < Width; j++) action(i,j); } public void ForEachNeighbor(int i, int j, Action<int,int> action) { for (var i1 = i-1; i1 <= i+1; i1++) for (var j1 = j-1; j1 <= j+1; j1++) if (InBounds(j1, i1) && !(i1==i && j1 ==j)) action(i1, j1); } private bool InBounds(int x, int y) { return y >= 0 && y < Height && x >=0 && x < Width; } public event Action Exploded = delegate{}; public event Action Win = delegate{}; public event Action Updated = delegate{}; public void OpenCell(int i, int j){ if(!Opened[i,j]){ if (Mines[i,j]) Exploded(); else{ OpenCellsStartingFrom(i,j); Updated(); CheckForVictory(); } } } void OpenCellsStartingFrom(int i, int j) { Opened[i,j] = true; ForEachNeighbor(i,j, (i1,j1)=>{ if (!Mines[i1,j1] && !Opened[i1,j1] && !Marked[i1,j1]) OpenCellsStartingFrom(i1, j1); }); } void CheckForVictory(){ int notMarked = 0; int wrongMarked = 0; ForEachCell((i,j)=>{ if (Mines[i,j] && !Marked[i,j]) notMarked++; if (!Mines[i,j] && Marked[i,j]) wrongMarked++; }); if (notMarked == 0 && wrongMarked == 0) Win(); } public void Mark(int i, int j){ if (!Opened[i,j]) Marked[i,j] = true; Updated(); CheckForVictory(); } } class MineFieldView: UserControl{ public const int CellSize = 40; MineFieldModel _model; public MineFieldModel Model{ get{ return _model; } set { _model = value; this.Size = new Size(_model.Width * CellSize+1, _model.Height * CellSize+2); } } public MineFieldView(){ this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer,true); this.Font = new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold); this.MouseUp += (o,e)=>{ Point cellCoords = GetCell(e.Location); if (Model != null) { if (e.Button == MouseButtons.Left) Model.OpenCell(cellCoords.Y, cellCoords.X); else if (e.Button == MouseButtons.Right) Model.Mark(cellCoords.Y, cellCoords.X); } }; } Point GetCell(Point coords) { var rgn = ClientRectangle; var x = (coords.X - rgn.X)/CellSize; var y = (coords.Y - rgn.Y)/CellSize; return new Point(x,y); } static readonly Brush MarkBrush = new SolidBrush(Color.Blue); static readonly Brush ValueBrush = new SolidBrush(Color.Black); static readonly Brush UnexploredBrush = new SolidBrush(SystemColors.Control); static readonly Brush OpenBrush = new SolidBrush(SystemColors.ControlDark); protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); var g = e.Graphics; if (Model != null) { Model.ForEachCell((i,j)=> { var bounds = new Rectangle(j * CellSize, i * CellSize, CellSize, CellSize); if (Model.Opened[i,j]) { g.FillRectangle(OpenBrush, bounds); if (Model.Values[i,j] > 0) { DrawStringInCenter(g, Model.Values[i,j].ToString(), ValueBrush, bounds); } } else { g.FillRectangle(UnexploredBrush, bounds); if (Model.Marked[i,j]) { DrawStringInCenter(g, "?", MarkBrush, bounds); } var outlineOffset = 1; var outline = new Rectangle(bounds.X+outlineOffset, bounds.Y+outlineOffset, bounds.Width-2*outlineOffset, bounds.Height-2*outlineOffset); g.DrawRectangle(Pens.Gray, outline); } g.DrawRectangle(Pens.Black, bounds); }); } } static readonly StringFormat FormatCenter = new StringFormat { LineAlignment = StringAlignment.Center, Alignment=StringAlignment.Center }; void DrawStringInCenter(Graphics g, string s, Brush brush, Rectangle bounds) { PointF center = new PointF(bounds.X + bounds.Width/2, bounds.Y + bounds.Height/2); g.DrawString(s, this.Font, brush, center, FormatCenter); } } class MineSweepForm: Form { MineFieldModel CreateField(int width, int height) { var field = new bool[height, width]; int mineCount = (int)(0.2 * height * width); var rnd = new Random(); while(mineCount > 0) { var x = rnd.Next(width); var y = rnd.Next(height); if (!field[y,x]) { field[y,x] = true; mineCount--; } } return new MineFieldModel(field); } public MineSweepForm() { var model = CreateField(6, 4); var counter = new Label{ }; counter.Text = model.RemainingMinesCount.ToString(); var view = new MineFieldView { Model = model, BorderStyle = BorderStyle.FixedSingle, }; var stackPanel = new FlowLayoutPanel { Dock = DockStyle.Fill, FlowDirection = FlowDirection.TopDown, Controls = {counter, view} }; this.Controls.Add(stackPanel); model.Updated += delegate{ view.Invalidate(); counter.Text = model.RemainingMinesCount.ToString(); }; model.Exploded += delegate { MessageBox.Show("FAIL!"); Close(); }; model.Win += delegate { MessageBox.Show("WIN!"); view.Enabled = false; }; } } class Program { static void Main() { Application.Run(new MineSweepForm()); } }
coclass 'mineswpeng' newMinefield=: 3Β : 0 if. 0=#y do. y=. 9 9 end. Marked=: Cleared=: y$0 NMines=: <. */(0.01*10+?20),y mines=. (i. e. NMines ? */) y Map=: (9*mines) >. y{. (1,:3 3) +/@,;.3 (-1+y){.mines ) markTiles=: 3Β : 0 Marked=: (<"1 <:y) (-.@{)`[`]} Marked ) clearTiles=: clearcell@:<: clearcell=: verb define if. #y do. free=. (#~ (Cleared < 0 = Map) {~ <"1) y Cleared=: 1 (<"1 y)} Cleared if. #free do. clearcell (#~ Cleared -.@{~ <"1) ~. (<:$Map) (<."1) 0 >. getNbrs free end. end. ) getNbrs=: [: ,/^:(3=#@$) +"1/&(<: 3 3#: i.9) eval=: verb define if. 9 e. Cleared #&, Map do. 1; 'KABOOM!!' elseif. *./ 9 = (-.Cleared) #&, Map do. 1; 'Minefield cleared.' elseif. do. 0; (": +/, Marked>Cleared),' of ',(":NMines),' mines marked.' end. ) showField=: 4Β : 0 idx=. y{ (2 <. Marked + +:Cleared) ,: 2 |: idx} (11&{ , 12&{ ,: Map&{) x ) Minesweeper_z_=: conew&'mineswp' coclass 'mineswp' coinsert 'mineswpeng' Tiles=: ' 12345678**.?' create=: verb define smoutput Instructions startgame y ) destroy=: codestroy quit=: destroy startgame=: update@newMinefield clear=: update@clearTiles mark=: update@markTiles update=: 3Β : 0 'isend msg'=. eval '' smoutput msg smoutput < Tiles showField isend if. isend do. msg=. ('K'={.msg) {:: 'won';'lost' smoutput 'You ',msg,'! Try again?' destroy '' end. empty'' ) Instructions=: 0Β : 0 === MineSweeper === Object: Uncover (clear) all the tiles that are not mines. How to play: - the left, top tile is: 1 1 - clear an uncleared tile (.) using the command: clear__fld <column index> <row index> - mark and uncleared tile (?) as a suspected mine using the command: mark__fld <column index> <row index> - if you uncover a number, that is the number of mines adjacent to the tile - if you uncover a mine (*) the game ends (you lose) - if you uncover all tiles that are not mines the game ends (you win). - quit a game before winning or losing using the command: quit__fld '' - start a new game using the command: fld=: MineSweeper <num columns> <num rows> )
Convert this C# block to J, preserving its control flow and logic.
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x)); public static Church Multiply(this Church m, Church n) => f => m(n(f)); public static Church Exponent(this Church m, Church n) => n(m); public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne); public static Church Predecessor(this Church n) => f => x => n(g => h => h(g(f)))(_ => x)(a => a); public static Church Subtract(this Church m, Church n) => n(Predecessor)(m); static Church looper(this Church v, Church d) => v(_ => v.divr(d).Successor())(ChurchZero); static Church divr(this Church n, Church d) => n.Subtract(d).looper(d); public static Church Divide(this Church dvdnd, Church dvsr) => (dvdnd.Successor()).divr(dvsr); public static Church FromInt(int i) => i <= 0 ? ChurchZero : Successor(FromInt(i - 1)); public static int ToInt(this Church ch) { int count = 0; ch(x => { count++; return x; })(null); return count; } public static void Main() { Church c3 = FromInt(3); Church c4 = c3.Successor(); Church c11 = FromInt(11); Church c12 = c11.Successor(); int sum = c3.Add(c4).ToInt(); int product = c3.Multiply(c4).ToInt(); int exp43 = c4.Exponent(c3).ToInt(); int exp34 = c3.Exponent(c4).ToInt(); int tst0 = ChurchZero.IsZero().ToInt(); int pred4 = c4.Predecessor().ToInt(); int sub43 = c4.Subtract(c3).ToInt(); int div11by3 = c11.Divide(c3).ToInt(); int div12by3 = c12.Divide(c3).ToInt(); Console.Write($"{sum} {product} {exp43} {exp34} {tst0} "); Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}"); } }
chget=: {{(0;1;1;1) {:: y}} chset=: {{ 'A B'=.;y 'C D'=.B 'E F'=.D <A;<C;<E;<<.x }} ch0=: {{ if.0=#y do.y=.;:'>:' end. 0 chset y`:6^:2`'' }} apply=: `:6 chNext=: {{(1+chget y) chset y}} chAdd=: {{(x +&chget y) chset y}} chSub=: {{(x -&chget y) chset y}} chMul=: {{(x *&chget y) chset y}} chExp=: {{(x ^&chget y) chset y}} int2ch=: {{y chset ch0 ''}} ch2int=: chget
Please provide an equivalent version of this C# code in J.
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x)); public static Church Multiply(this Church m, Church n) => f => m(n(f)); public static Church Exponent(this Church m, Church n) => n(m); public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne); public static Church Predecessor(this Church n) => f => x => n(g => h => h(g(f)))(_ => x)(a => a); public static Church Subtract(this Church m, Church n) => n(Predecessor)(m); static Church looper(this Church v, Church d) => v(_ => v.divr(d).Successor())(ChurchZero); static Church divr(this Church n, Church d) => n.Subtract(d).looper(d); public static Church Divide(this Church dvdnd, Church dvsr) => (dvdnd.Successor()).divr(dvsr); public static Church FromInt(int i) => i <= 0 ? ChurchZero : Successor(FromInt(i - 1)); public static int ToInt(this Church ch) { int count = 0; ch(x => { count++; return x; })(null); return count; } public static void Main() { Church c3 = FromInt(3); Church c4 = c3.Successor(); Church c11 = FromInt(11); Church c12 = c11.Successor(); int sum = c3.Add(c4).ToInt(); int product = c3.Multiply(c4).ToInt(); int exp43 = c4.Exponent(c3).ToInt(); int exp34 = c3.Exponent(c4).ToInt(); int tst0 = ChurchZero.IsZero().ToInt(); int pred4 = c4.Predecessor().ToInt(); int sub43 = c4.Subtract(c3).ToInt(); int div11by3 = c11.Divide(c3).ToInt(); int div12by3 = c12.Divide(c3).ToInt(); Console.Write($"{sum} {product} {exp43} {exp34} {tst0} "); Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}"); } }
chget=: {{(0;1;1;1) {:: y}} chset=: {{ 'A B'=.;y 'C D'=.B 'E F'=.D <A;<C;<E;<<.x }} ch0=: {{ if.0=#y do.y=.;:'>:' end. 0 chset y`:6^:2`'' }} apply=: `:6 chNext=: {{(1+chget y) chset y}} chAdd=: {{(x +&chget y) chset y}} chSub=: {{(x -&chget y) chset y}} chMul=: {{(x *&chget y) chset y}} chExp=: {{(x ^&chget y) chset y}} int2ch=: {{y chset ch0 ''}} ch2int=: chget
Please provide an equivalent version of this C# code in J.
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(TestForMethodReflection).GetMethods(flags)) Console.WriteLine(method); } class TestForMethodReflection { public void MyPublicMethod() {} private void MyPrivateMethod() {} public static void MyPublicStaticMethod() {} private static void MyPrivateStaticMethod() {} } }
coclass 'Stack' create =: 3 : 'items =: i. 0' push =: 3 : '# items =: items , < y' top =: 3 : '> {: items' pop =: 3 : ([;._2' a =. top 0; items =: }: items; a;') destroy =: codestroy cocurrent 'base' names_Stack_'' create destroy pop push top 'p' names_Stack_ 3 pop push S =: conew~ 'Stack' names__S'' COCREATOR items pop__S 3Β : 0 a =. top 0 items =: }: items a ) copath S β”Œβ”€β”€β”€β”€β”€β”¬β”€β” β”‚Stackβ”‚zβ”‚ β””β”€β”€β”€β”€β”€β”΄β”€β”˜ names__S 0 COCREATOR items
Change the programming language of this snippet from C# to J without modifying what it does.
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 }); Console.WriteLine("{0}(5) = {1}", method, result); } }
sum =: +/ prod =: */ count =: # nameToDispatch =: 'sum' ". nameToDispatch,' 1 2 3' 6 nameToDispatch~ 1 2 3 6 nameToDispatch (128!:2) 1 2 3 6 nameToDispatch =: 'count' ". nameToDispatch,' 1 2 3' 3 nameToDispatch~ 1 2 3 3 nameToDispatch (128!:2) 1 2 3 3
Write the same algorithm in J as shown in this C# implementation.
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", "184.232.176.184/18" }; foreach (string t in tests) Console.WriteLine($"{t} => {Canonicalize(t)}"); } static string Canonicalize(string cidr) => CIDR.Parse(cidr).Canonicalize().ToString(); } readonly struct CIDR { public readonly IPAddress ip; public readonly int length; public static CIDR Parse(string cidr) { string[] parts = cidr.Split('/'); return new CIDR(IPAddress.Parse(parts[0]), int.Parse(parts[1])); } public CIDR(IPAddress ip, int length) => (this.ip, this.length) = (ip, length); public CIDR Canonicalize() => new CIDR( new IPAddress( ToBytes( ToInt( ip.GetAddressBytes() ) & ~((1 << (32 - length)) - 1) ) ), length ); private int ToInt(byte[] bytes) => bytes.Aggregate(0, (n, b) => (n << 8) | b); private byte[] ToBytes(int n) { byte[] bytes = new byte[4]; for (int i = 3; i >= 0; i--) { bytes[i] = (byte)(n & 0xFF); n >>= 8; } return bytes; } public override string ToString() => $"{ip}/{length}"; }
cidr=: {{ 'a e'=. 0 ".each (y rplc'. ')-.&;:'/' ('/',":e),~rplc&' .'":_8#.\32{.e{.,(8#2)#:a }}
Rewrite the snippet below in J 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", "184.232.176.184/18" }; foreach (string t in tests) Console.WriteLine($"{t} => {Canonicalize(t)}"); } static string Canonicalize(string cidr) => CIDR.Parse(cidr).Canonicalize().ToString(); } readonly struct CIDR { public readonly IPAddress ip; public readonly int length; public static CIDR Parse(string cidr) { string[] parts = cidr.Split('/'); return new CIDR(IPAddress.Parse(parts[0]), int.Parse(parts[1])); } public CIDR(IPAddress ip, int length) => (this.ip, this.length) = (ip, length); public CIDR Canonicalize() => new CIDR( new IPAddress( ToBytes( ToInt( ip.GetAddressBytes() ) & ~((1 << (32 - length)) - 1) ) ), length ); private int ToInt(byte[] bytes) => bytes.Aggregate(0, (n, b) => (n << 8) | b); private byte[] ToBytes(int n) { byte[] bytes = new byte[4]; for (int i = 3; i >= 0; i--) { bytes[i] = (byte)(n & 0xFF); n >>= 8; } return bytes; } public override string ToString() => $"{ip}/{length}"; }
cidr=: {{ 'a e'=. 0 ".each (y rplc'. ')-.&;:'/' ('/',":e),~rplc&' .'":_8#.\32{.e{.,(8#2)#:a }}
Change the programming language of this snippet from C# to J without modifying what it does.
using System; using System.Numerics; class AgmPie { static BigInteger IntSqRoot(BigInteger valu, BigInteger guess) { BigInteger term; do { term = valu / guess; if (BigInteger.Abs(term - guess) <= 1) break; guess += term; guess >>= 1; } while (true); return guess; } static BigInteger ISR(BigInteger term, BigInteger guess) { BigInteger valu = term * guess; do { if (BigInteger.Abs(term - guess) <= 1) break; guess += term; guess >>= 1; term = valu / guess; } while (true); return guess; } static BigInteger CalcAGM(BigInteger lam, BigInteger gm, ref BigInteger z, BigInteger ep) { BigInteger am, zi; ulong n = 1; do { am = (lam + gm) >> 1; gm = ISR(lam, gm); BigInteger v = am - lam; if ((zi = v * v * n) < ep) break; z -= zi; n <<= 1; lam = am; } while (true); return am; } static BigInteger BIP(int exp, ulong man = 1) { BigInteger rv = BigInteger.Pow(10, exp); return man == 1 ? rv : man * rv; } static void Main(string[] args) { int d = 25000; if (args.Length > 0) { int.TryParse(args[0], out d); if (d < 1 || d > 999999) d = 25000; } DateTime st = DateTime.Now; BigInteger am = BIP(d), gm = IntSqRoot(BIP(d + d - 1, 5), BIP(d - 15, (ulong)(Math.Sqrt(0.5) * 1e+15))), z = BIP(d + d - 2, 25), agm = CalcAGM(am, gm, ref z, BIP(d + 1)), pi = agm * agm * BIP(d - 2) / z; Console.WriteLine("Computation time: {0:0.0000} seconds ", (DateTime.Now - st).TotalMilliseconds / 1000); string s = pi.ToString(); Console.WriteLine("{0}.{1}", s[0], s.Substring(1)); if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey(); } }
DP=: 100 round=: DP&$: : (4Β : 0) b %~ <.1r2+y*b=. 10x^x ) sqrt=: DP&$: : (4Β : 0) " 0 assert. 0<:y %/ <.@%: (2 x: (2*x) round y)*10x^2*x+0>.>.10^.y ) pi =: 3Β : 0 A =. N =. 1x 'G Z HALF' =. (% sqrt 2) , 1r4 1r2 for_I. i.18 do. X =. ((A + G) * HALF) , sqrt A * G VAR =. ({.X) - A Z =. Z - VAR * VAR * N N =. +: N 'A G' =. X PI =: A * A % Z echo (0j100":PI) , 4 ": I end. PI )
Write the same algorithm in J as shown in this C# implementation.
using System; using System.Numerics; class AgmPie { static BigInteger IntSqRoot(BigInteger valu, BigInteger guess) { BigInteger term; do { term = valu / guess; if (BigInteger.Abs(term - guess) <= 1) break; guess += term; guess >>= 1; } while (true); return guess; } static BigInteger ISR(BigInteger term, BigInteger guess) { BigInteger valu = term * guess; do { if (BigInteger.Abs(term - guess) <= 1) break; guess += term; guess >>= 1; term = valu / guess; } while (true); return guess; } static BigInteger CalcAGM(BigInteger lam, BigInteger gm, ref BigInteger z, BigInteger ep) { BigInteger am, zi; ulong n = 1; do { am = (lam + gm) >> 1; gm = ISR(lam, gm); BigInteger v = am - lam; if ((zi = v * v * n) < ep) break; z -= zi; n <<= 1; lam = am; } while (true); return am; } static BigInteger BIP(int exp, ulong man = 1) { BigInteger rv = BigInteger.Pow(10, exp); return man == 1 ? rv : man * rv; } static void Main(string[] args) { int d = 25000; if (args.Length > 0) { int.TryParse(args[0], out d); if (d < 1 || d > 999999) d = 25000; } DateTime st = DateTime.Now; BigInteger am = BIP(d), gm = IntSqRoot(BIP(d + d - 1, 5), BIP(d - 15, (ulong)(Math.Sqrt(0.5) * 1e+15))), z = BIP(d + d - 2, 25), agm = CalcAGM(am, gm, ref z, BIP(d + 1)), pi = agm * agm * BIP(d - 2) / z; Console.WriteLine("Computation time: {0:0.0000} seconds ", (DateTime.Now - st).TotalMilliseconds / 1000); string s = pi.ToString(); Console.WriteLine("{0}.{1}", s[0], s.Substring(1)); if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey(); } }
DP=: 100 round=: DP&$: : (4Β : 0) b %~ <.1r2+y*b=. 10x^x ) sqrt=: DP&$: : (4Β : 0) " 0 assert. 0<:y %/ <.@%: (2 x: (2*x) round y)*10x^2*x+0>.>.10^.y ) pi =: 3Β : 0 A =. N =. 1x 'G Z HALF' =. (% sqrt 2) , 1r4 1r2 for_I. i.18 do. X =. ((A + G) * HALF) , sqrt A * G VAR =. ({.X) - A Z =. Z - VAR * VAR * N N =. +: N 'A G' =. X PI =: A * A % Z echo (0j100":PI) , 4 ": I end. PI )
Can you help me rewrite this code in J instead of C#, keeping it the same logically?
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 BigInteger Den { get; } public Rational(BigInteger n, BigInteger d) { var c = Gcd(n, d); Num = n / c; Den = d / c; if (Den < 0) { Num = -Num; Den = -Den; } } public Rational(BigInteger n) { Num = n; Den = 1; } public override string ToString() { if (Den == 1) { return Num.ToString(); } else { return string.Format("{0}/{1}", Num, Den); } } public Rational Add(Rational rhs) { return new Rational(Num * rhs.Den + rhs.Num * Den, Den * rhs.Den); } public Rational Sub(Rational rhs) { return new Rational(Num * rhs.Den - rhs.Num * Den, Den * rhs.Den); } public int CompareTo(Rational rhs) { var ad = Num * rhs.Den; var bc = Den * rhs.Num; return ad.CompareTo(bc); } public int CompareTo(int rhs) { var ad = Num * rhs; var bc = Den * rhs; return ad.CompareTo(bc); } } static BigInteger Gcd(BigInteger a, BigInteger b) { if (b == 0) { if (a < 0) { return -a; } else { return a; } } else { return Gcd(b, a % b); } } static List<Rational> Egyptian(Rational r) { List<Rational> result = new List<Rational>(); if (r.CompareTo(1) >= 0) { if (r.Den == 1) { result.Add(r); result.Add(new Rational(0)); return result; } result.Add(new Rational(r.Num / r.Den)); r = r.Sub(result[0]); } BigInteger modFunc(BigInteger m, BigInteger n) { return ((m % n) + n) % n; } while (r.Num != 1) { var q = (r.Den + r.Num - 1) / r.Num; result.Add(new Rational(1, q)); r = new Rational(modFunc(-r.Den, r.Num), r.Den * q); } result.Add(r); return result; } static string FormatList<T>(IEnumerable<T> col) { StringBuilder sb = new StringBuilder(); var iter = col.GetEnumerator(); sb.Append('['); if (iter.MoveNext()) { sb.Append(iter.Current); } while (iter.MoveNext()) { sb.AppendFormat(", {0}", iter.Current); } sb.Append(']'); return sb.ToString(); } static void Main() { List<Rational> rs = new List<Rational> { new Rational(43, 48), new Rational(5, 121), new Rational(2014, 59) }; foreach (var r in rs) { Console.WriteLine("{0} => {1}", r, FormatList(Egyptian(r))); } var lenMax = Tuple.Create(0UL, new Rational(0)); var denomMax = Tuple.Create(BigInteger.Zero, new Rational(0)); var query = (from i in Enumerable.Range(1, 100) from j in Enumerable.Range(1, 100) select new Rational(i, j)) .Distinct() .ToList(); foreach (var r in query) { var e = Egyptian(r); ulong eLen = (ulong) e.Count; var eDenom = e.Last().Den; if (eLen > lenMax.Item1) { lenMax = Tuple.Create(eLen, r); } if (eDenom > denomMax.Item1) { denomMax = Tuple.Create(eDenom, r); } } Console.WriteLine("Term max is {0} with {1} terms", lenMax.Item2, lenMax.Item1); var dStr = denomMax.Item1.ToString(); Console.WriteLine("Denominator max is {0} with {1} digits {2}...{3}", denomMax.Item2, dStr.Length, dStr.Substring(0, 5), dStr.Substring(dStr.Length - 5, 5)); } } }
ef =: [: (}.~ 0={.) [: (, r2ef)/ 0 1 #: x: r2ef =: (<(<0);0) { ((] , -) >:@:<.&.%)^:((~:<.)@:%)@:{:^:a:
Maintain the same structure and functionality when rewriting this code in J.
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 BigInteger Den { get; } public Rational(BigInteger n, BigInteger d) { var c = Gcd(n, d); Num = n / c; Den = d / c; if (Den < 0) { Num = -Num; Den = -Den; } } public Rational(BigInteger n) { Num = n; Den = 1; } public override string ToString() { if (Den == 1) { return Num.ToString(); } else { return string.Format("{0}/{1}", Num, Den); } } public Rational Add(Rational rhs) { return new Rational(Num * rhs.Den + rhs.Num * Den, Den * rhs.Den); } public Rational Sub(Rational rhs) { return new Rational(Num * rhs.Den - rhs.Num * Den, Den * rhs.Den); } public int CompareTo(Rational rhs) { var ad = Num * rhs.Den; var bc = Den * rhs.Num; return ad.CompareTo(bc); } public int CompareTo(int rhs) { var ad = Num * rhs; var bc = Den * rhs; return ad.CompareTo(bc); } } static BigInteger Gcd(BigInteger a, BigInteger b) { if (b == 0) { if (a < 0) { return -a; } else { return a; } } else { return Gcd(b, a % b); } } static List<Rational> Egyptian(Rational r) { List<Rational> result = new List<Rational>(); if (r.CompareTo(1) >= 0) { if (r.Den == 1) { result.Add(r); result.Add(new Rational(0)); return result; } result.Add(new Rational(r.Num / r.Den)); r = r.Sub(result[0]); } BigInteger modFunc(BigInteger m, BigInteger n) { return ((m % n) + n) % n; } while (r.Num != 1) { var q = (r.Den + r.Num - 1) / r.Num; result.Add(new Rational(1, q)); r = new Rational(modFunc(-r.Den, r.Num), r.Den * q); } result.Add(r); return result; } static string FormatList<T>(IEnumerable<T> col) { StringBuilder sb = new StringBuilder(); var iter = col.GetEnumerator(); sb.Append('['); if (iter.MoveNext()) { sb.Append(iter.Current); } while (iter.MoveNext()) { sb.AppendFormat(", {0}", iter.Current); } sb.Append(']'); return sb.ToString(); } static void Main() { List<Rational> rs = new List<Rational> { new Rational(43, 48), new Rational(5, 121), new Rational(2014, 59) }; foreach (var r in rs) { Console.WriteLine("{0} => {1}", r, FormatList(Egyptian(r))); } var lenMax = Tuple.Create(0UL, new Rational(0)); var denomMax = Tuple.Create(BigInteger.Zero, new Rational(0)); var query = (from i in Enumerable.Range(1, 100) from j in Enumerable.Range(1, 100) select new Rational(i, j)) .Distinct() .ToList(); foreach (var r in query) { var e = Egyptian(r); ulong eLen = (ulong) e.Count; var eDenom = e.Last().Den; if (eLen > lenMax.Item1) { lenMax = Tuple.Create(eLen, r); } if (eDenom > denomMax.Item1) { denomMax = Tuple.Create(eDenom, r); } } Console.WriteLine("Term max is {0} with {1} terms", lenMax.Item2, lenMax.Item1); var dStr = denomMax.Item1.ToString(); Console.WriteLine("Denominator max is {0} with {1} digits {2}...{3}", denomMax.Item2, dStr.Length, dStr.Substring(0, 5), dStr.Substring(dStr.Length - 5, 5)); } } }
ef =: [: (}.~ 0={.) [: (, r2ef)/ 0 1 #: x: r2ef =: (<(<0);0) { ((] , -) >:@:<.&.%)^:((~:<.)@:%)@:{:^:a:
Change the following C# code into J without altering its purpose.
using System; public class Program { public static double[][] legeCoef(int N) { double[][] lcoef = new double[N+1][]; for (int i=0; i < lcoef.Length; ++i) lcoef[i] = new double[N+1]; lcoef[0][0] = lcoef[1][1] = 1; for (int n = 2; n <= N; n++) { lcoef[n][0] = -(n - 1) * lcoef[n - 2][0] / n; for (int i = 1; i <= n; i++) lcoef[n][i] = ((2*n - 1) * lcoef[n-1][i-1] - (n-1) * lcoef[n-2][i] ) / n; } return lcoef; } static double legeEval(double[][] lcoef, int N, double x) { double s = lcoef[N][N]; for (int i = N; i > 0; --i) s = s * x + lcoef[N][i-1]; return s; } static double legeDiff(double[][] lcoef, int N, double x) { return N * (x * legeEval(lcoef, N, x) - legeEval(lcoef, N-1, x)) / (x*x - 1); } static void legeRoots(double[][] lcoef, int N, out double[] lroots, out double[] weight) { lroots = new double[N]; weight = new double[N]; double x, x1; for (int i = 1; i <= N; i++) { x = Math.Cos(Math.PI * (i - 0.25) / (N + 0.5)); do { x1 = x; x -= legeEval(lcoef, N, x) / legeDiff(lcoef, N, x); } while (x != x1); lroots[i-1] = x; x1 = legeDiff(lcoef, N, x); weight[i-1] = 2 / ((1 - x*x) * x1*x1); } } static double legeInte(Func<Double, Double> f, int N, double[] weights, double[] lroots, double a, double b) { double c1 = (b - a) / 2, c2 = (b + a) / 2, sum = 0; for (int i = 0; i < N; i++) sum += weights[i] * f.Invoke(c1 * lroots[i] + c2); return c1 * sum; } public static string Combine(double[] arrayD) { return string.Join(", ", arrayD); } public static void Main() { int N = 5; var lcoeff = legeCoef(N); double[] roots; double[] weights; legeRoots(lcoeff, N, out roots, out weights); var integrateResult = legeInte(x=>Math.Exp(x), N, weights, roots, -3, 3); Console.WriteLine("Roots: " + Combine(roots)); Console.WriteLine("Weights: " + Combine(weights)+ "\n" ); Console.WriteLine("integral: " + integrateResult ); Console.WriteLine("actual: " + (Math.Exp(3)-Math.Exp(-3)) ); } }
getLegendreCoeffs=: verb define M. if. y<:1 do. 1 {.~ - y+1 return. end. (%~ <:@(,~ +:) -/@:* (0;'') ,&> [: getLegendreCoeffs&.> -&1 2) y ) getPolyRoots=: 1 {:: p. getGaussLegendreWeights=: 2 % -.@*:@[ * (*:@p.~ p..) getGaussLegendrePoints=: (getPolyRoots ([ ,: getGaussLegendreWeights) ])@getLegendreCoeffs integrateGaussLegendre=: adverb define : 'nodes wgts'=. getGaussLegendrePoints x -: (-~/ y) * wgts +/@:* u -: nodes p.~ (+/ , -~/) y )
Change the following C# code into J without altering its purpose.
using System.Diagnostics; using System.Drawing; namespace RosettaChaosGame { class Program { static void Main(string[] args) { var bm = new Bitmap(600, 600); var referencePoints = new Point[] { new Point(0, 600), new Point(600, 600), new Point(300, 81) }; var r = new System.Random(); var p = new Point(r.Next(600), r.Next(600)); for (int count = 0; count < 10000; count++) { bm.SetPixel(p.X, p.Y, Color.Magenta); int i = r.Next(3); p.X = (p.X + referencePoints[i].X) / 2; p.Y = (p.Y + referencePoints[i].Y) / 2; } const string filename = "Chaos Game.png"; bm.Save(filename); Process.Start(filename); } } }
Note 'plan, Working in complex plane' Make an equilateral triangle. Make a list of N targets Starting with a random point near the triangle, iteratively generate new points. plot the new points. j has a particularly rich notation for numbers. 1ad_90 specifies a complex number with radius 1 at an angle of negative 90 degrees. 2p1 is 2 times (pi raised to the first power). ) N=: 3000 require'plot' TAU=: 2p1 mean=: +/ % # TRIANGLE=: *(j./2 1 o.(TAU%6)*?0)*1ad_90 1ad150 1ad30 TARGETS=: (N ?@:# 3) { TRIANGLE START=: j./2 1 o.TAU*?0 NEW_POINTS=: (mean@:(, {.) , ])/ TARGETS , START 'marker'plot NEW_POINTS
Generate an equivalent J version of this C# code.
using System.Diagnostics; using System.Drawing; namespace RosettaChaosGame { class Program { static void Main(string[] args) { var bm = new Bitmap(600, 600); var referencePoints = new Point[] { new Point(0, 600), new Point(600, 600), new Point(300, 81) }; var r = new System.Random(); var p = new Point(r.Next(600), r.Next(600)); for (int count = 0; count < 10000; count++) { bm.SetPixel(p.X, p.Y, Color.Magenta); int i = r.Next(3); p.X = (p.X + referencePoints[i].X) / 2; p.Y = (p.Y + referencePoints[i].Y) / 2; } const string filename = "Chaos Game.png"; bm.Save(filename); Process.Start(filename); } } }
Note 'plan, Working in complex plane' Make an equilateral triangle. Make a list of N targets Starting with a random point near the triangle, iteratively generate new points. plot the new points. j has a particularly rich notation for numbers. 1ad_90 specifies a complex number with radius 1 at an angle of negative 90 degrees. 2p1 is 2 times (pi raised to the first power). ) N=: 3000 require'plot' TAU=: 2p1 mean=: +/ % # TRIANGLE=: *(j./2 1 o.(TAU%6)*?0)*1ad_90 1ad150 1ad30 TARGETS=: (N ?@:# 3) { TRIANGLE START=: j./2 1 o.TAU*?0 NEW_POINTS=: (mean@:(, {.) , ])/ TARGETS , START 'marker'plot NEW_POINTS
Port the provided C# code into J while preserving the original functionality.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using static System.Console; using static System.Linq.Enumerable; namespace WorldCupGroupStage { public static class WorldCupGroupStage { static int[][] _histogram; static WorldCupGroupStage() { int[] scoring = new[] { 0, 1, 3 }; _histogram = Repeat<Func<int[]>>(()=>new int[10], 4).Select(f=>f()).ToArray(); var teamCombos = Range(0, 4).Combinations(2).Select(t2=>t2.ToArray()).ToList(); foreach (var results in Range(0, 3).CartesianProduct(6)) { var points = new int[4]; foreach (var (result, teams) in results.Zip(teamCombos, (r, t) => (r, t))) { points[teams[0]] += scoring[result]; points[teams[1]] += scoring[2 - result]; } foreach(var (p,i) in points.OrderByDescending(a => a).Select((p,i)=>(p,i))) _histogram[i][p]++; } } static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> seqs) => seqs.Aggregate(Empty<T>().ToSingleton(), (acc, sq) => acc.SelectMany(a => sq.Select(s => a.Append(s)))); static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<T> seq, int repeat = 1) => Repeat(seq, repeat).CartesianProduct(); static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> seq) => seq.Aggregate(Empty<T>().ToSingleton(), (a, b) => a.Concat(a.Select(x => x.Append(b)))); static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> seq, int numItems) => seq.Combinations().Where(s => s.Count() == numItems); private static IEnumerable<T> ToSingleton<T>(this T item) { yield return item; } static new string ToString() { var sb = new StringBuilder(); var range = String.Concat(Range(0, 10).Select(i => $"{i,-3} ")); sb.AppendLine($"Points Β : {range}"); var u = String.Concat(Repeat("─", 40+13)); sb.AppendLine($"{u}"); var places = new[] { "First", "Second", "Third", "Fourth" }; foreach (var row in _histogram.Select((r, i) => (r, i))) { sb.Append($"{places[row.i],-6} place: "); foreach (var standing in row.r) sb.Append($"{standing,-3} "); sb.Append("\n"); } return sb.ToString(); } static void Main(string[] args) { Write(ToString()); Read(); } } }
require'stats' outcome=: 3 0,1 1,:0 3 pairs=: (i.4) e."1(2 comb 4) standings=: +/@:>&>,{<"1<"1((i.4) e."1 pairs)#inv"1/ outcome
Produce a functionally identical J code for the snippet given in C#.
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; Console.WriteLine(infix.ToPostfix()); } } public static class ShuntingYard { private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators = new (string symbol, int precedence, bool rightAssociative) [] { ("^", 4, true), ("*", 3, false), ("/", 3, false), ("+", 2, false), ("-", 2, false) }.ToDictionary(op => op.symbol); public static string ToPostfix(this string infix) { string[] tokens = infix.Split(' '); var stack = new Stack<string>(); var output = new List<string>(); foreach (string token in tokens) { if (int.TryParse(token, out _)) { output.Add(token); Print(token); } else if (operators.TryGetValue(token, out var op1)) { while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) { int c = op1.precedence.CompareTo(op2.precedence); if (c < 0 || !op1.rightAssociative && c <= 0) { output.Add(stack.Pop()); } else { break; } } stack.Push(token); Print(token); } else if (token == "(") { stack.Push(token); Print(token); } else if (token == ")") { string top = ""; while (stack.Count > 0 && (top = stack.Pop()) != "(") { output.Add(top); } if (top != "(") throw new ArgumentException("No matching left parenthesis."); Print(token); } } while (stack.Count > 0) { var top = stack.Pop(); if (!operators.ContainsKey(top)) throw new ArgumentException("No matching right parenthesis."); output.Add(top); } Print("pop"); return string.Join(" ", output); void Print(string action) => Console.WriteLine($"{action + ":",-4} {$"stack[ {string.Join(" ", stack.Reverse())} ]",-18} {$"out[ {string.Join(" ", output)} ]"}"); void Print(string action) => Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {string.Join(" ", stack.Reverse())} ]", $"out[ {string.Join(" ", output)} ]"); } }
display=: ([: : (smoutput@:(, [: ; ' '&,&.>@:{:@:|:))) :: empty Display=: adverb define : m display^:(0 -.@:-: x)y ) Queue=: adverb define ('m'~)=: y ,~ (m~) EMPTY : x (m,' queue')Display y m Queue y ) Stack=: adverb define ('m'~)=: (|.y) , (m~) EMPTY : x (m,' stack')Display y m Stack y ) Pop=: adverb define 0 m Pop y : y=. 0 {:@:, y rv=. y {. (m~) ('m'~)=: y }. (m~) x (m,' pop') Display rv rv ) TEST=: '' 'TEST'Stack'abc' 'TEST'Stack'de' assert 'edc' -: 'TEST'Pop 3 assert 'ba' -: 'TEST'Pop 2 assert 0 (= #) TEST 'TEST'Queue'abc' 'TEST'Queue'de' assert 'ab' -: 'TEST'Pop 2 assert 'cde' -: 'TEST'Pop 3 assert 0 (= #) TEST any=: +./ DIGITS=: a. {~ 48+i.10 precedence_oppression=: <;._1' +- */ ^ ( ) ',DIGITS associativity=: 'xLLRxxL' classify=: {:@:I.@:(1 , any@e.&>)&precedence_oppression rclex=: (;~ classify)"0@:;: number=: Q Queue left=: S Stack right=: 4Β : 0 i=. (S~) (i. rclex) '(' if. i (= #) S~ do. smoutput'Check your parens!' throw. end. x Q Queue x S Pop i x S Pop 1 EMPTY ) o=: 4Β : 0 P=. 0 0 {:: y L=. 'L' = P { associativity operators=. ({.~ i.&(rclex'(')) S~ i=. (+/@:(*./\)@:((L *. P&<:) +. ((-.L) *. P&<))@:(0&{::"1)) :: 0: operators x Q Queue x S Pop i x (S Stack) y EMPTY ) invalid=: 4Β : 0 smoutput 'invalid token ',0 1 {:: y throw. ) invalid=: [: smoutput 'discarding invalid token ' , 0 1 {:: ] shunt_yard_parse=: 0&$: : (4Β : 0) 'S Q'=: ;: 'OPERATOR OUTPUT' ('S'~)=:('Q'~)=: i.0 2 x (invalid`o`o`o`left`right`number@.(0 0 {:: ])"2 ,:"1@:rclex) y if. (rclex'(') e. S~ do. smoutput'Check your other parens!' throw. end. x Q Queue x S Pop # S~ Q~ ) algebra_to_rpn=: {:@:|:@:shunt_yard_parse fulfill_requirement=: ;@:(' '&,&.>)@:algebra_to_rpn
Convert this C# snippet to J and keep its semantics consistent.
using System; using System.Collections.Generic; namespace A_star { class A_star { public class Coordinates : IEquatable<Coordinates> { public int row; public int col; public Coordinates() { this.row = -1; this.col = -1; } public Coordinates(int row, int col) { this.row = row; this.col = col; } public Boolean Equals(Coordinates c) { if (this.row == c.row && this.col == c.col) return true; else return false; } } public class Cell { public int cost; public int g; public int f; public Coordinates parent; } public class Astar { public Cell[,] cells = new Cell[8, 8]; public List<Coordinates> path = new List<Coordinates>(); public List<Coordinates> opened = new List<Coordinates>(); public List<Coordinates> closed = new List<Coordinates>(); public Coordinates startCell = new Coordinates(0, 0); public Coordinates finishCell = new Coordinates(7, 7); public Astar() { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) { cells[i, j] = new Cell(); cells[i, j].parent = new Coordinates(); if (IsAWall(i, j)) cells[i, j].cost = 100; else cells[i, j].cost = 1; } opened.Add(startCell); Boolean pathFound = false; do { List<Coordinates> neighbors = new List<Coordinates>(); Coordinates currentCell = ShorterExpectedPath(); neighbors = neighborsCells(currentCell); foreach (Coordinates newCell in neighbors) { if (newCell.row == finishCell.row && newCell.col == finishCell.col) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; pathFound = true; break; } else if (!opened.Contains(newCell) && !closed.Contains(newCell)) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); } else if (cells[newCell.row, newCell.col].g > cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); ResetCell(newCell, closed); } } SetCell(currentCell, closed); ResetCell(currentCell, opened); } while (opened.Count > 0 && pathFound == false); if (pathFound) { path.Add(finishCell); Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col); while (cells[currentCell.row, currentCell.col].parent.row >= 0) { path.Add(cells[currentCell.row, currentCell.col].parent); int tmp_row = cells[currentCell.row, currentCell.col].parent.row; currentCell.col = cells[currentCell.row, currentCell.col].parent.col; currentCell.row = tmp_row; } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { char gr = '.'; if (path.Contains(new Coordinates(i, j))) { gr = 'X'; } else if (cells[i, j].cost > 1) { gr = '\u2588'; } System.Console.Write(gr); } System.Console.WriteLine(); } System.Console.Write("\nPath: "); for (int i = path.Count - 1; i >= 0; i--) { System.Console.Write("({0},{1})", path[i].row, path[i].col); } System.Console.WriteLine("\nPath cost: {0}", path.Count - 1); String wt = System.Console.ReadLine(); } } public Coordinates ShorterExpectedPath() { int sep = 0; if (opened.Count > 1) { for (int i = 1; i < opened.Count; i++) { if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row, opened[sep].col].f) { sep = i; } } } return opened[sep]; } public List<Coordinates> neighborsCells(Coordinates c) { List<Coordinates> lc = new List<Coordinates>(); for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 && (i != 0 || j != 0)) { lc.Add(new Coordinates(c.row + i, c.col + j)); } return lc; } public bool IsAWall(int row, int col) { int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 }, { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } }; bool found = false; for (int i = 0; i < walls.GetLength(0); i++) if (walls[i,0] == row && walls[i,1] == col) found = true; return found; } public int Heuristic(Coordinates cell) { int dRow = Math.Abs(finishCell.row - cell.row); int dCol = Math.Abs(finishCell.col - cell.col); return Math.Max(dRow, dCol); } public void SetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell) == false) { coordinatesList.Add(cell); } } public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell)) { coordinatesList.Remove(cell); } } } static void Main(string[] args) { Astar astar = new Astar(); } } }
barrier=: 2 4,2 5,2 6,3 6,4 6,5 6,5 5,5 4,5 3,5 2,4 2,:3 2 price=: _,.~_,~100 barrier} 8 8$1 dirs=: 0 0-.~>,{,~<i:1 start=: 0 0 end=: 7 7 next=: {{ frontier=. ~.locs=. ,/dests=. ($price)|"1 ({:"2 y)+"1/dirs paths=. ,/y,"2 1/"2 dests costs=. ,x+(<"1 dests){price deals=. (1+locs <.//. costs) <. (<"1 frontier) { values keep=. costs < (frontier i. locs) { deals (keep#costs);keep#paths }} Asrch=: {{ values=: ($price)$_ best=: ($price)$a: paths=: ,:,:start costs=: ,0 while. #paths do. dests=. <"1 {:"2 paths values=: costs dests} values best=: (<"2 paths) dests} best 'costs paths'=.costs next paths end. ((<end){values) ; (<end){best }}
Change the programming language of this snippet from C# to J without modifying what it does.
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) { int gb = 1, dg = ++digs + gb, z; BI t1 = 1, t2 = 9, t3 = 1, te, su = 0, t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1; for (BI n = 0; n < dg; n++) { if (n > 0) t3 *= BI.Pow(n, 6); te = t1 * t2 / t3; if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z); else te /= BI.Pow (10, -z); if (show && n < 10) WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t); su += te; if (te < 10) { if (show) WriteLine("\n{0} iterations required for {1} digits " + "after the decimal point.\n", n, --digs); break; } for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j; t2 += 126 + 532 * (d += 2); } string s = string.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) / su / 32 * 3 * BI.Pow((BI)10, dg + 5))); return s[0] + "." + s.Substring(1, digs); } static void Main(string[] args) { WriteLine(dump(70, true)); } }
numerator =: monad define "0 (3 * (! x: y)^6) %~ 32 * (!6x*y) * (y*(126 + 532*y)) + 9x ) term =: numerator % 10x ^ 3 + 6&* echo 'The first 10 numerators are:' echo ,. numerator i.10 echo '' echo 'The sum of the first 10 terms (pi^-2) is ', 0j15 ": +/ term i.10 heron =: [: -: ] + % sqrt =: dyad define x0 =. }: x eps =. }. x x1 =. y heron x0 while. (| x1 - x0) > eps do. x2 =. y heron x1 x0 =. x1 x1 =. x2 end. x1 ) pi70 =. (355r113, %10^70x) sqrt % +/ term i.53 echo '' echo 'pi to 70 decimals: ', 0j70 ": pi70 exit ''
Can you help me rewrite this code in J instead of C#, keeping it the same logically?
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) { int gb = 1, dg = ++digs + gb, z; BI t1 = 1, t2 = 9, t3 = 1, te, su = 0, t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1; for (BI n = 0; n < dg; n++) { if (n > 0) t3 *= BI.Pow(n, 6); te = t1 * t2 / t3; if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z); else te /= BI.Pow (10, -z); if (show && n < 10) WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t); su += te; if (te < 10) { if (show) WriteLine("\n{0} iterations required for {1} digits " + "after the decimal point.\n", n, --digs); break; } for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j; t2 += 126 + 532 * (d += 2); } string s = string.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) / su / 32 * 3 * BI.Pow((BI)10, dg + 5))); return s[0] + "." + s.Substring(1, digs); } static void Main(string[] args) { WriteLine(dump(70, true)); } }
numerator =: monad define "0 (3 * (! x: y)^6) %~ 32 * (!6x*y) * (y*(126 + 532*y)) + 9x ) term =: numerator % 10x ^ 3 + 6&* echo 'The first 10 numerators are:' echo ,. numerator i.10 echo '' echo 'The sum of the first 10 terms (pi^-2) is ', 0j15 ": +/ term i.10 heron =: [: -: ] + % sqrt =: dyad define x0 =. }: x eps =. }. x x1 =. y heron x0 while. (| x1 - x0) > eps do. x2 =. y heron x1 x0 =. x1 x1 =. x2 end. x1 ) pi70 =. (355r113, %10^70x) sqrt % +/ term i.53 echo '' echo 'pi to 70 decimals: ', 0j70 ": pi70 exit ''
Convert this C# snippet to J and keep its semantics consistent.
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 long gi(int ld, int n) { string Ls = ld.ToString(); long res = 0, count = 0, f = 1; for (int i = 1; i <= 18 - Ls.Length; i++) f *= 10; const long ten18 = (long)1e18; long probe = 1; do { probe <<= 1; res++; if (probe >= ten18) do { if (probe >= ten18) probe /= 10; if (probe / f == ld) if (++count >= n) { count--; break; } probe <<= 1; res++; } while (true); string ps = probe.ToString(); if (ps.Substring(0, Math.Min(Ls.Length, ps.Length)) == Ls) if (++count >= n) break; } while (true); return res; } static long pa(int ld, int n) { double L_float64 = Math.Pow(2, 64); ulong Log10_2_64 = (ulong)(L_float64 * Math.Log10(2)); double Log10Num; ulong LmtUpper, LmtLower, Frac64; long res = 0, dgts = 1, cnt; for (int i = ld; i >= 10; i /= 10) dgts *= 10; Log10Num = Math.Log10((ld + 1.0) / dgts); if (Log10Num >= 0.5) { LmtUpper = (ld + 1.0) / dgts < 10.0 ? (ulong)(Log10Num * (L_float64 * 0.5)) * 2 + (ulong)(Log10Num * 2) : 0; Log10Num = Math.Log10((double)ld / dgts); LmtLower = (ulong)(Log10Num * (L_float64 * 0.5)) * 2 + (ulong)(Log10Num * 2); } else { LmtUpper = (ulong)(Log10Num * L_float64); LmtLower = (ulong)(Math.Log10((double)ld / dgts) * L_float64); } cnt = 0; Frac64 = 0; if (LmtUpper != 0) do { res++; Frac64 += Log10_2_64; if ((Frac64 >= LmtLower) & (Frac64 < LmtUpper)) if (++cnt >= n) break; } while (true); else do { res++; Frac64 += Log10_2_64; if (Frac64 >= LmtLower) if (++cnt >= n) break; } while (true); return res; } static int[] values = new int[] { 12, 1, 12, 2, 123, 45, 123, 12345, 123, 678910, 99, 1 }; static void doOne(string name, Func<int, int, long> fun) { Console.WriteLine("{0} version:", name); var start = DateTime.Now; for (int i = 0; i < values.Length; i += 2) Console.WriteLine("p({0,3}, {1,6}) = {2,11:n0}", values[i], values[i + 1], fun(values[i], values[i + 1])); Console.WriteLine("Took {0} seconds\n", DateTime.Now - start); } static void Main() { doOne("java simple", js); doOne("go integer", gi); doOne("pascal alternative", pa); } }
p=: adverb define : el =. x en =. y pwr =. m el =. <. | el digitcount =. <. 10 ^. el log10pwr =. 10 ^. pwr 'raised found' =. _1 0 while. found < en do. raised =. >: raised firstdigits =. (<.!.0) 10^digitcount + 1 | log10pwr * raised found =. found + firstdigits = el end. raised )
Generate a J translation of this C# snippet without changing its computational steps.
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 long gi(int ld, int n) { string Ls = ld.ToString(); long res = 0, count = 0, f = 1; for (int i = 1; i <= 18 - Ls.Length; i++) f *= 10; const long ten18 = (long)1e18; long probe = 1; do { probe <<= 1; res++; if (probe >= ten18) do { if (probe >= ten18) probe /= 10; if (probe / f == ld) if (++count >= n) { count--; break; } probe <<= 1; res++; } while (true); string ps = probe.ToString(); if (ps.Substring(0, Math.Min(Ls.Length, ps.Length)) == Ls) if (++count >= n) break; } while (true); return res; } static long pa(int ld, int n) { double L_float64 = Math.Pow(2, 64); ulong Log10_2_64 = (ulong)(L_float64 * Math.Log10(2)); double Log10Num; ulong LmtUpper, LmtLower, Frac64; long res = 0, dgts = 1, cnt; for (int i = ld; i >= 10; i /= 10) dgts *= 10; Log10Num = Math.Log10((ld + 1.0) / dgts); if (Log10Num >= 0.5) { LmtUpper = (ld + 1.0) / dgts < 10.0 ? (ulong)(Log10Num * (L_float64 * 0.5)) * 2 + (ulong)(Log10Num * 2) : 0; Log10Num = Math.Log10((double)ld / dgts); LmtLower = (ulong)(Log10Num * (L_float64 * 0.5)) * 2 + (ulong)(Log10Num * 2); } else { LmtUpper = (ulong)(Log10Num * L_float64); LmtLower = (ulong)(Math.Log10((double)ld / dgts) * L_float64); } cnt = 0; Frac64 = 0; if (LmtUpper != 0) do { res++; Frac64 += Log10_2_64; if ((Frac64 >= LmtLower) & (Frac64 < LmtUpper)) if (++cnt >= n) break; } while (true); else do { res++; Frac64 += Log10_2_64; if (Frac64 >= LmtLower) if (++cnt >= n) break; } while (true); return res; } static int[] values = new int[] { 12, 1, 12, 2, 123, 45, 123, 12345, 123, 678910, 99, 1 }; static void doOne(string name, Func<int, int, long> fun) { Console.WriteLine("{0} version:", name); var start = DateTime.Now; for (int i = 0; i < values.Length; i += 2) Console.WriteLine("p({0,3}, {1,6}) = {2,11:n0}", values[i], values[i + 1], fun(values[i], values[i + 1])); Console.WriteLine("Took {0} seconds\n", DateTime.Now - start); } static void Main() { doOne("java simple", js); doOne("go integer", gi); doOne("pascal alternative", pa); } }
p=: adverb define : el =. x en =. y pwr =. m el =. <. | el digitcount =. <. 10 ^. el log10pwr =. 10 ^. pwr 'raised found' =. _1 0 while. found < en do. raised =. >: raised firstdigits =. (<.!.0) 10^digitcount + 1 | log10pwr * raised found =. found + firstdigits = el end. raised )
Translate the given C# code snippet into J without altering its behavior.
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 = ps.Length > 0 ? BigInteger.Parse(ps) : BIG; BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p); if (ls(n) != 1) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } BigInteger a = 0; BigInteger omega2; while (true) { omega2 = (a * a + p - n) % p; if (ls(omega2) == p - 1) { break; } a += 1; } BigInteger finalOmega = omega2; Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) { return new Tuple<BigInteger, BigInteger>( (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p ); } Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0); Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1); BigInteger nn = ((p + 1) >> 1) % p; while (nn > 0) { if ((nn & 1) == 1) { r = mul(r, s); } s = mul(s, s); nn >>= 1; } if (r.Item2 != 0) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } if (r.Item1 * r.Item1 % p != n) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true); } static void Main(string[] args) { Console.WriteLine(C("10", "13")); Console.WriteLine(C("56", "101")); Console.WriteLine(C("8218", "10007")); Console.WriteLine(C("8219", "10007")); Console.WriteLine(C("331575", "1000003")); Console.WriteLine(C("665165880", "1000000007")); Console.WriteLine(C("881398088036", "1000000000039")); Console.WriteLine(C("34035243914635549601583369544560650254325084643201", "")); } } }
leg=: dyad define x (y&|)@^ (y-1)%2 ) mul2=: conjunction define m| (*&{. + n**&{:), (+/ .* |.) ) pow2=: conjunction define : if. 0=y do. 1 0 elseif. 1=y do. x elseif. 2=y do. x (m mul2 n) x elseif. 0=2|y do. (m mul2 n)~ x (m pow2 n) y%2 elseif. do. x (m mul2 n) x (m pow2 n) y-1 end. ) cipolla=: dyad define assert. 1=1 p: y [ 'y must be prime' assert. 1= x leg y [ 'x must be square mod y' a=.1 whilst. (0 ~:{: r) do. a=. a+1 while. 1>: leg&y@(x -~ *:) a do. a=.a+1 end. w2=. y|(*:a) - x r=. (a,1) (y pow2 w2) (y+1)%2 end. if. x =&(y&|) *:{.r do. y|(,-){.r else. smoutput 'got ',":~.y|(,-){.r assert. 'not a valid square root' end. )
Maintain the same structure and functionality when rewriting this code in J.
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 = ps.Length > 0 ? BigInteger.Parse(ps) : BIG; BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p); if (ls(n) != 1) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } BigInteger a = 0; BigInteger omega2; while (true) { omega2 = (a * a + p - n) % p; if (ls(omega2) == p - 1) { break; } a += 1; } BigInteger finalOmega = omega2; Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) { return new Tuple<BigInteger, BigInteger>( (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p ); } Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0); Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1); BigInteger nn = ((p + 1) >> 1) % p; while (nn > 0) { if ((nn & 1) == 1) { r = mul(r, s); } s = mul(s, s); nn >>= 1; } if (r.Item2 != 0) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } if (r.Item1 * r.Item1 % p != n) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true); } static void Main(string[] args) { Console.WriteLine(C("10", "13")); Console.WriteLine(C("56", "101")); Console.WriteLine(C("8218", "10007")); Console.WriteLine(C("8219", "10007")); Console.WriteLine(C("331575", "1000003")); Console.WriteLine(C("665165880", "1000000007")); Console.WriteLine(C("881398088036", "1000000000039")); Console.WriteLine(C("34035243914635549601583369544560650254325084643201", "")); } } }
leg=: dyad define x (y&|)@^ (y-1)%2 ) mul2=: conjunction define m| (*&{. + n**&{:), (+/ .* |.) ) pow2=: conjunction define : if. 0=y do. 1 0 elseif. 1=y do. x elseif. 2=y do. x (m mul2 n) x elseif. 0=2|y do. (m mul2 n)~ x (m pow2 n) y%2 elseif. do. x (m mul2 n) x (m pow2 n) y-1 end. ) cipolla=: dyad define assert. 1=1 p: y [ 'y must be prime' assert. 1= x leg y [ 'x must be square mod y' a=.1 whilst. (0 ~:{: r) do. a=. a+1 while. 1>: leg&y@(x -~ *:) a do. a=.a+1 end. w2=. y|(*:a) - x r=. (a,1) (y pow2 w2) (y+1)%2 end. if. x =&(y&|) *:{.r do. y|(,-){.r else. smoutput 'got ',":~.y|(,-){.r assert. 'not a valid square root' end. )
Generate an equivalent J version of this C# code.
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, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, }; public static BigInteger GetRandom(BigInteger min, BigInteger max) { var bytes = max.ToByteArray(); BigInteger r; do { rand.NextBytes(bytes); bytes[bytes.Length - 1] &= (byte)0x7F; r = new BigInteger(bytes); } while (r < min || r >= max); return r; } public static bool IsProbablePrime(this BigInteger n) { if (n == 0 || n == 1) { return false; } bool Check(BigInteger num) { foreach (var prime in primeList) { if (num == prime) { return true; } if (num % prime == 0) { return false; } if (prime * prime > num) { return true; } } return true; } if (Check(n)) { var large = primeList[primeList.Count - 1]; if (n <= large) { return true; } } var s = 0; var d = n - 1; while (d.IsEven) { d >>= 1; s++; } bool TrialComposite(BigInteger a) { if (BigInteger.ModPow(a, d, n) == 1) { return false; } for (int i = 0; i < s; i++) { var t = BigInteger.Pow(2, i); if (BigInteger.ModPow(a, t * d, n) == n - 1) { return false; } } return true; } for (int i = 0; i < 8; i++) { var a = GetRandom(2, n); if (TrialComposite(a)) { return false; } } return true; } } class Program { static List<List<BigInteger>> Pierpont(int n) { var p = new List<List<BigInteger>> { new List<BigInteger>(), new List<BigInteger>() }; for (int i = 0; i < n; i++) { p[0].Add(0); p[1].Add(0); } p[0][0] = 2; var count = 0; var count1 = 1; var count2 = 0; List<BigInteger> s = new List<BigInteger> { 1 }; var i2 = 0; var i3 = 0; var k = 1; BigInteger n2; BigInteger n3; BigInteger t; while (count < n) { n2 = s[i2] * 2; n3 = s[i3] * 3; if (n2 < n3) { t = n2; i2++; } else { t = n3; i3++; } if (t > s[k - 1]) { s.Add(t); k++; t += 1; if (count1 < n && t.IsProbablePrime()) { p[0][count1] = t; count1++; } t -= 2; if (count2 < n && t.IsProbablePrime()) { p[1][count2] = t; count2++; } count = Math.Min(count1, count2); } } return p; } static void Main() { var p = Pierpont(250); Console.WriteLine("First 50 Pierpont primes of the first kind:"); for (int i = 0; i < 50; i++) { Console.Write("{0,8} ", p[0][i]); if ((i - 9) % 10 == 0) { Console.WriteLine(); } } Console.WriteLine(); Console.WriteLine("First 50 Pierpont primes of the second kind:"); for (int i = 0; i < 50; i++) { Console.Write("{0,8} ", p[1][i]); if ((i - 9) % 10 == 0) { Console.WriteLine(); } } Console.WriteLine(); Console.WriteLine("250th Pierpont prime of the first kind: {0}", p[0][249]); Console.WriteLine("250th Pierpont prime of the second kind: {0}", p[1][249]); Console.WriteLine(); } } }
5 10$(#~ 1 p:])1+/:~,*//2 3x^/i.20 2 3 5 7 13 17 19 37 73 97 109 163 193 257 433 487 577 769 1153 1297 1459 2593 2917 3457 3889 10369 12289 17497 18433 39367 52489 65537 139969 147457 209953 331777 472393 629857 746497 786433 839809 995329 1179649 1492993 1769473 1990657 2654209 5038849 5308417 8503057 5 10$(#~ 1 p:])_1+/:~,*//2 3x^/i.20 2 3 5 7 11 17 23 31 47 53 71 107 127 191 383 431 647 863 971 1151 2591 4373 6143 6911 8191 8747 13121 15551 23327 27647 62207 73727 131071 139967 165887 294911 314927 442367 472391 497663 524287 786431 995327 1062881 2519423 10616831 17915903 25509167 30233087 57395627
Translate this program into J but keep the logic exactly as in C#.
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(2); smallPrimes.Add(2); BigInteger i = 3; while (i <= 521) { if (IsPrime(i)) { primes.Add(i); if (i <= 29) { smallPrimes.Add((int)i); } } i += 2; } } static bool IsPrime(BigInteger value) { if (value < 2) return false; if (value % 2 == 0) return value == 2; if (value % 3 == 0) return value == 3; if (value % 5 == 0) return value == 5; if (value % 7 == 0) return value == 7; if (value % 11 == 0) return value == 11; if (value % 13 == 0) return value == 13; if (value % 17 == 0) return value == 17; if (value % 19 == 0) return value == 19; if (value % 23 == 0) return value == 23; BigInteger t = 29; while (t * t < value) { if (value % t == 0) return false; value += 2; if (value % t == 0) return false; value += 4; } return true; } static List<BigInteger> NSmooth(int n, int size) { if (n < 2 || n > 521) { throw new ArgumentOutOfRangeException("n"); } if (size < 1) { throw new ArgumentOutOfRangeException("size"); } BigInteger bn = n; bool ok = false; foreach (var prime in primes) { if (bn == prime) { ok = true; break; } } if (!ok) { throw new ArgumentException("must be a prime number", "n"); } BigInteger[] ns = new BigInteger[size]; ns[0] = 1; for (int i = 1; i < size; i++) { ns[i] = 0; } List<BigInteger> next = new List<BigInteger>(); foreach (var prime in primes) { if (prime > bn) { break; } next.Add(prime); } int[] indices = new int[next.Count]; for (int i = 0; i < indices.Length; i++) { indices[i] = 0; } for (int m = 1; m < size; m++) { ns[m] = next.Min(); for (int i = 0; i < indices.Length; i++) { if (ns[m] == next[i]) { indices[i]++; next[i] = primes[i] * ns[indices[i]]; } } } return ns.ToList(); } static void Println<T>(IEnumerable<T> nums) { Console.Write('['); var it = nums.GetEnumerator(); if (it.MoveNext()) { Console.Write(it.Current); } while (it.MoveNext()) { Console.Write(", "); Console.Write(it.Current); } Console.WriteLine(']'); } static void Main() { foreach (var i in smallPrimes) { Console.WriteLine("The first {0}-smooth numbers are:", i); Println(NSmooth(i, 25)); Console.WriteLine(); } foreach (var i in smallPrimes.Skip(1)) { Console.WriteLine("The 3,000 to 3,202 {0}-smooth numbers are:", i); Println(NSmooth(i, 3_002).Skip(2_999)); Console.WriteLine(); } foreach (var i in new int[] { 503, 509, 521 }) { Console.WriteLine("The 30,000 to 3,019 {0}-smooth numbers are:", i); Println(NSmooth(i, 30_019).Skip(29_999)); Console.WriteLine(); } } } }
nsmooth=: dyad define factors=. x: i.@:>:&.:(p:inv) y smoothies=. , 1x result=. , i. 0x while. x > # result do. mn =. {. smoothies smoothies =. ({.~ (x <. #)) ~. /:~ (}. smoothies) , mn * factors result=. result , mn end. )
Generate an equivalent J 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, 24), (22699, 1), (22699, 2), (22699, 3), (22699, 4), (40355, 3) }) { Console.WriteLine(Partition(x, n)); } } public static string Partition(int x, int n) { if (x < 1 || n < 1) throw new ArgumentOutOfRangeException("Parameters must be positive."); string header = $"{x} with {n} {(n == 1Β ? "prime"Β : "primes")}: "; int[] primes = SievePrimes(x).ToArray(); if (primes.Length < n) return header + "not enough primes"; int[] solution = CombinationsOf(n, primes).FirstOrDefault(c => c.Sum() == x); return header + (solution == null ? "not possible" : string.Join("+", solution); } static IEnumerable<int> SievePrimes(int bound) { if (bound < 2) yield break; yield return 2; BitArray composite = new BitArray((bound - 1) / 2); int limit = ((int)(Math.Sqrt(bound)) - 1) / 2; for (int i = 0; i < limit; i++) { if (composite[i]) continue; int prime = 2 * i + 3; yield return prime; for (int j = (prime * prime - 2) / 2; j < composite.Count; j += prime) composite[j] = true; } for (int i = limit; i < composite.Count; i++) { if (!composite[i]) yield return 2 * i + 3; } } static IEnumerable<int[]> CombinationsOf(int count, int[] input) { T[] result = new T[count]; foreach (int[] indices in Combinations(input.Length, count)) { for (int i = 0; i < count; i++) result[i] = input[indices[i]]; yield return result; } } static IEnumerable<int[]> Combinations(int n, int k) { var result = new int[k]; var stack = new Stack<int>(); stack.Push(0); while (stack.Count > 0) { int index = stack.Count - 1; int value = stack.Pop(); while (value < n) { result[index++] = value++; stack.Push(value); if (index == k) { yield return result; break; } } } } }
load 'format/printf' primes_up_to =: monad def 'p: i. _1 p: 1 + y' terms_as_text =: monad def '; }: , (": each y),.<'' + ''' search_next_terms =: dyad define acc=. x p=. >0{y ns=. >1{y sum=. >2{y if. p=0 do. if. sum=+/acc do. acc return. end. else. for_m. i. (#ns)-(p-1) do. r =. (acc,m{ns) search_next_terms (p-1);((m+1)}.ns);sum if. #r do. r return. end. end. end. 0$0 ) partitioned_in =: dyad define terms =. (0$0) search_next_terms y;(primes_up_to x);x if. #terms do. 'As the sum of %d primes, %d = %s' printf y;x; terms_as_text terms else. 'Didn''t find a way to express %d as a sum of %d different primes.' printf x;y end. ) tests=: (99809 1) ; (18 2) ; (19 3) ; (20 4) ; (2017 24) ; (22699 1) ; (22699 2) ; (22699 3) ; (22699 4) (0&{ partitioned_in 1&{) each tests
Change the following C# code into J without altering its purpose.
using System; using System.Text; namespace ZeckendorfArithmetic { class Zeckendorf : IComparable<Zeckendorf> { private static readonly string[] dig = { "00", "01", "10" }; private static readonly string[] dig1 = { "", "1", "10" }; private int dVal = 0; private int dLen = 0; public Zeckendorf() : this("0") { } public Zeckendorf(string x) { int q = 1; int i = x.Length - 1; dLen = i / 2; while (i >= 0) { dVal += (x[i] - '0') * q; q *= 2; i--; } } private void A(int n) { int i = n; while (true) { if (dLen < i) dLen = i; int j = (dVal >> (i * 2)) & 3; switch (j) { case 0: case 1: return; case 2: if (((dVal >> ((i + 1) * 2)) & 1) != 1) return; dVal += 1 << (i * 2 + 1); return; case 3: int temp = 3 << (i * 2); temp ^= -1; dVal = dVal & temp; B((i + 1) * 2); break; } i++; } } private void B(int pos) { if (pos == 0) { Inc(); return; } if (((dVal >> pos) & 1) == 0) { dVal += 1 << pos; A(pos / 2); if (pos > 1) A(pos / 2 - 1); } else { int temp = 1 << pos; temp ^= -1; dVal = dVal & temp; B(pos + 1); B(pos - (pos > 1 ? 2 : 1)); } } private void C(int pos) { if (((dVal >> pos) & 1) == 1) { int temp = 1 << pos; temp ^= -1; dVal = dVal & temp; return; } C(pos + 1); if (pos > 0) { B(pos - 1); } else { Inc(); } } public Zeckendorf Inc() { dVal++; A(0); return this; } public Zeckendorf Copy() { Zeckendorf z = new Zeckendorf { dVal = dVal, dLen = dLen }; return z; } public void PlusAssign(Zeckendorf other) { for (int gn = 0; gn < (other.dLen + 1) * 2; gn++) { if (((other.dVal >> gn) & 1) == 1) { B(gn); } } } public void MinusAssign(Zeckendorf other) { for (int gn = 0; gn < (other.dLen + 1) * 2; gn++) { if (((other.dVal >> gn) & 1) == 1) { C(gn); } } while ((((dVal >> dLen * 2) & 3) == 0) || (dLen == 0)) { dLen--; } } public void TimesAssign(Zeckendorf other) { Zeckendorf na = other.Copy(); Zeckendorf nb = other.Copy(); Zeckendorf nt; Zeckendorf nr = new Zeckendorf(); for (int i = 0; i < (dLen + 1) * 2; i++) { if (((dVal >> i) & 1) > 0) { nr.PlusAssign(nb); } nt = nb.Copy(); nb.PlusAssign(na); na = nt.Copy(); } dVal = nr.dVal; dLen = nr.dLen; } public int CompareTo(Zeckendorf other) { return dVal.CompareTo(other.dVal); } public override string ToString() { if (dVal == 0) { return "0"; } int idx = (dVal >> (dLen * 2)) & 3; StringBuilder sb = new StringBuilder(dig1[idx]); for (int i = dLen - 1; i >= 0; i--) { idx = (dVal >> (i * 2)) & 3; sb.Append(dig[idx]); } return sb.ToString(); } } class Program { static void Main(string[] args) { Console.WriteLine("Addition:"); Zeckendorf g = new Zeckendorf("10"); g.PlusAssign(new Zeckendorf("10")); Console.WriteLine(g); g.PlusAssign(new Zeckendorf("10")); Console.WriteLine(g); g.PlusAssign(new Zeckendorf("1001")); Console.WriteLine(g); g.PlusAssign(new Zeckendorf("1000")); Console.WriteLine(g); g.PlusAssign(new Zeckendorf("10101")); Console.WriteLine(g); Console.WriteLine(); Console.WriteLine("Subtraction:"); g = new Zeckendorf("1000"); g.MinusAssign(new Zeckendorf("101")); Console.WriteLine(g); g = new Zeckendorf("10101010"); g.MinusAssign(new Zeckendorf("1010101")); Console.WriteLine(g); Console.WriteLine(); Console.WriteLine("Multiplication:"); g = new Zeckendorf("1001"); g.TimesAssign(new Zeckendorf("101")); Console.WriteLine(g); g = new Zeckendorf("101010"); g.PlusAssign(new Zeckendorf("101")); Console.WriteLine(g); } } }
zform=: {{ 10 |."1@(#.inv) y }} :. (10#.|."1) zinc=: {{ carry ({.,2}.])carry 1,y }} zdec=: {{ (|.k$0 1),y }.~k=. 1+y i.1 }} zadd=: {{ x while. 1 e. y do. x=. zinc x [ y=. zdec y end. }} zsub=: {{ x while. 1 e. y do. x=. zdec x [ y=. zdec y end. }} zmul=: {{ t=. 0 0 while. 1 e. y do. t=. t zadd x [ y=. zdec y end. }} zdiv=: {{ t=. 0 0 while. x zge y do. t=. zinc t [ x=. x zsub y end. }} carry=: {{ s=. 0 for_b. y do. if. (1+b) = s=. s-_1^b do. y=. (-.b) (b_index-0,b)} y end. end. if. 2=s do. y,1 else. y end. }} zge=: {{ cmp=. x -/@,: y while. (#cmp)*0={:cmp do. cmp=. }:cmp end. 0<:{:cmp }}
Translate this program into J but keep the logic exactly as in C#.
using System; using System.Collections.Generic; using System.Linq; namespace LineSimplification { using Point = Tuple<double, double>; class Program { static double PerpendicularDistance(Point pt, Point lineStart, Point lineEnd) { double dx = lineEnd.Item1 - lineStart.Item1; double dy = lineEnd.Item2 - lineStart.Item2; double mag = Math.Sqrt(dx * dx + dy * dy); if (mag > 0.0) { dx /= mag; dy /= mag; } double pvx = pt.Item1 - lineStart.Item1; double pvy = pt.Item2 - lineStart.Item2; double pvdot = dx * pvx + dy * pvy; double ax = pvx - pvdot * dx; double ay = pvy - pvdot * dy; return Math.Sqrt(ax * ax + ay * ay); } static void RamerDouglasPeucker(List<Point> pointList, double epsilon, List<Point> output) { if (pointList.Count < 2) { throw new ArgumentOutOfRangeException("Not enough points to simplify"); } double dmax = 0.0; int index = 0; int end = pointList.Count - 1; for (int i = 1; i < end; ++i) { double d = PerpendicularDistance(pointList[i], pointList[0], pointList[end]); if (d > dmax) { index = i; dmax = d; } } if (dmax > epsilon) { List<Point> recResults1 = new List<Point>(); List<Point> recResults2 = new List<Point>(); List<Point> firstLine = pointList.Take(index + 1).ToList(); List<Point> lastLine = pointList.Skip(index).ToList(); RamerDouglasPeucker(firstLine, epsilon, recResults1); RamerDouglasPeucker(lastLine, epsilon, recResults2); output.AddRange(recResults1.Take(recResults1.Count - 1)); output.AddRange(recResults2); if (output.Count < 2) throw new Exception("Problem assembling output"); } else { output.Clear(); output.Add(pointList[0]); output.Add(pointList[pointList.Count - 1]); } } static void Main(string[] args) { List<Point> pointList = new List<Point>() { new Point(0.0,0.0), new Point(1.0,0.1), new Point(2.0,-0.1), new Point(3.0,5.0), new Point(4.0,6.0), new Point(5.0,7.0), new Point(6.0,8.1), new Point(7.0,9.0), new Point(8.0,9.0), new Point(9.0,9.0), }; List<Point> pointListOut = new List<Point>(); RamerDouglasPeucker(pointList, 1.0, pointListOut); Console.WriteLine("Points remaining after simplification:"); pointListOut.ForEach(p => Console.WriteLine(p)); } } }
mp=: +/ .* norm=: +/&.:*: normalize=: (% norm)^:(0 < norm) dxy=. normalize@({: - {.) pv=. -"1 {. perpDist=: norm"1@(pv ([ -"1 mp"1~ */ ]) dxy) f. rdp=: verb define 1 rdp y : points=. ,:^:(2 > #@$) y epsilon=. x if. 2 > # points do. points return. end. 'imax dmax'=. ((i. , ]) >./) perpDist points if. dmax > epsilon do. epsilon ((}:@rdp (1+imax)&{.) , (rdp imax&}.)) points else. ({. ,: {:) points end. )
Produce a functionally identical J code for the snippet given in C#.
using System; using System.Collections.Generic; using System.Linq; namespace LineSimplification { using Point = Tuple<double, double>; class Program { static double PerpendicularDistance(Point pt, Point lineStart, Point lineEnd) { double dx = lineEnd.Item1 - lineStart.Item1; double dy = lineEnd.Item2 - lineStart.Item2; double mag = Math.Sqrt(dx * dx + dy * dy); if (mag > 0.0) { dx /= mag; dy /= mag; } double pvx = pt.Item1 - lineStart.Item1; double pvy = pt.Item2 - lineStart.Item2; double pvdot = dx * pvx + dy * pvy; double ax = pvx - pvdot * dx; double ay = pvy - pvdot * dy; return Math.Sqrt(ax * ax + ay * ay); } static void RamerDouglasPeucker(List<Point> pointList, double epsilon, List<Point> output) { if (pointList.Count < 2) { throw new ArgumentOutOfRangeException("Not enough points to simplify"); } double dmax = 0.0; int index = 0; int end = pointList.Count - 1; for (int i = 1; i < end; ++i) { double d = PerpendicularDistance(pointList[i], pointList[0], pointList[end]); if (d > dmax) { index = i; dmax = d; } } if (dmax > epsilon) { List<Point> recResults1 = new List<Point>(); List<Point> recResults2 = new List<Point>(); List<Point> firstLine = pointList.Take(index + 1).ToList(); List<Point> lastLine = pointList.Skip(index).ToList(); RamerDouglasPeucker(firstLine, epsilon, recResults1); RamerDouglasPeucker(lastLine, epsilon, recResults2); output.AddRange(recResults1.Take(recResults1.Count - 1)); output.AddRange(recResults2); if (output.Count < 2) throw new Exception("Problem assembling output"); } else { output.Clear(); output.Add(pointList[0]); output.Add(pointList[pointList.Count - 1]); } } static void Main(string[] args) { List<Point> pointList = new List<Point>() { new Point(0.0,0.0), new Point(1.0,0.1), new Point(2.0,-0.1), new Point(3.0,5.0), new Point(4.0,6.0), new Point(5.0,7.0), new Point(6.0,8.1), new Point(7.0,9.0), new Point(8.0,9.0), new Point(9.0,9.0), }; List<Point> pointListOut = new List<Point>(); RamerDouglasPeucker(pointList, 1.0, pointListOut); Console.WriteLine("Points remaining after simplification:"); pointListOut.ForEach(p => Console.WriteLine(p)); } } }
mp=: +/ .* norm=: +/&.:*: normalize=: (% norm)^:(0 < norm) dxy=. normalize@({: - {.) pv=. -"1 {. perpDist=: norm"1@(pv ([ -"1 mp"1~ */ ]) dxy) f. rdp=: verb define 1 rdp y : points=. ,:^:(2 > #@$) y epsilon=. x if. 2 > # points do. points return. end. 'imax dmax'=. ((i. , ]) >./) perpDist points if. dmax > epsilon do. epsilon ((}:@rdp (1+imax)&{.) , (rdp imax&}.)) points else. ({. ,: {:) points end. )
Generate a J translation of this C# snippet without changing its computational steps.
using System; using System.Drawing; namespace BilinearInterpolation { class Program { private static float Lerp(float s, float e, float t) { return s + (e - s) * t; } private static float Blerp(float c00, float c10, float c01, float c11, float tx, float ty) { return Lerp(Lerp(c00, c10, tx), Lerp(c01, c11, tx), ty); } private static Image Scale(Bitmap self, float scaleX, float scaleY) { int newWidth = (int)(self.Width * scaleX); int newHeight = (int)(self.Height * scaleY); Bitmap newImage = new Bitmap(newWidth, newHeight, self.PixelFormat); for (int x = 0; x < newWidth; x++) { for (int y = 0; y < newHeight; y++) { float gx = ((float)x) / newWidth * (self.Width - 1); float gy = ((float)y) / newHeight * (self.Height - 1); int gxi = (int)gx; int gyi = (int)gy; Color c00 = self.GetPixel(gxi, gyi); Color c10 = self.GetPixel(gxi + 1, gyi); Color c01 = self.GetPixel(gxi, gyi + 1); Color c11 = self.GetPixel(gxi + 1, gyi + 1); int red = (int)Blerp(c00.R, c10.R, c01.R, c11.R, gx - gxi, gy - gyi); int green = (int)Blerp(c00.G, c10.G, c01.G, c11.G, gx - gxi, gy - gyi); int blue = (int)Blerp(c00.B, c10.B, c01.B, c11.B, gx - gxi, gy - gyi); Color rgb = Color.FromArgb(red, green, blue); newImage.SetPixel(x, y, rgb); } } return newImage; } static void Main(string[] args) { Image newImage = Image.FromFile("Lenna100.jpg"); if (newImage is Bitmap oi) { Image result = Scale(oi, 1.6f, 1.6f); result.Save("Lenna100_larger.jpg"); } else { Console.WriteLine("Could not open the source file."); } } } }
Note 'FEA' Here we develop a general method to generate isoparametric interpolants. The interpolant is the dot product of the four shape function values evaluated at the coordinates within the element with the known values at the nodes. The sum of four shape functions of two variables (xi, eta) is 1 at each of four nodes. Let the base element have nodal coordinates (xi, eta) of +/-1. 2 3 (1,1) +---------------+ | | | | | (0,0) | | * | | | | | | | +---------------+ 0 1 determine f0(xi,eta), ..., f3(xi,eta). f0(-1,-1) = 1, f0(all other corners) is 0. f1( 1,-1) = 1, f1(all other corners) is 0. ... Choose a shape function. Use shape functions C0 + C1*xi + C2*eta + C3*xi*eta . Given (xi,eta) as the vector y form a vector of the coefficients of the constants (1, xi, eta, and their product) shape_function =: 1 , {. , {: , */ CORNERS _1 _1 1 _1 _1 1 1 1 (=i.4) 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 (=i.4x) %. shape_function"1 x: CORNERS 1r4 1r4 1r4 1r4 _1r4 1r4 _1r4 1r4 _1r4 _1r4 1r4 1r4 1r4 _1r4 _1r4 1r4 This method extends to higher order interpolants having more nodes or to other dimensions. ) mp =: +/ .* CORNERS =: 21 A.-.+:#:i.4 shape_function =: 1 , ] , */ COEFFICIENTS =: (=i.4) %. shape_function"1 CORNERS shape_functions =: COEFFICIENTS mp~ shape_function interpolate =: mp shape_functions
Translate the given C# code snippet into J without altering its behavior.
using System; using System.Drawing; namespace BilinearInterpolation { class Program { private static float Lerp(float s, float e, float t) { return s + (e - s) * t; } private static float Blerp(float c00, float c10, float c01, float c11, float tx, float ty) { return Lerp(Lerp(c00, c10, tx), Lerp(c01, c11, tx), ty); } private static Image Scale(Bitmap self, float scaleX, float scaleY) { int newWidth = (int)(self.Width * scaleX); int newHeight = (int)(self.Height * scaleY); Bitmap newImage = new Bitmap(newWidth, newHeight, self.PixelFormat); for (int x = 0; x < newWidth; x++) { for (int y = 0; y < newHeight; y++) { float gx = ((float)x) / newWidth * (self.Width - 1); float gy = ((float)y) / newHeight * (self.Height - 1); int gxi = (int)gx; int gyi = (int)gy; Color c00 = self.GetPixel(gxi, gyi); Color c10 = self.GetPixel(gxi + 1, gyi); Color c01 = self.GetPixel(gxi, gyi + 1); Color c11 = self.GetPixel(gxi + 1, gyi + 1); int red = (int)Blerp(c00.R, c10.R, c01.R, c11.R, gx - gxi, gy - gyi); int green = (int)Blerp(c00.G, c10.G, c01.G, c11.G, gx - gxi, gy - gyi); int blue = (int)Blerp(c00.B, c10.B, c01.B, c11.B, gx - gxi, gy - gyi); Color rgb = Color.FromArgb(red, green, blue); newImage.SetPixel(x, y, rgb); } } return newImage; } static void Main(string[] args) { Image newImage = Image.FromFile("Lenna100.jpg"); if (newImage is Bitmap oi) { Image result = Scale(oi, 1.6f, 1.6f); result.Save("Lenna100_larger.jpg"); } else { Console.WriteLine("Could not open the source file."); } } } }
Note 'FEA' Here we develop a general method to generate isoparametric interpolants. The interpolant is the dot product of the four shape function values evaluated at the coordinates within the element with the known values at the nodes. The sum of four shape functions of two variables (xi, eta) is 1 at each of four nodes. Let the base element have nodal coordinates (xi, eta) of +/-1. 2 3 (1,1) +---------------+ | | | | | (0,0) | | * | | | | | | | +---------------+ 0 1 determine f0(xi,eta), ..., f3(xi,eta). f0(-1,-1) = 1, f0(all other corners) is 0. f1( 1,-1) = 1, f1(all other corners) is 0. ... Choose a shape function. Use shape functions C0 + C1*xi + C2*eta + C3*xi*eta . Given (xi,eta) as the vector y form a vector of the coefficients of the constants (1, xi, eta, and their product) shape_function =: 1 , {. , {: , */ CORNERS _1 _1 1 _1 _1 1 1 1 (=i.4) 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 (=i.4x) %. shape_function"1 x: CORNERS 1r4 1r4 1r4 1r4 _1r4 1r4 _1r4 1r4 _1r4 _1r4 1r4 1r4 1r4 _1r4 _1r4 1r4 This method extends to higher order interpolants having more nodes or to other dimensions. ) mp =: +/ .* CORNERS =: 21 A.-.+:#:i.4 shape_function =: 1 , ] , */ COEFFICIENTS =: (=i.4) %. shape_function"1 CORNERS shape_functions =: COEFFICIENTS mp~ shape_function interpolate =: mp shape_functions
Change the following C# code into J without altering its purpose.
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) { store = new double[] { x, y }; } static public Vector operator+(Vector v1, Vector v2) { return new Vector(v1.store.Zip(v2.store, (a, b) => a + b)); } static public Vector operator -(Vector v1, Vector v2) { return new Vector(v1.store.Zip(v2.store, (a, b) => a - b)); } static public Vector operator *(Vector v1, double scalar) { return new Vector(v1.store.Select(x => x * scalar)); } static public Vector operator /(Vector v1, double scalar) { return new Vector(v1.store.Select(x => x / scalar)); } public override string ToString() { return string.Format("[{0}]", string.Join(",", store)); } } class Program { static void Main(string[] args) { var v1 = new Vector(5, 7); var v2 = new Vector(2, 3); Console.WriteLine(v1 + v2); Console.WriteLine(v1 - v2); Console.WriteLine(v1 * 11); Console.WriteLine(v1 / 2); var lostVector = new Vector(new double[] { 4, 8, 15, 16, 23, 42 }); Console.WriteLine(lostVector * 7); Console.ReadLine(); } } }
5 7+2 3 7 10 5 7-2 3 3 4 5 7*11 55 77 5 7%2 2.5 3.5
Generate an equivalent J version of this C# code.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chebyshev { class Program { struct ChebyshevApprox { public readonly List<double> coeffs; public readonly Tuple<double, double> domain; public ChebyshevApprox(Func<double, double> func, int n, Tuple<double, double> domain) { coeffs = ChebCoef(func, n, domain); this.domain = domain; } public double Call(double x) { return ChebEval(coeffs, domain, x); } } static double AffineRemap(Tuple<double, double> from, double x, Tuple<double, double> to) { return to.Item1 + (x - from.Item1) * (to.Item2 - to.Item1) / (from.Item2 - from.Item1); } static List<double> ChebCoef(List<double> fVals) { int n = fVals.Count; double theta = Math.PI / n; List<double> retval = new List<double>(); for (int i = 0; i < n; i++) { retval.Add(0.0); } for (int ii = 0; ii < n; ii++) { double f = fVals[ii] * 2.0 / n; double phi = (ii + 0.5) * theta; double c1 = Math.Cos(phi); double s1 = Math.Sin(phi); double c = 1.0; double s = 0.0; for (int j = 0; j < n; j++) { retval[j] += f * c; double cNext = c * c1 - s * s1; s = c * s1 + s * c1; c = cNext; } } return retval; } static List<double> ChebCoef(Func<double, double> func, int n, Tuple<double, double> domain) { double remap(double x) { return AffineRemap(new Tuple<double, double>(-1.0, 1.0), x, domain); } double theta = Math.PI / n; List<double> fVals = new List<double>(); for (int i = 0; i < n; i++) { fVals.Add(0.0); } for (int ii = 0; ii < n; ii++) { fVals[ii] = func(remap(Math.Cos((ii + 0.5) * theta))); } return ChebCoef(fVals); } static double ChebEval(List<double> coef, double x) { double a = 1.0; double b = x; double c; double retval = 0.5 * coef[0] + b * coef[1]; var it = coef.GetEnumerator(); it.MoveNext(); it.MoveNext(); while (it.MoveNext()) { double pc = it.Current; c = 2.0 * b * x - a; retval += pc * c; a = b; b = c; } return retval; } static double ChebEval(List<double> coef, Tuple<double, double> domain, double x) { return ChebEval(coef, AffineRemap(domain, x, new Tuple<double, double>(-1.0, 1.0))); } static void Main() { const int N = 10; ChebyshevApprox fApprox = new ChebyshevApprox(Math.Cos, N, new Tuple<double, double>(0.0, 1.0)); Console.WriteLine("Coefficients: "); foreach (var c in fApprox.coeffs) { Console.WriteLine("\t{0: 0.00000000000000;-0.00000000000000;zero}", c); } Console.WriteLine("\nApproximation:\n x func(x) approx diff"); const int nX = 20; const int min = 0; const int max = 1; for (int i = 0; i < nX; i++) { double x = AffineRemap(new Tuple<double, double>(0, nX), i, new Tuple<double, double>(min, max)); double f = Math.Cos(x); double approx = fApprox.Call(x); Console.WriteLine("{0:0.000} {1:0.00000000000000} {2:0.00000000000000} {3:E}", x, f, approx, approx - f); } } } }
chebft =: adverb define : f =. u 0.5 * (+/y) - (-/y) * 2 o. o. (0.5 + i. x) % x (2 % x) * +/ f * 2 o. o. (0.5 + i. x) *"0 1 (i. x) % x )
Please provide an equivalent version of this C# code in J.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chebyshev { class Program { struct ChebyshevApprox { public readonly List<double> coeffs; public readonly Tuple<double, double> domain; public ChebyshevApprox(Func<double, double> func, int n, Tuple<double, double> domain) { coeffs = ChebCoef(func, n, domain); this.domain = domain; } public double Call(double x) { return ChebEval(coeffs, domain, x); } } static double AffineRemap(Tuple<double, double> from, double x, Tuple<double, double> to) { return to.Item1 + (x - from.Item1) * (to.Item2 - to.Item1) / (from.Item2 - from.Item1); } static List<double> ChebCoef(List<double> fVals) { int n = fVals.Count; double theta = Math.PI / n; List<double> retval = new List<double>(); for (int i = 0; i < n; i++) { retval.Add(0.0); } for (int ii = 0; ii < n; ii++) { double f = fVals[ii] * 2.0 / n; double phi = (ii + 0.5) * theta; double c1 = Math.Cos(phi); double s1 = Math.Sin(phi); double c = 1.0; double s = 0.0; for (int j = 0; j < n; j++) { retval[j] += f * c; double cNext = c * c1 - s * s1; s = c * s1 + s * c1; c = cNext; } } return retval; } static List<double> ChebCoef(Func<double, double> func, int n, Tuple<double, double> domain) { double remap(double x) { return AffineRemap(new Tuple<double, double>(-1.0, 1.0), x, domain); } double theta = Math.PI / n; List<double> fVals = new List<double>(); for (int i = 0; i < n; i++) { fVals.Add(0.0); } for (int ii = 0; ii < n; ii++) { fVals[ii] = func(remap(Math.Cos((ii + 0.5) * theta))); } return ChebCoef(fVals); } static double ChebEval(List<double> coef, double x) { double a = 1.0; double b = x; double c; double retval = 0.5 * coef[0] + b * coef[1]; var it = coef.GetEnumerator(); it.MoveNext(); it.MoveNext(); while (it.MoveNext()) { double pc = it.Current; c = 2.0 * b * x - a; retval += pc * c; a = b; b = c; } return retval; } static double ChebEval(List<double> coef, Tuple<double, double> domain, double x) { return ChebEval(coef, AffineRemap(domain, x, new Tuple<double, double>(-1.0, 1.0))); } static void Main() { const int N = 10; ChebyshevApprox fApprox = new ChebyshevApprox(Math.Cos, N, new Tuple<double, double>(0.0, 1.0)); Console.WriteLine("Coefficients: "); foreach (var c in fApprox.coeffs) { Console.WriteLine("\t{0: 0.00000000000000;-0.00000000000000;zero}", c); } Console.WriteLine("\nApproximation:\n x func(x) approx diff"); const int nX = 20; const int min = 0; const int max = 1; for (int i = 0; i < nX; i++) { double x = AffineRemap(new Tuple<double, double>(0, nX), i, new Tuple<double, double>(min, max)); double f = Math.Cos(x); double approx = fApprox.Call(x); Console.WriteLine("{0:0.000} {1:0.00000000000000} {2:0.00000000000000} {3:E}", x, f, approx, approx - f); } } } }
chebft =: adverb define : f =. u 0.5 * (+/y) - (-/y) * 2 o. o. (0.5 + i. x) % x (2 % x) * +/ f * 2 o. o. (0.5 + i. x) *"0 1 (i. x) % x )
Produce a language-to-language conversion: from C# to J, same semantics.
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; --i) { a[i] = a[i - 1]; } a[0] = t; } private static int Compare(string s1, string s2) { for (int i = 0; i < s1.Length && i < s2.Length; ++i) { if (s1[i] < s2[i]) { return -1; } if (s2[i] < s1[i]) { return 1; } } if (s1.Length < s2.Length) { return -1; } if (s2.Length < s1.Length) { return 1; } return 0; } static string Bwt(string s) { if (s.Any(a => a == STX || a == ETX)) { throw new ArgumentException("Input can't contain STX or ETX"); } char[] ss = (STX + s + ETX).ToCharArray(); List<string> table = new List<string>(); for (int i = 0; i < ss.Length; ++i) { table.Add(new string(ss)); Rotate(ref ss); } table.Sort(Compare); return new string(table.Select(a => a.Last()).ToArray()); } static string Ibwt(string r) { int len = r.Length; List<string> table = new List<string>(new string[len]); for (int i = 0; i < len; ++i) { for (int j = 0; j < len; ++j) { table[j] = r[j] + table[j]; } table.Sort(Compare); } foreach (string row in table) { if (row.Last() == ETX) { return row.Substring(1, len - 2); } } return ""; } static string MakePrintable(string s) { return s.Replace(STX, '^').Replace(ETX, '|'); } static void Main() { string[] tests = new string[] { "banana", "appellee", "dogwood", "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", "\u0002ABC\u0003" }; foreach (string test in tests) { Console.WriteLine(MakePrintable(test)); Console.Write(" --> "); string t = ""; try { t = Bwt(test); Console.WriteLine(MakePrintable(t)); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e.Message); } string r = Ibwt(t); Console.WriteLine(" --> {0}", r); Console.WriteLine(); } } } }
bwt=:verb def '{:"1 /:~(|."0 1~i.@#) (8 u:y),{:a.' ibwt=: 1 (}.{:) (/:~@,.^:(#@]) 0#"0])
Generate a J translation of this C# snippet without changing its computational steps.
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; --i) { a[i] = a[i - 1]; } a[0] = t; } private static int Compare(string s1, string s2) { for (int i = 0; i < s1.Length && i < s2.Length; ++i) { if (s1[i] < s2[i]) { return -1; } if (s2[i] < s1[i]) { return 1; } } if (s1.Length < s2.Length) { return -1; } if (s2.Length < s1.Length) { return 1; } return 0; } static string Bwt(string s) { if (s.Any(a => a == STX || a == ETX)) { throw new ArgumentException("Input can't contain STX or ETX"); } char[] ss = (STX + s + ETX).ToCharArray(); List<string> table = new List<string>(); for (int i = 0; i < ss.Length; ++i) { table.Add(new string(ss)); Rotate(ref ss); } table.Sort(Compare); return new string(table.Select(a => a.Last()).ToArray()); } static string Ibwt(string r) { int len = r.Length; List<string> table = new List<string>(new string[len]); for (int i = 0; i < len; ++i) { for (int j = 0; j < len; ++j) { table[j] = r[j] + table[j]; } table.Sort(Compare); } foreach (string row in table) { if (row.Last() == ETX) { return row.Substring(1, len - 2); } } return ""; } static string MakePrintable(string s) { return s.Replace(STX, '^').Replace(ETX, '|'); } static void Main() { string[] tests = new string[] { "banana", "appellee", "dogwood", "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", "\u0002ABC\u0003" }; foreach (string test in tests) { Console.WriteLine(MakePrintable(test)); Console.Write(" --> "); string t = ""; try { t = Bwt(test); Console.WriteLine(MakePrintable(t)); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e.Message); } string r = Ibwt(t); Console.WriteLine(" --> {0}", r); Console.WriteLine(); } } } }
bwt=:verb def '{:"1 /:~(|."0 1~i.@#) (8 u:y),{:a.' ibwt=: 1 (}.{:) (/:~@,.^:(#@]) 0#"0])
Write the same algorithm in J as shown in this C# implementation.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CardShuffles { public static class Helper { public static string AsString<T>(this ICollection<T> c) { StringBuilder sb = new StringBuilder("["); sb.Append(string.Join(", ", c)); return sb.Append("]").ToString(); } } class Program { private static Random rand = new Random(); public static List<T> riffleShuffle<T>(ICollection<T> list, int flips) { List<T> newList = new List<T>(list); for (int n = 0; n < flips; n++) { int cutPoint = newList.Count / 2 + (rand.Next(0, 2) == 0 ? -1 : 1) * rand.Next((int)(newList.Count * 0.1)); List<T> left = new List<T>(newList.Take(cutPoint)); List<T> right = new List<T>(newList.Skip(cutPoint)); newList.Clear(); while (left.Count > 0 && right.Count > 0) { if (rand.NextDouble() >= ((double)left.Count / right.Count) / 2) { newList.Add(right.First()); right.RemoveAt(0); } else { newList.Add(left.First()); left.RemoveAt(0); } } if (left.Count > 0) newList.AddRange(left); if (right.Count > 0) newList.AddRange(right); } return newList; } public static List<T> overhandShuffle<T>(List<T> list, int passes) { List<T> mainHand = new List<T>(list); for (int n = 0; n < passes; n++) { List<T> otherHand = new List<T>(); while (mainHand.Count>0) { int cutSize = rand.Next((int)(list.Count * 0.2)) + 1; List<T> temp = new List<T>(); for (int i = 0; i < cutSize && mainHand.Count > 0; i++) { temp.Add(mainHand.First()); mainHand.RemoveAt(0); } if (rand.NextDouble()>=0.1) { temp.AddRange(otherHand); otherHand = temp; } else { otherHand.AddRange(temp); } } mainHand = otherHand; } return mainHand; } static void Main(string[] args) { List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; Console.WriteLine(list.AsString()); list = riffleShuffle(list, 10); Console.WriteLine(list.AsString()); Console.WriteLine(); list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; Console.WriteLine(list.AsString()); list = riffleShuffle(list, 1); Console.WriteLine(list.AsString()); Console.WriteLine(); list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; Console.WriteLine(list.AsString()); list = overhandShuffle(list, 10); Console.WriteLine(list.AsString()); Console.WriteLine(); list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; Console.WriteLine(list.AsString()); list = overhandShuffle(list, 1); Console.WriteLine(list.AsString()); Console.WriteLine(); } } }
overhand=: (\: [: +/\ %@%:@# > # ?@# 0:)@]^:[ riffle=: (({.~+/)`(I.@])`(-.@]#inv (}.~+/))} ?@(#&2)@#)@]^:[
Rewrite the snippet below in J so it works the same as the original C# code.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CardShuffles { public static class Helper { public static string AsString<T>(this ICollection<T> c) { StringBuilder sb = new StringBuilder("["); sb.Append(string.Join(", ", c)); return sb.Append("]").ToString(); } } class Program { private static Random rand = new Random(); public static List<T> riffleShuffle<T>(ICollection<T> list, int flips) { List<T> newList = new List<T>(list); for (int n = 0; n < flips; n++) { int cutPoint = newList.Count / 2 + (rand.Next(0, 2) == 0 ? -1 : 1) * rand.Next((int)(newList.Count * 0.1)); List<T> left = new List<T>(newList.Take(cutPoint)); List<T> right = new List<T>(newList.Skip(cutPoint)); newList.Clear(); while (left.Count > 0 && right.Count > 0) { if (rand.NextDouble() >= ((double)left.Count / right.Count) / 2) { newList.Add(right.First()); right.RemoveAt(0); } else { newList.Add(left.First()); left.RemoveAt(0); } } if (left.Count > 0) newList.AddRange(left); if (right.Count > 0) newList.AddRange(right); } return newList; } public static List<T> overhandShuffle<T>(List<T> list, int passes) { List<T> mainHand = new List<T>(list); for (int n = 0; n < passes; n++) { List<T> otherHand = new List<T>(); while (mainHand.Count>0) { int cutSize = rand.Next((int)(list.Count * 0.2)) + 1; List<T> temp = new List<T>(); for (int i = 0; i < cutSize && mainHand.Count > 0; i++) { temp.Add(mainHand.First()); mainHand.RemoveAt(0); } if (rand.NextDouble()>=0.1) { temp.AddRange(otherHand); otherHand = temp; } else { otherHand.AddRange(temp); } } mainHand = otherHand; } return mainHand; } static void Main(string[] args) { List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; Console.WriteLine(list.AsString()); list = riffleShuffle(list, 10); Console.WriteLine(list.AsString()); Console.WriteLine(); list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; Console.WriteLine(list.AsString()); list = riffleShuffle(list, 1); Console.WriteLine(list.AsString()); Console.WriteLine(); list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; Console.WriteLine(list.AsString()); list = overhandShuffle(list, 10); Console.WriteLine(list.AsString()); Console.WriteLine(); list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; Console.WriteLine(list.AsString()); list = overhandShuffle(list, 1); Console.WriteLine(list.AsString()); Console.WriteLine(); } } }
overhand=: (\: [: +/\ %@%:@# > # ?@# 0:)@]^:[ riffle=: (({.~+/)`(I.@])`(-.@]#inv (}.~+/))} ?@(#&2)@#)@]^:[
Rewrite this program in J while keeping its functionality equivalent to the C# version.
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) { throw new ArgumentException("d must not be zero"); } long nn = n; long dd = d; if (nn == 0) { dd = 1; } else if (dd < 0) { nn = -nn; dd = -dd; } long g = Math.Abs(Gcd(nn, dd)); if (g > 1) { nn /= g; dd /= g; } num = nn; denom = dd; } private static long Gcd(long a, long b) { if (b == 0) { return a; } return Gcd(b, a % b); } public static Frac operator -(Frac self) { return new Frac(-self.num, self.denom); } public static Frac operator +(Frac lhs, Frac rhs) { return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom); } public static Frac operator -(Frac lhs, Frac rhs) { return lhs + -rhs; } public static Frac operator *(Frac lhs, Frac rhs) { return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom); } public static bool operator <(Frac lhs, Frac rhs) { double x = (double)lhs.num / lhs.denom; double y = (double)rhs.num / rhs.denom; return x < y; } public static bool operator >(Frac lhs, Frac rhs) { double x = (double)lhs.num / lhs.denom; double y = (double)rhs.num / rhs.denom; return x > y; } public static bool operator ==(Frac lhs, Frac rhs) { return lhs.num == rhs.num && lhs.denom == rhs.denom; } public static bool operator !=(Frac lhs, Frac rhs) { return lhs.num != rhs.num || lhs.denom != rhs.denom; } public override string ToString() { if (denom == 1) { return num.ToString(); } return string.Format("{0}/{1}", num, denom); } public override bool Equals(object obj) { var frac = obj as Frac; return frac != null && num == frac.num && denom == frac.denom; } public override int GetHashCode() { var hashCode = 1317992671; hashCode = hashCode * -1521134295 + num.GetHashCode(); hashCode = hashCode * -1521134295 + denom.GetHashCode(); return hashCode; } } class Program { static Frac Bernoulli(int n) { if (n < 0) { throw new ArgumentException("n may not be negative or zero"); } Frac[] a = new Frac[n + 1]; for (int m = 0; m <= n; m++) { a[m] = new Frac(1, m + 1); for (int j = m; j >= 1; j--) { a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1); } } if (n != 1) return a[0]; return -a[0]; } static int Binomial(int n, int k) { if (n < 0 || k < 0 || n < k) { throw new ArgumentException(); } if (n == 0 || k == 0) return 1; int num = 1; for (int i = k + 1; i <= n; i++) { num = num * i; } int denom = 1; for (int i = 2; i <= n - k; i++) { denom = denom * i; } return num / denom; } static void Faulhaber(int p) { Console.Write("{0}Β : ", p); Frac q = new Frac(1, p + 1); int sign = -1; for (int j = 0; j <= p; j++) { sign *= -1; Frac coeff = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j); if (Frac.ZERO == coeff) continue; if (j == 0) { if (Frac.ONE != coeff) { if (-Frac.ONE == coeff) { Console.Write("-"); } else { Console.Write(coeff); } } } else { if (Frac.ONE == coeff) { Console.Write(" + "); } else if (-Frac.ONE == coeff) { Console.Write(" - "); } else if (Frac.ZERO < coeff) { Console.Write(" + {0}", coeff); } else { Console.Write(" - {0}", -coeff); } } int pwr = p + 1 - j; if (pwr > 1) { Console.Write("n^{0}", pwr); } else { Console.Write("n"); } } Console.WriteLine(); } static void Main(string[] args) { for (int i = 0; i < 10; i++) { Faulhaber(i); } } } }
Bsecond=:verb define"0 +/,(<:*(_1^[)*!*(y^~1+[)%1+])"0/~i.1x+y ) Bfirst=: Bsecond - 1&= Faul=:adverb define (0,|.(%m+1x) * (_1x&^ * !&(m+1) * Bfirst) i.1+m)&p. )
Transform the following C# implementation into J, maintaining the same output and logic.
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); for (int n = 3, primeCount = 1; primeCount < limit; n++) { if (notPrime[n]) continue; int digit = n % 10; buckets[prevDigit, digit]++; prevDigit = digit; primeCount++; } for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (buckets[i, j] != 0) { Console.WriteLine("{0} -> {1} count: {2,5:d} frequencyΒ : {3,6:0.00%}", i, j, buckets[i, j], 1.0 * buckets[i, j] / limit); } } } } public static bool[] Sieve(int limit) { bool[] composite = new bool[limit]; composite[0] = composite[1] = true; int max = (int)Math.Sqrt(limit); for (int n = 2; n <= max; n++) { if (!composite[n]) { for (int k = n * n; k < limit; k += n) { composite[k] = true; } } } return composite; } } }
/:~ (~.,. ' ',. ":@(%/&1 999999)@(#/.~)) 2 (,'->',])&":/\ 10|p:i.1e6 1->1 42853 0.042853 1->3 77475 0.0774751 1->7 79453 0.0794531 1->9 50153 0.0501531 2->3 1 1e_6 3->1 58255 0.0582551 3->3 39668 0.039668 3->5 1 1e_6 3->7 72827 0.0728271 3->9 79358 0.0793581 5->7 1 1e_6 7->1 64230 0.0642301 7->3 68595 0.0685951 7->7 39603 0.039603 7->9 77586 0.0775861 9->1 84596 0.0845961 9->3 64371 0.0643711 9->7 58130 0.0581301 9->9 42843 0.042843
Convert this C# snippet to J and keep its semantics consistent.
using System; using System.Linq; using System.Text; namespace ImaginaryBaseNumbers { class Complex { private double real, imag; public Complex(int r, int i) { real = r; imag = i; } public Complex(double r, double i) { real = r; imag = i; } public static Complex operator -(Complex self) => new Complex(-self.real, -self.imag); public static Complex operator +(Complex rhs, Complex lhs) => new Complex(rhs.real + lhs.real, rhs.imag + lhs.imag); public static Complex operator -(Complex rhs, Complex lhs) => new Complex(rhs.real - lhs.real, rhs.imag - lhs.imag); public static Complex operator *(Complex rhs, Complex lhs) => new Complex( rhs.real * lhs.real - rhs.imag * lhs.imag, rhs.real * lhs.imag + rhs.imag * lhs.real ); public static Complex operator *(Complex rhs, double lhs) => new Complex(rhs.real * lhs, rhs.imag * lhs); public static Complex operator /(Complex rhs, Complex lhs) => rhs * lhs.Inv(); public Complex Inv() { double denom = real * real + imag * imag; return new Complex(real / denom, -imag / denom); } public QuaterImaginary ToQuaterImaginary() { if (real == 0.0 && imag == 0.0) return new QuaterImaginary("0"); int re = (int)real; int im = (int)imag; int fi = -1; StringBuilder sb = new StringBuilder(); while (re != 0) { int rem = re % -4; re /= -4; if (rem < 0) { rem = 4 + rem; re++; } sb.Append(rem); sb.Append(0); } if (im != 0) { double f = (new Complex(0.0, imag) / new Complex(0.0, 2.0)).real; im = (int)Math.Ceiling(f); f = -4.0 * (f - im); int index = 1; while (im != 0) { int rem = im % -4; im /= -4; if (rem < 0) { rem = 4 + rem; im++; } if (index < sb.Length) { sb[index] = (char)(rem + 48); } else { sb.Append(0); sb.Append(rem); } index += 2; } fi = (int)f; } string reverse = new string(sb.ToString().Reverse().ToArray()); sb.Length = 0; sb.Append(reverse); if (fi != -1) sb.AppendFormat(".{0}", fi); string s = sb.ToString().TrimStart('0'); if (s[0] == '.') s = "0" + s; return new QuaterImaginary(s); } public override string ToString() { double real2 = (real == -0.0) ? 0.0 : real; double imag2 = (imag == -0.0) ? 0.0 : imag; if (imag2 == 0.0) { return string.Format("{0}", real2); } if (real2 == 0.0) { return string.Format("{0}i", imag2); } if (imag2 > 0.0) { return string.Format("{0} + {1}i", real2, imag2); } return string.Format("{0} - {1}i", real2, -imag2); } } class QuaterImaginary { internal static Complex twoI = new Complex(0.0, 2.0); internal static Complex invTwoI = twoI.Inv(); private string b2i; public QuaterImaginary(string b2i) { if (b2i == "" || !b2i.All(c => "0123.".IndexOf(c) > -1) || b2i.Count(c => c == '.') > 1) { throw new Exception("Invalid Base 2i number"); } this.b2i = b2i; } public Complex ToComplex() { int pointPos = b2i.IndexOf("."); int posLen = (pointPos != -1) ? pointPos : b2i.Length; Complex sum = new Complex(0.0, 0.0); Complex prod = new Complex(1.0, 0.0); for (int j = 0; j < posLen; j++) { double k = (b2i[posLen - 1 - j] - '0'); if (k > 0.0) { sum += prod * k; } prod *= twoI; } if (pointPos != -1) { prod = invTwoI; for (int j = posLen + 1; j < b2i.Length; j++) { double k = (b2i[j] - '0'); if (k > 0.0) { sum += prod * k; } prod *= invTwoI; } } return sum; } public override string ToString() { return b2i; } } class Program { static void Main(string[] args) { for (int i = 1; i <= 16; i++) { Complex c1 = new Complex(i, 0); QuaterImaginary qi = c1.ToQuaterImaginary(); Complex c2 = qi.ToComplex(); Console.Write("{0,4} -> {1,8} -> {2,4} ", c1, qi, c2); c1 = -c1; qi = c1.ToQuaterImaginary(); c2 = qi.ToComplex(); Console.WriteLine("{0,4} -> {1,8} -> {2,4}", c1, qi, c2); } Console.WriteLine(); for (int i = 1; i <= 16; i++) { Complex c1 = new Complex(0, i); QuaterImaginary qi = c1.ToQuaterImaginary(); Complex c2 = qi.ToComplex(); Console.Write("{0,4} -> {1,8} -> {2,4} ", c1, qi, c2); c1 = -c1; qi = c1.ToQuaterImaginary(); c2 = qi.ToComplex(); Console.WriteLine("{0,4} -> {1,8} -> {2,4}", c1, qi, c2); } } } }
ibdec=: {{ 0j2 ibdec y : digits=. 0,".,~&'36b'@> tolower y -.'. ' (x #. digits) % x^#(}.~ 1+i.&'.')y-.' ' }}"1 ibenc=: {{ 0j2 ibenc y : if.0=y do.,'0' return.end. sq=.*:x assert. 17 > sq step=. }.,~(1,|sq) +^:(0>{:@]) (0,sq) #: {. seq=. step^:(0~:{.)^:_"0 're im0'=.+.y 'im imf'=.(sign,1)*(0,|x)#:im0*sign=.*im0 frac=. ,hfd (imf*|x)-.0 if.#frac do.frac=.'.',frac end. frac,~(}.~0 i.~_1}.'0'=]) }:,hfd|:0 1|."0 1 seq re,im }}"0
Convert the following code from C# to J, ensuring the logic remains intact.
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 histogram = new Histogram(X, numBuckets); Console.WriteLine("Sample size: {0:N0}", sampleSize); for (int i = 0; i < numBuckets; i++) { string bar = new String('#', (int)(histogram[i].Count * 360 / sampleSize)); Console.WriteLine(" {0:0.00}Β : {1}", histogram[i].LowerBound, bar); } var statistics = new DescriptiveStatistics(X); Console.WriteLine(" Mean: " + statistics.Mean); Console.WriteLine("StdDev: " + statistics.StandardDeviation); Console.WriteLine(); } static void Main(string[] args) { RunNormal(100); RunNormal(1000); RunNormal(10000); } }
runif01=: ?@$ 0: rnorm01=. (2 o. 2p1 * runif01) * [: %: _2 * ^.@runif01 mean=: +/ % # stddev=: (<:@# %~ +/)&.:*:@(- mean) histogram=: <:@(#/.~)@(i.@#@[ , I.)
Generate a J translation of this C# snippet without changing its computational steps.
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[j] != x && pow[t = (j + ten) % n] == 0) pow[t] = x; if (pow[ten] == 0) pow[ten] = x; ten = (10 * ten) % n; if (pow[0] != 0) { x = n; string s = ""; while (x != 0) { int p = pow[x % n]; if (count > p) s += new string('0', count - p); count = p - 1; s += "1"; x = (n + x - val[p]) % n; } if (count > 0) s += new string('0', count); return s; } } return "1"; } static void Main(string[] args) { string fmt = "{0,4} * {1,24} = {2,-28}\n"; int[] m = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878 }; string[] r = new string[m.Length]; WriteLine(fmt + new string('-', 62), "n", "multiplier", "B10"); var sw = System.Diagnostics.Stopwatch.StartNew(); for (int i = 0; i < m.Length; i++) r[i] = B10(m[i]); sw.Stop(); for (int i = 0; i < m.Length; i++) Write(fmt, m[i], decimal.Parse(r[i]) / m[i], r[i]); Write("\nTook {0}ms", sw.Elapsed.TotalMilliseconds); } }
B10=: {{ next=. {{ {: (u -) 10x^# }} step=. ([>. [ {~ y|(i.y)+]) next continue=. 0 = ({~y|]) next L=.1 0,~^:(y>1) (, step)^:continue^:_ ,:y{.1 1 k=. y|-r=.10x^<:#L for_j. i.-<:#L do. if. 0=L{~<k,~j-1 do. k=. y|k-E=. 10x^j r=. r+E end. end. r assert. 0=y|r }}
Port the following code from C# to J with equivalent syntax and logic.
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 == 0) { int j = n / i; divs.Add(i); if (i != j) { divs.Add(j); } } } return divs; } static bool IsPartSum(List<int> divs, int sum) { if (sum == 0) { return true; } var le = divs.Count; if (le == 0) { return false; } var last = divs[le - 1]; List<int> newDivs = new List<int>(); for (int i = 0; i < le - 1; i++) { newDivs.Add(divs[i]); } if (last > sum) { return IsPartSum(newDivs, sum); } return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last); } static bool IsZumkeller(int n) { var divs = GetDivisors(n); var sum = divs.Sum(); if (sum % 2 == 1) { return false; } if (n % 2 == 1) { var abundance = sum - 2 * n; return abundance > 0 && abundance % 2 == 0; } return IsPartSum(divs, sum / 2); } static void Main() { Console.WriteLine("The first 220 Zumkeller numbers are:"); int i = 2; for (int count = 0; count < 220; i++) { if (IsZumkeller(i)) { Console.Write("{0,3} ", i); count++; if (count % 20 == 0) { Console.WriteLine(); } } } Console.WriteLine("\nThe first 40 odd Zumkeller numbers are:"); i = 3; for (int count = 0; count < 40; i += 2) { if (IsZumkeller(i)) { Console.Write("{0,5} ", i); count++; if (count % 10 == 0) { Console.WriteLine(); } } } Console.WriteLine("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:"); i = 3; for (int count = 0; count < 40; i += 2) { if (i % 10 != 5 && IsZumkeller(i)) { Console.Write("{0,7} ", i); count++; if (count % 8 == 0) { Console.WriteLine(); } } } } } }
divisors=: {{ \:~ */@>,{ (^ i.@>:)&.">/ __ q: y }} zum=: {{ if. 2|s=. +/divs=. divisors y do. 0 elseif. 2|y do. (0<k) * 0=2|k=. s-2*y else. s=. -:s for_d. divs do. if. d<:s do. s=. s-d end. end. s=0 end. }}@>
Maintain the same structure and functionality when rewriting this code in J.
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, ",")) .ToList() .ForEach(Console.WriteLine); } string Commatize(string text, int startPosition, int interval, string separator) { var matches = Regex.Matches(text.Substring(startPosition), "[0-9]*"); var x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList(); return string.Join("", x); } string Commatize(Match match, int interval, string separator, string original) { if (match.Length <= interval) return original.Substring(match.Index, match.Index == original.Length ? 0 : Math.Max(match.Length, 1)); return string.Join(separator, match.Value.Split(interval)); } public static class Extension { public static string[] Split(this string source, int interval) { return SplitImpl(source, interval).ToArray(); } static IEnumerable<string>SplitImpl(string source, int interval) { for (int i = 1; i < source.Length; i++) { if (i % interval != 0) continue; yield return source.Substring(i - interval, interval); } } }
require'regex' commatize=:3 :0"1 L:1 0 (i.0) commatize y : opts=. boxopen x char=. (#~ ' '&=@{.@(0&#)@>) opts num=. ;opts-.char delim=. 0 {:: char,<',' 'begin period'=. _1 0+2{.num,(#num)}.1 3 prefix=. begin {.y text=. begin }. y 'start len'=. ,'[1-9][0-9]*' rxmatch text if.0=len do. y return. end. number=. (start,:len) [;.0 text numb=. (>:period|<:#number){.number fixed=. numb,;delim&,each (-period)<\ (#numb)}.number prefix,(start{.text),fixed,(start+len)}.text )
Preserve the algorithm and functionality while converting the code from C# to J.
using System; using System.Collections.Generic; using System.Linq; using static System.Console; using UI = System.UInt64; using LST = System.Collections.Generic.List<System.Collections.Generic.List<sbyte>>; using Lst = System.Collections.Generic.List<sbyte>; using DT = System.DateTime; class Program { const sbyte MxD = 19; public struct term { public UI coeff; public sbyte a, b; public term(UI c, int a_, int b_) { coeff = c; a = (sbyte)a_; b = (sbyte)b_; } } static int[] digs; static List<UI> res; static sbyte count = 0; static DT st; static List<List<term>> tLst; static List<LST> lists; static Dictionary<int, LST> fml, dmd; static Lst dl, zl, el, ol, il; static bool odd; static int nd, nd2; static LST ixs; static int[] cnd, di; static LST dis; static UI Dif; static UI ToDif() { UI r = 0; for (int i = 0; i < digs.Length; i++) r = r * 10 + (uint)digs[i]; return r; } static UI ToSum() { UI r = 0; for (int i = digs.Length - 1; i >= 0; i--) r = r * 10 + (uint)digs[i]; return Dif + (r << 1); } static bool IsSquare(UI nmbr) { if ((0x202021202030213 & (1 << (int)(nmbr & 63))) != 0) { UI r = (UI)Math.Sqrt((double)nmbr); return r * r == nmbr; } return false; } static Lst Seq(sbyte from, int to, sbyte stp = 1) { Lst res = new Lst(); for (sbyte item = from; item <= to; item += stp) res.Add(item); return res; } static void Fnpr(int lev) { if (lev == dis.Count) { digs[ixs[0][0]] = fml[cnd[0]][di[0]][0]; digs[ixs[0][1]] = fml[cnd[0]][di[0]][1]; int le = di.Length, i = 1; if (odd) digs[nd >> 1] = di[--le]; foreach (sbyte d in di.Skip(1).Take(le - 1)) { digs[ixs[i][0]] = dmd[cnd[i]][d][0]; digs[ixs[i][1]] = dmd[cnd[i++]][d][1]; } if (!IsSquare(ToSum())) return; res.Add(ToDif()); WriteLine("{0,16:n0}{1,4} ({2:n0})", (DT.Now - st).TotalMilliseconds, ++count, res.Last()); } else foreach (var n in dis[lev]) { di[lev] = n; Fnpr(lev + 1); } } static void Fnmr (LST list, int lev) { if (lev == list.Count) { Dif = 0; sbyte i = 0; foreach (var t in tLst[nd2]) { if (cnd[i] < 0) Dif -= t.coeff * (UI)(-cnd[i++]); else Dif += t.coeff * (UI)cnd[i++]; } if (Dif <= 0 || !IsSquare(Dif)) return; dis = new LST { Seq(0, fml[cnd[0]].Count - 1) }; foreach (int ii in cnd.Skip(1)) dis.Add(Seq(0, dmd[ii].Count - 1)); if (odd) dis.Add(il); di = new int[dis.Count]; Fnpr(0); } else foreach(sbyte n in list[lev]) { cnd[lev] = n; Fnmr(list, lev + 1); } } static void init() { UI pow = 1; tLst = new List<List<term>>(); foreach (int r in Seq(2, MxD)) { List<term> terms = new List<term>(); pow *= 10; UI p1 = pow, p2 = 1; for (int i1 = 0, i2 = r - 1; i1 < i2; i1++, i2--) { terms.Add(new term(p1 - p2, i1, i2)); p1 /= 10; p2 *= 10; } tLst.Add(terms); } fml = new Dictionary<int, LST> { [0] = new LST { new Lst { 2, 2 }, new Lst { 8, 8 } }, [1] = new LST { new Lst { 6, 5 }, new Lst { 8, 7 } }, [4] = new LST { new Lst { 4, 0 } }, [6] = new LST { new Lst { 6, 0 }, new Lst { 8, 2 } } }; dmd = new Dictionary<int, LST>(); for (sbyte i = 0; i < 10; i++) for (sbyte j = 0, d = i; j < 10; j++, d--) { if (dmd.ContainsKey(d)) dmd[d].Add(new Lst { i, j }); else dmd[d] = new LST { new Lst { i, j } }; } dl = Seq(-9, 9); zl = Seq( 0, 0); el = Seq(-8, 8, 2); ol = Seq(-9, 9, 2); il = Seq( 0, 9); lists = new List<LST>(); foreach (sbyte f in fml.Keys) lists.Add(new LST { new Lst { f } }); } static void Main(string[] args) { init(); res = new List<UI>(); st = DT.Now; count = 0; WriteLine("{0,5}{1,12}{2,4}{3,14}", "digs", "elapsed(ms)", "R/N", "Unordered Rare Numbers"); for (nd = 2, nd2 = 0, odd = false; nd <= MxD; nd++, nd2++, odd = !odd) { digs = new int[nd]; if (nd == 4) { lists[0].Add(zl); lists[1].Add(ol); lists[2].Add(el); lists[3].Add(ol); } else if (tLst[nd2].Count > lists[0].Count) foreach (LST list in lists) list.Add(dl); ixs = new LST(); foreach (term t in tLst[nd2]) ixs.Add(new Lst { t.a, t.b }); foreach (LST list in lists) { cnd = new int[list.Count]; Fnmr(list, 0); } WriteLine(" {0,2} {1,10:n0}", nd, (DT.Now - st).TotalMilliseconds); } res.Sort(); WriteLine("\nThe {0} rare numbers with up to {1} digits are:", res.Count, MxD); count = 0; foreach (var rare in res) WriteLine("{0,2}:{1,27:n0}", ++count, rare); if (System.Diagnostics.Debugger.IsAttached) ReadKey(); } }
rare =: ( np@:] *. (nbrPs rr) ) b10 np =: -.@:(-: |.) nbrPs =: > *. sdPs sdPs =: + *.&:ps - ps =: 0 = 1 | %: rr =: 10&#.@:|. b10 =: 10&#.^:_1
Convert this C# snippet to J and keep its semantics consistent.
using System; using System.Collections.Generic; namespace SuffixTree { class Node { public string sub; public List<int> ch = new List<int>(); public Node() { sub = ""; } public Node(string sub, params int[] children) { this.sub = sub; ch.AddRange(children); } } class SuffixTree { readonly List<Node> nodes = new List<Node>(); public SuffixTree(string str) { nodes.Add(new Node()); for (int i = 0; i < str.Length; i++) { AddSuffix(str.Substring(i)); } } public void Visualize() { if (nodes.Count == 0) { Console.WriteLine("<empty>"); return; } void f(int n, string pre) { var children = nodes[n].ch; if (children.Count == 0) { Console.WriteLine("- {0}", nodes[n].sub); return; } Console.WriteLine("+ {0}", nodes[n].sub); var it = children.GetEnumerator(); if (it.MoveNext()) { do { var cit = it; if (!cit.MoveNext()) break; Console.Write("{0}+-", pre); f(it.Current, pre + "| "); } while (it.MoveNext()); } Console.Write("{0}+-", pre); f(children[children.Count-1], pre+" "); } f(0, ""); } private void AddSuffix(string suf) { int n = 0; int i = 0; while (i < suf.Length) { char b = suf[i]; int x2 = 0; int n2; while (true) { var children = nodes[n].ch; if (x2 == children.Count) { n2 = nodes.Count; nodes.Add(new Node(suf.Substring(i))); nodes[n].ch.Add(n2); return; } n2 = children[x2]; if (nodes[n2].sub[0] == b) { break; } x2++; } var sub2 = nodes[n2].sub; int j = 0; while (j < sub2.Length) { if (suf[i + j] != sub2[j]) { var n3 = n2; n2 = nodes.Count; nodes.Add(new Node(sub2.Substring(0, j), n3)); nodes[n3].sub = sub2.Substring(j); nodes[n].ch[x2] = n2; break; } j++; } i += j; n = n2; } } } class Program { static void Main() { new SuffixTree("banana$").Visualize(); } } }
classify=: {.@> </. ] build_tree=:3 :0 tree=. ,:_;_;'' if. 0=#y do. tree return.end. if. 1=#y do. tree,(#;y);0;y return.end. for_box.classify y do. char=. {.>{.>box subtree=. }.build_tree }.each>box ndx=.I.0=1&{::"1 subtree n=.#tree if. 1=#ndx do. counts=. 1 + 0&{::"1 subtree parents=. (n-1) (+*]&*) 1&{::"1 subtree edges=. (ndx}~ <@(char,ndx&{::)) 2&{"1 subtree tree=. tree, counts;"0 1 parents;"0 edges else. tree=. tree,(__;0;,char),(1;n;0) + ::]&.>"1 subtree end. end. ) suffix_tree=:3 :0 assert. -.({:e.}:)y tree=. B=:|:build_tree <\. y ((1+#y)-each {.tree),}.tree )
Maintain the same structure and functionality when rewriting this code in J.
using System; using System.Collections.Generic; namespace SuffixTree { class Node { public string sub; public List<int> ch = new List<int>(); public Node() { sub = ""; } public Node(string sub, params int[] children) { this.sub = sub; ch.AddRange(children); } } class SuffixTree { readonly List<Node> nodes = new List<Node>(); public SuffixTree(string str) { nodes.Add(new Node()); for (int i = 0; i < str.Length; i++) { AddSuffix(str.Substring(i)); } } public void Visualize() { if (nodes.Count == 0) { Console.WriteLine("<empty>"); return; } void f(int n, string pre) { var children = nodes[n].ch; if (children.Count == 0) { Console.WriteLine("- {0}", nodes[n].sub); return; } Console.WriteLine("+ {0}", nodes[n].sub); var it = children.GetEnumerator(); if (it.MoveNext()) { do { var cit = it; if (!cit.MoveNext()) break; Console.Write("{0}+-", pre); f(it.Current, pre + "| "); } while (it.MoveNext()); } Console.Write("{0}+-", pre); f(children[children.Count-1], pre+" "); } f(0, ""); } private void AddSuffix(string suf) { int n = 0; int i = 0; while (i < suf.Length) { char b = suf[i]; int x2 = 0; int n2; while (true) { var children = nodes[n].ch; if (x2 == children.Count) { n2 = nodes.Count; nodes.Add(new Node(suf.Substring(i))); nodes[n].ch.Add(n2); return; } n2 = children[x2]; if (nodes[n2].sub[0] == b) { break; } x2++; } var sub2 = nodes[n2].sub; int j = 0; while (j < sub2.Length) { if (suf[i + j] != sub2[j]) { var n3 = n2; n2 = nodes.Count; nodes.Add(new Node(sub2.Substring(0, j), n3)); nodes[n3].sub = sub2.Substring(j); nodes[n].ch[x2] = n2; break; } j++; } i += j; n = n2; } } } class Program { static void Main() { new SuffixTree("banana$").Visualize(); } } }
classify=: {.@> </. ] build_tree=:3 :0 tree=. ,:_;_;'' if. 0=#y do. tree return.end. if. 1=#y do. tree,(#;y);0;y return.end. for_box.classify y do. char=. {.>{.>box subtree=. }.build_tree }.each>box ndx=.I.0=1&{::"1 subtree n=.#tree if. 1=#ndx do. counts=. 1 + 0&{::"1 subtree parents=. (n-1) (+*]&*) 1&{::"1 subtree edges=. (ndx}~ <@(char,ndx&{::)) 2&{"1 subtree tree=. tree, counts;"0 1 parents;"0 edges else. tree=. tree,(__;0;,char),(1;n;0) + ::]&.>"1 subtree end. end. ) suffix_tree=:3 :0 assert. -.({:e.}:)y tree=. B=:|:build_tree <\. y ((1+#y)-each {.tree),}.tree )
Can you help me rewrite this code in J instead of C#, keeping it the same logically?
using System; using System.Collections.Generic; using System.Linq; namespace LatinSquares { using matrix = List<List<int>>; class Program { static void Swap<T>(ref T a, ref T b) { var t = a; a = b; b = t; } static matrix DList(int n, int start) { start--; var a = Enumerable.Range(0, n).ToArray(); a[start] = a[0]; a[0] = start; Array.Sort(a, 1, a.Length - 1); var first = a[1]; matrix r = new matrix(); void recurse(int last) { if (last == first) { for (int j = 1; j < a.Length; j++) { var v = a[j]; if (j == v) { return; } } var b = a.Select(v => v + 1).ToArray(); r.Add(b.ToList()); return; } for (int i = last; i >= 1; i--) { Swap(ref a[i], ref a[last]); recurse(last - 1); Swap(ref a[i], ref a[last]); } } recurse(n - 1); return r; } static ulong ReducedLatinSquares(int n, bool echo) { if (n <= 0) { if (echo) { Console.WriteLine("[]\n"); } return 0; } else if (n == 1) { if (echo) { Console.WriteLine("[1]\n"); } return 1; } matrix rlatin = new matrix(); for (int i = 0; i < n; i++) { rlatin.Add(new List<int>()); for (int j = 0; j < n; j++) { rlatin[i].Add(0); } } for (int j = 0; j < n; j++) { rlatin[0][j] = j + 1; } ulong count = 0; void recurse(int i) { var rows = DList(n, i); for (int r = 0; r < rows.Count; r++) { rlatin[i - 1] = rows[r]; for (int k = 0; k < i - 1; k++) { for (int j = 1; j < n; j++) { if (rlatin[k][j] == rlatin[i - 1][j]) { if (r < rows.Count - 1) { goto outer; } if (i > 2) { return; } } } } if (i < n) { recurse(i + 1); } else { count++; if (echo) { PrintSquare(rlatin, n); } } outer: { } } } recurse(2); return count; } static void PrintSquare(matrix latin, int n) { foreach (var row in latin) { var it = row.GetEnumerator(); Console.Write("["); if (it.MoveNext()) { Console.Write(it.Current); } while (it.MoveNext()) { Console.Write(", {0}", it.Current); } Console.WriteLine("]"); } Console.WriteLine(); } static ulong Factorial(ulong n) { if (n <= 0) { return 1; } ulong prod = 1; for (ulong i = 2; i < n + 1; i++) { prod *= i; } return prod; } static void Main() { Console.WriteLine("The four reduced latin squares of order 4 are:\n"); ReducedLatinSquares(4, true); Console.WriteLine("The size of the set of reduced latin squares for the following orders"); Console.WriteLine("and hence the total number of latin squares of these orders are:\n"); for (int n = 1; n < 7; n++) { ulong nu = (ulong)n; var size = ReducedLatinSquares(n, false); var f = Factorial(nu - 1); f *= f * nu * size; Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f); } } } }
redlat=: {{ perms=: (A.&i.~ !)~ y sqs=. i.1 1,y for_j.}.i.y do. p=. (j={."1 perms)#perms sel=.-.+./"1 p +./@:="1/"2 sqs sqs=.(#~ 1-0*/ .="1{:"2),/sqs,"2 1 sel#"2 p end. }}
Maintain the same structure and functionality when rewriting this code in J.
using System; using System.Collections.Generic; class Node { public enum Colors { Black, White, Gray } public Colors color { get; set; } public int N { get; } public Node(int n) { N = n; color = Colors.White; } } class Graph { public HashSet<Node> V { get; } public Dictionary<Node, HashSet<Node>> Adj { get; } public void Kosaraju() { var L = new HashSet<Node>(); Action<Node> Visit = null; Visit = (u) => { if (u.color == Node.Colors.White) { u.color = Node.Colors.Gray; foreach (var v in Adj[u]) Visit(v); L.Add(u); } }; Action<Node, Node> Assign = null; Assign = (u, root) => { if (u.color != Node.Colors.Black) { if (u == root) Console.Write("SCC: "); Console.Write(u.N + " "); u.color = Node.Colors.Black; foreach (var v in Adj[u]) Assign(v, root); if (u == root) Console.WriteLine(); } }; foreach (var u in V) Visit(u); foreach (var u in L) Assign(u, u); } }
visit=: {{ if.y{unvisited do. unvisited=: 0 y} unvisited visit y{::out L=: y,L end. }}"0 assign=: {{ if._1=y{assigned do. assigned=: x y} assigned x&assign y{::in end. }}"0 kosaraju=: {{ out=: y in=: <@I.|:y e.S:0~i.#y unvisited=: 1#~#y assigned=: _1#~#y L=: i.0 visit"0 i.#y assign~L assigned }}
Convert the following code from C# to J, ensuring the logic remains intact.
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Wordseach { static class Program { readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}; class Grid { public char[,] Cells = new char[nRows, nCols]; public List<string> Solutions = new List<string>(); public int NumAttempts; } readonly static int nRows = 10; readonly static int nCols = 10; readonly static int gridSize = nRows * nCols; readonly static int minWords = 25; readonly static Random rand = new Random(); static void Main(string[] args) { PrintResult(CreateWordSearch(ReadWords("unixdict.txt"))); } private static List<string> ReadWords(string filename) { int maxLen = Math.Max(nRows, nCols); return System.IO.File.ReadAllLines(filename) .Select(s => s.Trim().ToLower()) .Where(s => Regex.IsMatch(s, "^[a-z]{3," + maxLen + "}$")) .ToList(); } private static Grid CreateWordSearch(List<string> words) { int numAttempts = 0; while (++numAttempts < 100) { words.Shuffle(); var grid = new Grid(); int messageLen = PlaceMessage(grid, "Rosetta Code"); int target = gridSize - messageLen; int cellsFilled = 0; foreach (var word in words) { cellsFilled += TryPlaceWord(grid, word); if (cellsFilled == target) { if (grid.Solutions.Count >= minWords) { grid.NumAttempts = numAttempts; return grid; } else break; } } } return null; } private static int TryPlaceWord(Grid grid, string word) { int randDir = rand.Next(dirs.GetLength(0)); int randPos = rand.Next(gridSize); for (int dir = 0; dir < dirs.GetLength(0); dir++) { dir = (dir + randDir) % dirs.GetLength(0); for (int pos = 0; pos < gridSize; pos++) { pos = (pos + randPos) % gridSize; int lettersPlaced = TryLocation(grid, word, dir, pos); if (lettersPlaced > 0) return lettersPlaced; } } return 0; } private static int TryLocation(Grid grid, string word, int dir, int pos) { int r = pos / nCols; int c = pos % nCols; int len = word.Length; if ((dirs[dir, 0] == 1 && (len + c) > nCols) || (dirs[dir, 0] == -1 && (len - 1) > c) || (dirs[dir, 1] == 1 && (len + r) > nRows) || (dirs[dir, 1] == -1 && (len - 1) > r)) return 0; int rr, cc, i, overlaps = 0; for (i = 0, rr = r, cc = c; i < len; i++) { if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i]) { return 0; } cc += dirs[dir, 0]; rr += dirs[dir, 1]; } for (i = 0, rr = r, cc = c; i < len; i++) { if (grid.Cells[rr, cc] == word[i]) overlaps++; else grid.Cells[rr, cc] = word[i]; if (i < len - 1) { cc += dirs[dir, 0]; rr += dirs[dir, 1]; } } int lettersPlaced = len - overlaps; if (lettersPlaced > 0) { grid.Solutions.Add($"{word,-10} ({c},{r})({cc},{rr})"); } return lettersPlaced; } private static int PlaceMessage(Grid grid, string msg) { msg = Regex.Replace(msg.ToUpper(), "[^A-Z]", ""); int messageLen = msg.Length; if (messageLen > 0 && messageLen < gridSize) { int gapSize = gridSize / messageLen; for (int i = 0; i < messageLen; i++) { int pos = i * gapSize + rand.Next(gapSize); grid.Cells[pos / nCols, pos % nCols] = msg[i]; } return messageLen; } return 0; } public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = rand.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } private static void PrintResult(Grid grid) { if (grid == null || grid.NumAttempts == 0) { Console.WriteLine("No grid to display"); return; } int size = grid.Solutions.Count; Console.WriteLine("Attempts: " + grid.NumAttempts); Console.WriteLine("Number of words: " + size); Console.WriteLine("\n 0 1 2 3 4 5 6 7 8 9"); for (int r = 0; r < nRows; r++) { Console.Write("\n{0} ", r); for (int c = 0; c < nCols; c++) Console.Write(" {0} ", grid.Cells[r, c]); } Console.WriteLine("\n"); for (int i = 0; i < size - 1; i += 2) { Console.WriteLine("{0} {1}", grid.Solutions[i], grid.Solutions[i + 1]); } if (size % 2 == 1) Console.WriteLine(grid.Solutions[size - 1]); Console.ReadLine(); } } }
require'web/gethttp' unixdict=:verb define if. _1 -: fread 'unixdict.txt' do. (gethttp 'http://www.puzzlers.org/pub/wordlists/unixdict.txt') fwrite 'unixdict.txt' end. fread 'unixdict.txt' ) words=:verb define (#~ 1 - 0&e.@e.&'abcdefghijklmnopqrstuvwxyz'@>) (#~ [: (2&< * 10&>:) #@>) <;._2 unixdict'' ) dirs=: 10#.0 0-.~>,{,~<i:1 lims=: _10+,"2 +/&>/"1 (0~:i:4)#>,{,~<<"1]1 10 1 +i."0]10*i:_1 dnms=: ;:'nw north ne west east sw south se' genpuz=:verb define words=. words'' fill=. 'ROSETTACODE' grid=. ,10 10$' ' inds=. ,i.10 10 patience=. -:#words key=. i.0 0 inuse=. i.0 2 while. (26>#key)+.0<cap=. (+/' '=grid)-#fill do. word=. >({~ ?@#) words dir=. ?@#dirs offs=. (inds#~(#word)<:inds{dir{lims)+/(i.#word)*/dir{dirs cool=. ' '=offs{grid sel=. */"1 cool+.(offs{grid)="1 word offs=. (sel*cap>:+/"1 cool)#offs if. (#offs) do. off=. ({~ ?@#) offs loc=. ({.off),dir if. -. loc e. inuse do. inuse=. inuse,loc grid=. word off} grid patience=. patience+1 key=. /:~ key,' ',(10{.word),(3":1+10 10#:{.off),' ',dir{::dnms end. else. if. 0 > patience=. patience-1 do. inuse=.i.0 2 key=.i.0 0 grid=. ,10 10$' ' patience=. -:#words end. end. end. puz=. (_23{.":i.10),' ',1j1#"1(":i.10 1),.' ',.10 10$fill (I.grid=' ')} grid puz,' ',1 1}._1 _1}.":((</.~ <.) i.@# * 3%#)key )
Transform the following C# implementation into J, maintaining the same output and logic.
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) { if (keySize < 1) throw new ArgumentException("Key size can't be less than 1"); string body; using (StreamReader sr = new StreamReader(filePath)) { body = sr.ReadToEnd(); } var words = body.Split(); if (outputSize < keySize || words.Length < outputSize) { throw new ArgumentException("Output size is out of range"); } Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>(); for (int i = 0; i < words.Length - keySize; i++) { var key = words.Skip(i).Take(keySize).Aggregate(Join); string value; if (i + keySize < words.Length) { value = words[i + keySize]; } else { value = ""; } if (dict.ContainsKey(key)) { dict[key].Add(value); } else { dict.Add(key, new List<string>() { value }); } } Random rand = new Random(); List<string> output = new List<string>(); int n = 0; int rn = rand.Next(dict.Count); string prefix = dict.Keys.Skip(rn).Take(1).Single(); output.AddRange(prefix.Split()); while (true) { var suffix = dict[prefix]; if (suffix.Count == 1) { if (suffix[0] == "") { return output.Aggregate(Join); } output.Add(suffix[0]); } else { rn = rand.Next(suffix.Count); output.Add(suffix[rn]); } if (output.Count >= outputSize) { return output.Take(outputSize).Aggregate(Join); } n++; prefix = output.Skip(n).Take(keySize).Aggregate(Join); } } static void Main(string[] args) { Console.WriteLine(Markov("alice_oz.txt", 3, 200)); } } }
require'web/gethttp' setstats=:dyad define 'plen slen limit'=: x txt=. gethttp y letters=. (tolower~:toupper)txt apostrophes=. (_1 |.!.0 letters)*(1 |.!.0 letters)*''''=txt parsed=. <;._1 ' ',deb ' ' (I.-.letters+apostrophes)} tolower txt words=: ~.parsed corpus=: words i.parsed prefixes=: ~.plen]\corpus suffixes=: ~.slen]\corpus ngrams=. (plen+slen)]\corpus pairs=. (prefixes i. plen{."1 ngrams),. suffixes i. plen}."1 ngrams stats=: (#/.~pairs) (<"1~.pairs)} (prefixes ,&# suffixes)$0 weights=: +/\"1 stats totals=: (+/"1 stats),0 i.0 0 ) genphrase=:3 :0 pren=. #prefixes sufn=. #suffixes phrase=. (?pren) { prefixes while. limit > #phrase do. p=. prefixes i. (-plen) {. phrase t=. p { totals if. 0=t do. break.end. s=. (p { weights) I. ?t phrase=. phrase, s { suffixes end. ;:inv phrase { words )
Can you help me rewrite this code in J instead of C#, keeping it the same logically?
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; namespace AruthmeticCoding { using Freq = Dictionary<char, long>; using Triple = Tuple<BigInteger, int, Dictionary<char, long>>; class Program { static Freq CumulativeFreq(Freq freq) { long total = 0; Freq cf = new Freq(); for (int i = 0; i < 256; i++) { char c = (char)i; if (freq.ContainsKey(c)) { long v = freq[c]; cf[c] = total; total += v; } } return cf; } static Triple ArithmeticCoding(string str, long radix) { Freq freq = new Freq(); foreach (char c in str) { if (freq.ContainsKey(c)) { freq[c] += 1; } else { freq[c] = 1; } } Freq cf = CumulativeFreq(freq); BigInteger @base = str.Length; BigInteger lower = 0; BigInteger pf = 1; foreach (char c in str) { BigInteger x = cf[c]; lower = lower * @base + x * pf; pf = pf * freq[c]; } BigInteger upper = lower + pf; int powr = 0; BigInteger bigRadix = radix; while (true) { pf = pf / bigRadix; if (pf == 0) break; powr++; } BigInteger diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr)); return new Triple(diff, powr, freq); } static string ArithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) { BigInteger powr = radix; BigInteger enc = num * BigInteger.Pow(powr, pwr); long @base = freq.Values.Sum(); Freq cf = CumulativeFreq(freq); Dictionary<long, char> dict = new Dictionary<long, char>(); foreach (char key in cf.Keys) { long value = cf[key]; dict[value] = key; } long lchar = -1; for (long i = 0; i < @base; i++) { if (dict.ContainsKey(i)) { lchar = dict[i]; } else if (lchar != -1) { dict[i] = (char)lchar; } } StringBuilder decoded = new StringBuilder((int)@base); BigInteger bigBase = @base; for (long i = @base - 1; i >= 0; --i) { BigInteger pow = BigInteger.Pow(bigBase, (int)i); BigInteger div = enc / pow; char c = dict[(long)div]; BigInteger fv = freq[c]; BigInteger cv = cf[c]; BigInteger diff = enc - pow * cv; enc = diff / fv; decoded.Append(c); } return decoded.ToString(); } static void Main(string[] args) { long radix = 10; string[] strings = { "DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT" }; foreach (string str in strings) { Triple encoded = ArithmeticCoding(str, radix); string dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3); Console.WriteLine("{0,-25}=> {1,19} * {2}^{3}", str, encoded.Item1, radix, encoded.Item2); if (str != dec) { throw new Exception("\tHowever that is incorrect!"); } } } } }
aekDict=:verb define d=. ~.y o=. /:d f=. (#/.~%&x:#)y (o{d);o{f ) aekEnc=:verb define (aekDict y) aekEnc y : 'u F'=.x b=. x:#y f=. b*F i=. u i.y c=. +/\0,}:f L=. b #. (i{c)**/\1,}:i{f p=. */i{f e=. x:<.10^.p e,~<.(L+p)%10^e ) aekDec=:adverb define : 'u F'=. x f=. m*F c=.+/\0,}:f C=.<:}.c,m N=. (* 10&^)/y r=. '' for_d. m^x:i.-m do. id=. <.N%d i=.C I.id N=.<.(N -(i{c)*d)%i{f r=.r,u{~i end. ) aek=:verb define dict=. aekDict y echo 'Dictionary:' echo ' ',.(0{::dict),.' ',.":,.1{::dict echo 'Length:' echo ' ',":#y echo 'Encoded:' echo ' ',":dict aekEnc y echo 'Decoded:' echo ' ',":dict (#y) aekDec aekEnc y )
Convert the following code from C# to J, ensuring the logic remains intact.
using System; using System.Text; namespace GeometricAlgebra { struct Vector { private readonly double[] dims; public Vector(double[] da) { dims = da; } public static Vector operator -(Vector v) { return v * -1.0; } public static Vector operator +(Vector lhs, Vector rhs) { var result = new double[32]; Array.Copy(lhs.dims, 0, result, 0, lhs.Length); for (int i = 0; i < result.Length; i++) { result[i] = lhs[i] + rhs[i]; } return new Vector(result); } public static Vector operator *(Vector lhs, Vector rhs) { var result = new double[32]; for (int i = 0; i < lhs.Length; i++) { if (lhs[i] != 0.0) { for (int j = 0; j < lhs.Length; j++) { if (rhs[j] != 0.0) { var s = ReorderingSign(i, j) * lhs[i] * rhs[j]; var k = i ^ j; result[k] += s; } } } } return new Vector(result); } public static Vector operator *(Vector v, double scale) { var result = (double[])v.dims.Clone(); for (int i = 0; i < result.Length; i++) { result[i] *= scale; } return new Vector(result); } public double this[int key] { get { return dims[key]; } set { dims[key] = value; } } public int Length { get { return dims.Length; } } public Vector Dot(Vector rhs) { return (this * rhs + rhs * this) * 0.5; } private static int BitCount(int i) { i -= ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); i = (i + (i >> 4)) & 0x0F0F0F0F; i += (i >> 8); i += (i >> 16); return i & 0x0000003F; } private static double ReorderingSign(int i, int j) { int k = i >> 1; int sum = 0; while (k != 0) { sum += BitCount(k & j); k >>= 1; } return ((sum & 1) == 0) ? 1.0 : -1.0; } public override string ToString() { var it = dims.GetEnumerator(); StringBuilder sb = new StringBuilder("["); if (it.MoveNext()) { sb.Append(it.Current); } while (it.MoveNext()) { sb.Append(", "); sb.Append(it.Current); } sb.Append(']'); return sb.ToString(); } } class Program { static double[] DoubleArray(uint size) { double[] result = new double[size]; for (int i = 0; i < size; i++) { result[i] = 0.0; } return result; } static Vector E(int n) { if (n > 4) { throw new ArgumentException("n must be less than 5"); } var result = new Vector(DoubleArray(32)); result[1 << n] = 1.0; return result; } static readonly Random r = new Random(); static Vector RandomVector() { var result = new Vector(DoubleArray(32)); for (int i = 0; i < 5; i++) { var singleton = new double[] { r.NextDouble() }; result += new Vector(singleton) * E(i); } return result; } static Vector RandomMultiVector() { var result = new Vector(DoubleArray(32)); for (int i = 0; i < result.Length; i++) { result[i] = r.NextDouble(); } return result; } static void Main() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i < j) { if (E(i).Dot(E(j))[0] != 0.0) { Console.WriteLine("Unexpected non-null sclar product."); return; } } else if (i == j) { if ((E(i).Dot(E(j)))[0] == 0.0) { Console.WriteLine("Unexpected null sclar product."); } } } } var a = RandomMultiVector(); var b = RandomMultiVector(); var c = RandomMultiVector(); var x = RandomVector(); Console.WriteLine((a * b) * c); Console.WriteLine(a * (b * c)); Console.WriteLine(); Console.WriteLine(a * (b + c)); Console.WriteLine(a * b + a * c); Console.WriteLine(); Console.WriteLine((a + b) * c); Console.WriteLine(a * c + b * c); Console.WriteLine(); Console.WriteLine(x * x); } } }
vzero=: 1 $.2^31+IF64*32 odim=. 2^.#vzero ndx01=:1 :0 : n=. #x,.m x ((i.n),&.> m)} n#,:y ) clean=: (2;i.@#@$) $. ] gmul=:4 :0"1 xj=. ,4$.x yj=. ,4$.y if. 0= xj *&# yj do. vzero return. end. b=. (-##:>./0,xj,yj)&{."1@#: xb=. b xj yb=. b yj rj=. ,#.xb~:"1/yb s=. ,_1^ ~:/"1 yb *"1/ 0,.}:"1 ~:/\"1 xb vzero (~.rj)}~ rj +//. s*,(xj{x)*/yj{y ) gdot=: (gmul + gmul~) % 2: obasis=:1 (2^i.odim)ndx01 vzero e=: {&obasis
Rewrite this program in J while keeping its functionality equivalent to the C# version.
using System; using System.Collections.Generic; using System.Linq; namespace cppfpe { class Program { static int n, ns; static long[] AnyR; static long[] nFlip; static long[] Frees; static int[] fChk, fCkR; static int fSiz, fWid; static int[] dirs; static int[] rotO, rotX, rotY; static List<string> polys; static int target; static int clipAt; static int Main(string[] args) { polys = new List<string>(); n = 11; if (!(args.Length == 0)) int.TryParse(args[0], out n); if (n < 1 || n > 24) return 1; target = 5; Console.WriteLine("Counting polyominoes to rank {0}...", n); clipAt = 120; DateTime start = DateTime.Now; CountEm(); TimeSpan ti = DateTime.Now - start; if (polys.Count > 0) { Console.WriteLine("Displaying rank {0}:", target); Console.WriteLine(Assemble(polys)); } Console.WriteLine("Displaying results:"); Console.WriteLine(" n All Rotations Non-Flipped Free Polys"); for (int i = 1; i <= n; i++) Console.WriteLine("{0,2}Β :{1,17}{2,16}{3,16}", i, AnyR[i], nFlip[i], Frees[i]); Console.WriteLine(string.Format("Elasped: {0,2}d {1,2}h {2,2}m {3:00}s {4:000}ms", ti.Days, ti.Hours, ti.Minutes, ti.Seconds, ti.Milliseconds).Replace(" 0d ", "") .Replace(" 0h", "").Replace(" 0m", "").Replace(" 00s", "")); long ms = (long)ti.TotalMilliseconds, lim = int.MaxValue >> 2; if (ms > 250) { Console.WriteLine("Estimated completion times:"); for (int i = n + 1; i <= n + 10; i++) { if (ms >= lim) break; ms += 44; ms <<= 2; ti = TimeSpan.FromMilliseconds(ms); Console.WriteLine("{0,2}Β : {1,2}d {2,2}h {3,2}m {4:00}.{5:000}s", i, ti.Days, ti.Hours, ti.Minutes, ti.Seconds, ti.Milliseconds); } } if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey(); return 0; } static void CountEm() { ns = n * n; AnyR = new long[n + 1]; nFlip = new long[n + 1]; Frees = new long[n + 1]; fWid = n * 2 - 2; fSiz = (n - 1) * (n - 1) * 2 + 1; int[] pnField = new int[fSiz]; int[] pnPutList = new int[fSiz]; fChk = new int[ns]; fCkR = new int[ns]; dirs = new int[] { 1, fWid, -1, -fWid }; rotO = new int[] { 0, n - 1, ns - 1, ns - n, n - 1, 0, ns - n, ns - 1 }; rotX = new int[] { 1, n, -1, -n, -1, n, 1, -n }; rotY = new int[] { n, -1, -n, 1, n, 1, -n, -1 }; Recurse(0, pnField, pnPutList, 0, 1); } static void Recurse(int lv, int[] field, int[] putlist, int putno, int putlast) { CheckIt(field, lv); if (n == lv) return; int pos; for (int i = putno; i < putlast; i++) { field[pos = putlist[i]] |= 1; int k = 0; foreach (int dir in dirs) { int pos2 = pos + dir; if (0 <= pos2 && pos2 < fSiz && (field[pos2] == 0)) { field[pos2] = 2; putlist[putlast + k++] = pos2; } } Recurse(lv + 1, field, putlist, i + 1, putlast + k); for (int j = 0; j < k; j++) field[putlist[putlast + j]] = 0; field[pos] = 2; } for (int i = putno; i < putlast; i++) field[putlist[i]] &= -2; } static void CheckIt(int[] field, int lv) { AnyR[lv]++; for (int i = 0; i < ns; i++) fChk[i] = 0; int x, y; for (x = n; x < fWid; x++) for (y = 0; y + x < fSiz; y += fWid) if ((field[x + y] & 1) == 1) goto bail; bail: int x2 = n - x, t; for (int i = 0; i < fSiz; i++) if ((field[i] & 1) == 1) fChk[((t = (i + n - 2)) % fWid) + x2 + (t / fWid * n)] = 1; int of1; for (of1 = 0; of1 < fChk.Length && (fChk[of1] == 0); of1++) ; bool c = true; int r; for (r = 1; r < 8 && c; r++) { for (x = 0; x < n; x++) for (y = 0; y < n; y++) fCkR[rotO[r] + rotX[r] * x + rotY[r] * y] = fChk[x + y * n]; int of2; for (of2 = 0; of2 < fCkR.Length && (fCkR[of2] == 0); of2++) ; of2 -= of1; for (int i = of1; i < ns - ((of2 > 0) ? of2 : 0); i++) { if (fChk[i] > fCkR[i + of2]) break; if (fChk[i] < fCkR[i + of2]) { c = false; break; } } } if (r > 4) nFlip[lv]++; if (c) { if (lv == target) polys.Add(toStr(field.ToArray())); Frees[lv]++; } } static string toStr(int[] field) { char [] res = new string(' ', n * (fWid + 1) - 1).ToCharArray(); for (int i = fWid; i < res.Length; i += fWid+1) res[i] = '\n'; for (int i = 0, j = n - 2; i < field.Length; i++, j++) { if ((field[i] & 1) == 1) res[j] = '#'; if (j % (fWid + 1) == fWid) i--; } List<string> t = new string(res).Split('\n').ToList(); int nn = 100, m = 0, v, k = 0; foreach (string s in t) { if ((v = s.IndexOf('#')) < nn) if (v >= 0) nn = v; if ((v = s.LastIndexOf('#')) > m) if (v < fWid +1) m = v; if (v < 0) break; k++; } m = m - nn + 1; for (int i = t.Count - 1; i >= 0; i--) { if (i >= k) t.RemoveAt(i); else t[i] = t[i].Substring(nn, m); } return String.Join("\n", t.ToArray()); } static string Assemble(List<string> p) { List<string> lines = new List<string>(); for (int i = 0; i < target; i++) lines.Add(string.Empty); foreach (string poly in p) { List<string> t = poly.Split('\n').ToList(); if (t.Count < t[0].Length) t = flipXY(t); for (int i = 0; i < lines.Count; i++) lines[i] += (i < t.Count) ? ' ' + t[i] + ' ': new string(' ', t[0].Length + 2); } for (int i = lines.Count - 1; i > 0; i--) if (lines[i].IndexOf('#') < 0) lines.RemoveAt(i); if (lines[0].Length >= clipAt / 2-2) Wrap(lines, clipAt / 2-2); lines = Cornered(string.Join("\n", lines.ToArray())).Split('\n').ToList(); return String.Join("\n", lines.ToArray()); } static List<string> flipXY(List<string> p) { List<string> res = new List<string>(); for (int i = 0; i < p[0].Length; i++) res.Add(string.Empty); for (int i = 0; i < res.Count; i++) for(int j = 0; j < p.Count; j++) res[i] += p[j][i]; return res; } static string DW(string s) { string t = string.Empty; foreach (char c in s) t += string.Format("{0}{0}",c); return t; } static void Wrap(List<string> s, int w) { int last = 0; while (s.Last().Length >= w) { int x = w, lim = s.Count; bool ok; do { ok = true; for (int i = last; i < lim; i++) if (s[i][x] != ' ') { ok = false; x--; break; } } while (!ok); for (int i = last; i < lim; i++) if (s[i].Length > x) { s.Add(s[i].Substring(x)); s[i] = s[i].Substring(0, x + 1); } last = lim; } last = 0; for (int i = s.Count - 1; i > 0; i--) if ((last = (s[i].IndexOf('#') < 0) ? last + 1 : 0) > 1) s.RemoveAt(i + 1); } static string Cornered(string s) { string[] lines = s.Split('\n'); string res = string.Empty; string line = DW(new string(' ', lines[0].Length)), last; for (int i = 0; i < lines.Length; i++) { last = line; line = DW(lines[i]); res += Puzzle(last, line) + '\n'; } res += Puzzle(line, DW(new string(' ', lines.Last().Length))) + '\n'; return res; } static string Puzzle(string a, string b) { string res = string.Empty; if (a.Length > b.Length) b += new string(' ', a.Length - b.Length); if (a.Length < b.Length) a += new string(' ', b.Length - a.Length); for (int i = 0; i < a.Length - 1; i++) res += " 12β””4β”˜β”€β”΄8β”‚β”Œβ”œβ”β”€β”¬β”Ό"[(a[i] == a[i + 1] ? 0 : 1) + (b[i + 1] == a[i + 1] ? 0 : 2) + (a[i] == b[i] ? 0 : 4) + (b[i] == b[i + 1] ? 0 : 8)]; return res; } } }
polyominoes=:verb define if. 1>y do. i.0 0 0 return.end. if. 1=y do. 1 1 1$'#' return.end. }.~.' ',simplify ,/extend"2 polyominoes y-1 ) extend=:verb define reps=. ' ',"1~~.all y simplify ,/extend1"2 reps ) extend1=:verb define b=. (i.#y),._1|."1 '# ' E."1 y simplify ,/b extend2"1 _ y ) extend2=:verb define : row=.{.x mask=.}.x row mask extend3 y&>1+i.+/mask ) extend3=:conjunction define : '#' (<x,I.m*y=+/\m)} n ) simplify=:verb define t=. ~.trim"2 y t #~ +./"1 ((2{.$) $ (i.@# = i.~)@(,/)) all@trim"2 t ) flip=: |."_1 all=: , flip@|:, |.@flip, |.@|:, |., |.@flip@|:, flip,: |: trim=:verb define&|:^:2 y#~+./"1 y~:' ' )
Maintain the same structure and functionality when rewriting this code in J.
using System; namespace ParticleSwarmOptimization { public struct Parameters { public double omega, phip, phig; public Parameters(double omega, double phip, double phig) : this() { this.omega = omega; this.phip = phip; this.phig = phig; } } public struct State { public int iter; public double[] gbpos; public double gbval; public double[] min; public double[] max; public Parameters parameters; public double[][] pos; public double[][] vel; public double[][] bpos; public double[] bval; public int nParticles; public int nDims; public State(int iter, double[] gbpos, double gbval, double[] min, double[] max, Parameters parameters, double[][] pos, double[][] vel, double[][] bpos, double[] bval, int nParticles, int nDims) : this() { this.iter = iter; this.gbpos = gbpos; this.gbval = gbval; this.min = min; this.max = max; this.parameters = parameters; this.pos = pos; this.vel = vel; this.bpos = bpos; this.bval = bval; this.nParticles = nParticles; this.nDims = nDims; } public void Report(string testfunc) { Console.WriteLine("Test Function Β : {0}", testfunc); Console.WriteLine("Iterations Β : {0}", iter); Console.WriteLine("Global Best PositionΒ : {0}", string.Join(", ", gbpos)); Console.WriteLine("Global Best Value Β : {0}", gbval); } } class Program { public static State PsoInit(double[] min, double[] max, Parameters parameters, int nParticles) { var nDims = min.Length; double[][] pos = new double[nParticles][]; for (int i = 0; i < nParticles; i++) { pos[i] = new double[min.Length]; min.CopyTo(pos[i], 0); } double[][] vel = new double[nParticles][]; for (int i = 0; i < nParticles; i++) { vel[i] = new double[nDims]; } double[][] bpos = new double[nParticles][]; for (int i = 0; i < nParticles; i++) { bpos[i] = new double[min.Length]; min.CopyTo(bpos[i], 0); } double[] bval = new double[nParticles]; for (int i = 0; i < nParticles; i++) { bval[i] = double.PositiveInfinity; } int iter = 0; double[] gbpos = new double[nDims]; for (int i = 0; i < nDims; i++) { gbpos[i] = double.PositiveInfinity; } double gbval = double.PositiveInfinity; return new State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims); } static Random r = new Random(); public static State Pso(Func<double[], double> fn, State y) { var p = y.parameters; double[] v = new double[y.nParticles]; double[][] bpos = new double[y.nParticles][]; for (int i = 0; i < y.nParticles; i++) { bpos[i] = new double[y.min.Length]; y.min.CopyTo(bpos[i], 0); } double[] bval = new double[y.nParticles]; double[] gbpos = new double[y.nDims]; double gbval = double.PositiveInfinity; for (int j = 0; j < y.nParticles; j++) { v[j] = fn.Invoke(y.pos[j]); if (v[j] < y.bval[j]) { y.pos[j].CopyTo(bpos[j], 0); bval[j] = v[j]; } else { y.bpos[j].CopyTo(bpos[j], 0); bval[j] = y.bval[j]; } if (bval[j] < gbval) { gbval = bval[j]; bpos[j].CopyTo(gbpos, 0); } } double rg = r.NextDouble(); double[][] pos = new double[y.nParticles][]; double[][] vel = new double[y.nParticles][]; for (int i = 0; i < y.nParticles; i++) { pos[i] = new double[y.nDims]; vel[i] = new double[y.nDims]; } for (int j = 0; j < y.nParticles; j++) { double rp = r.NextDouble(); bool ok = true; for (int k = 0; k < y.nDims; k++) { vel[j][k] = 0.0; pos[j][k] = 0.0; } for (int k = 0; k < y.nDims; k++) { vel[j][k] = p.omega * y.vel[j][k] + p.phip * rp * (bpos[j][k] - y.pos[j][k]) + p.phig * rg * (gbpos[k] - y.pos[j][k]); pos[j][k] = y.pos[j][k] + vel[j][k]; ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k]; } if (!ok) { for (int k = 0; k < y.nDims; k++) { pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * r.NextDouble(); } } } var iter = 1 + y.iter; return new State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims); } public static State Iterate(Func<double[], double> fn, int n, State y) { State r = y; if (n == int.MaxValue) { State old = y; while (true) { r = Pso(fn, r); if (r.Equals(old)) break; old = r; } } else { for (int i = 0; i < n; i++) { r = Pso(fn, r); } } return r; } public static double Mccormick(double[] x) { var a = x[0]; var b = x[1]; return Math.Sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a; } public static double Michalewicz(double[] x) { int m = 10; int d = x.Length; double sum = 0.0; for (int i = 1; i < d; i++) { var j = x[i - 1]; var k = Math.Sin(i * j * j / Math.PI); sum += Math.Sin(j) * Math.Pow(k, 2.0 * m); } return -sum; } static void Main(string[] args) { var state = PsoInit( new double[] { -1.5, -3.0 }, new double[] { 4.0, 4.0 }, new Parameters(0.0, 0.6, 0.3), 100 ); state = Iterate(Mccormick, 40, state); state.Report("McCormick"); Console.WriteLine("f(-.54719, -1.54719)Β : {0}", Mccormick(new double[] { -.54719, -1.54719 })); Console.WriteLine(); state = PsoInit( new double[] { -0.0, -0.0 }, new double[] { Math.PI, Math.PI }, new Parameters(0.3, 0.3, 0.3), 1000 ); state = Iterate(Michalewicz, 30, state); state.Report("Michalewicz (2D)"); Console.WriteLine("f(2.20, 1.57) Β : {0}", Michalewicz(new double[] { 2.20, 1.57 })); } } }
load 'format/printf' pso_init =: verb define 'Min Max parameters nParticles' =. y 'Min: %j\nMax: %j\nomega, phip, phig: %j\nnParticles: %j\n' printf Min;Max;parameters;nParticles nDims =. #Min pos =. Min +"1 (Max - Min) *"1 (nParticles,nDims) ?@$ 0 bpos =. pos bval =. (#pos) $ _ vel =. ($pos) $ 0 0;_;_;Min;Max;parameters;pos;vel;bpos;bval ) pso =: adverb define 'iter gbpos gbval Min Max parameters pos vel bpos0 bval' =. y val =. u"1 pos better =. val < bval bpos =. (better # pos) (I. better)} bpos0 bval =. u"1 bpos gbval =. <./ bval gbpos =. bpos {~ (i. <./) bval 'omega phip phig' =. parameters rp =. (#pos) ?@$ 0 rg =. ? 0 vel =. (omega*vel) + (phip * rp * bpos - pos) + (phig * rg * gbpos -"1 pos) pos =. pos + vel bad =. +./"1 (Min >"1 pos) ,. (pos >"1 Max) newpos =. Min +"1 (Max-Min) *"1 ((+/bad),#Min) ?@$ 0 pos =. newpos (I. bad)} pos iter =. >: iter iter;gbpos;gbval;Min;Max;parameters;pos;vel;bpos;bval ) reportState=: 'Iteration: %j\nGlobalBestPosition: %j\nGlobalBestValue: %j\n' printf 3&{.
Translate the given C# code snippet into J without altering its behavior.
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.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; } if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; } d.tp += s.tp; } static void dec(ref LI d, LI s) { if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; } if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; } if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; } if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; } d.tp -= s.tp; } static LI set(long s) { LI d; d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; } static string fmt(LI x) { if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm); if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm); if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm); if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm); return x.lo.ToString(); } static LI partcount(int n) { var P = new LI[n + 1]; P[0] = set(1); for (int i = 1; i <= n; i++) { int k = 0, d = -2, j = i; LI x = set(0); while (true) { if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break; if ((j -= ++k) >= 0) inc(ref x, P[j]); else break; if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break; if ((j -= ++k) >= 0) dec(ref x, P[j]); else break; } P[i] = x; } return P[n]; } static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew (); var res = partcount(6666); sw.Stop(); Console.Write("{0} {1} ms", fmt(res), sw.Elapsed.TotalMilliseconds); } }
pn =: -/@(+/)@:($:"0)@rec ` (x:@(0&=)) @. (0>:]) M. rec=: - (-: (*"1) _1 1 +/ 3 * ]) @ (>:@i.@>.@%:@((2%3)&*))
Convert the following code from C# to J, 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() { const int LIMIT = 200; int row = 0; int num = 0; for (int n = 1; n < LIMIT; n++) { bool flag = true; int revNum = Reverse(n); for (int m = 1; m < n / 2; m++) { int revDiv = Reverse(m); if (n % m == 0) { if (revNum % revDiv == 0) { flag = true; } else { flag = false; break; } } } if (flag) { num++; row++; Console.Write("{0,4}", n); if (row % 10 == 0) { Console.WriteLine(); } } } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Found {0} special divisors N that reverse(D) divides reverse(N) for all divisors D of N, where N < 200", num); } } }
([#~([:*./0=|.&.":"0@>:@I.@(0=>:@i.|])||.&.":)"0)>:i.200
Transform the following C# implementation into J, maintaining the same output and logic.
using System; using System.Collections.Generic; using System.Linq; namespace SyntheticDivision { class Program { static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor) { List<int> output = dividend.ToList(); int normalizer = divisor[0]; for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++) { output[i] /= normalizer; int coef = output[i]; if (coef != 0) { for (int j = 1; j < divisor.Count(); j++) output[i + j] += -divisor[j] * coef; } } int separator = output.Count() - (divisor.Count() - 1); return ( output.GetRange(0, separator), output.GetRange(separator, output.Count() - separator) ); } static void Main(string[] args) { List<int> N = new List<int>{ 1, -12, 0, -42 }; List<int> D = new List<int> { 1, -3 }; var (quotient, remainder) = extendedSyntheticDivision(N, D); Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" , string.Join(",", N), string.Join(",", D), string.Join(",", quotient), string.Join(",", remainder) ); } } }
psd=: [:(}. ;{.) ([ (] -/@,:&}. (* {:)) ] , %&{.~)^:(>:@-~&#)~
Rewrite the snippet below in J so it works the same as the original C# code.
using System; using System.Collections.Generic; using System.Linq; namespace SyntheticDivision { class Program { static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor) { List<int> output = dividend.ToList(); int normalizer = divisor[0]; for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++) { output[i] /= normalizer; int coef = output[i]; if (coef != 0) { for (int j = 1; j < divisor.Count(); j++) output[i + j] += -divisor[j] * coef; } } int separator = output.Count() - (divisor.Count() - 1); return ( output.GetRange(0, separator), output.GetRange(separator, output.Count() - separator) ); } static void Main(string[] args) { List<int> N = new List<int>{ 1, -12, 0, -42 }; List<int> D = new List<int> { 1, -3 }; var (quotient, remainder) = extendedSyntheticDivision(N, D); Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" , string.Join(",", N), string.Join(",", D), string.Join(",", quotient), string.Join(",", remainder) ); } } }
psd=: [:(}. ;{.) ([ (] -/@,:&}. (* {:)) ] , %&{.~)^:(>:@-~&#)~
Change the following C# code into J without altering its purpose.
public MainWindow() { InitializeComponent(); RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality); imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null); DrawHue(100); } void DrawHue(int saturation) { var bmp = (WriteableBitmap)imgMain.Source; int centerX = (int)bmp.Width / 2; int centerY = (int)bmp.Height / 2; int radius = Math.Min(centerX, centerY); int radius2 = radius - 40; bmp.Lock(); unsafe{ var buf = bmp.BackBuffer; IntPtr pixLineStart; for(int y=0; y < bmp.Height; y++){ pixLineStart = buf + bmp.BackBufferStride * y; double dy = (y - centerY); for(int x=0; x < bmp.Width; x++){ double dx = (x - centerX); double dist = Math.Sqrt(dx * dx + dy * dy); if (radius2 <= dist && dist <= radius) { double theta = Math.Atan2(dy, dx); double hue = (theta + Math.PI) / (2.0 * Math.PI); *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100); } } } } bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480)); bmp.Unlock(); } static int HSB_to_RGB(int h, int s, int v) { var rgb = new int[3]; var baseColor = (h + 60) % 360 / 120; var shift = (h + 60) % 360 - (120 * baseColor + 60 ); var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3; rgb[baseColor] = 255; rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f); for (var i = 0; i < 3; i++) rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f)); for (var i = 0; i < 3; i++) rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f); return RGB2int(rgb[0], rgb[1], rgb[2]); } public static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;
rgbc=: {{1-x*0>.1<.(<.4&-)6|m+y%60}} hsv=: 5 rgbc(,"0 1) 3 rgbc(,"0) 1 rgbc degrees=: {{180p_1*{:"1+.^.y}} wheel=: {{((1>:|)*|hsv degrees)j./~y%~i:y}} require'viewmat' 'rgb' viewmat 256#.<.255*wheel 400
Generate an equivalent J version of this C# code.
using System; using System.Collections.Generic; using System.Linq; using static System.Console; class Program { static string fmt(int[] a) { var sb = new System.Text.StringBuilder(); for (int i = 0; i < a.Length; i++) sb.Append(string.Format("{0,5}{1}", a[i], i % 10 == 9 ? "\n" : " ")); return sb.ToString(); } static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew(); var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray(); sw.Stop(); Write("The first 100 odd prime numbers:\n{0}\n", fmt(pr.Take(100).ToArray())); Write("The millionth odd prime number: {0}", pr.Last()); Write("\n{0} ms", sw.Elapsed.TotalMilliseconds); } } class PG { public static IEnumerable<int> Sundaram(int n) { int i = 1, k = (n + 1) >> 1, t = 1, v = 1, d = 1, s = 1; var comps = new bool[k + 1]; for (; t < k; t = ((++i + (s += d += 2)) << 1) - d - 2) while ((t += d + 2) < k) comps[t] = true; for (; v < k; v++) if (!comps[v]) yield return (v << 1) + 1; } }
sundaram=: {{ sieve=. -.1{.~k=. <.1.2*(*^.) y for_i. 1+i.y do. f=. 1+2*i j=. (#~ k > ]) (i,f) p. i+i.<.k%f if. 0=#j do. y{.1+2*I. sieve return. end. sieve=. 0 j} sieve end. }}