Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate this program into J but keep the logic exactly as in C#.
using System.Linq; using System.Collections.Generic; using TG = System.Tuple<int, int>; using static System.Console; class Program { static void Main(string[] args) { const int mil = (int)1e6; foreach (var amt in new int[] { 1, 2, 6, 12, 18 }) { int lmt = mil * amt, lg = 0, ng, d, ld = 0; var desc = new string[] { "A", "", "De" }; int[] mx = new int[] { 0, 0, 0 }, bi = new int[] { 0, 0, 0 }, c = new int[] { 2, 2, 2 }; WriteLine("For primes up to {0:n0}:", lmt); var pr = PG.Primes(lmt).ToArray(); for (int i = 0; i < pr.Length; i++) { ng = pr[i].Item2; d = ng.CompareTo(lg) + 1; if (ld == d) c[2 - d]++; else { if (c[d] > mx[d]) { mx[d] = c[d]; bi[d] = i - mx[d] - 1; } c[d] = 2; } ld = d; lg = ng; } for (int r = 0; r <= 2; r += 2) { Write("{0}scending, found run of {1} consecutive primes:\n {2} ", desc[r], mx[r] + 1, pr[bi[r]++].Item1); foreach (var itm in pr.Skip(bi[r]).Take(mx[r])) Write("({0}) {1} ", itm.Item2, itm.Item1); WriteLine(r == 0 ? "" : "\n"); } } } } class PG { public static IEnumerable<TG> Primes(int lim) { bool[] flags = new bool[lim + 1]; int j = 3, lj = 2; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return new TG(j, j - lj); lj = j; for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; } for (; j <= lim; j += 2) if (!flags[j]) { yield return new TG(j, j - lj); lj = j; } } }
;{.(\: #@>) tris <@~.@,;._1~ <:/ 2 -/\ |: tris=: 3 ]\ p: i. p:inv 1e6 128981 128983 128987 128993 129001 129011 129023 129037 ;{.(\: #@>) tris <@~.@,;._1~ >:/ 2 -/\ |: tris=: 3 ]\ p: i. p:inv 1e6 322171 322193 322213 322229 322237 322243 322247 322249
Change the programming language of this snippet from C# to J without modifying what it does.
using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static BI IntSqRoot(BI v, BI res) { BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1; dl = d; d = term - res; } return term; } static string doOne(int b, int digs) { int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)), bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g); bs += b * BI.Parse('1' + new string('0', digs)); bs >>= 1; bs += 4; string st = bs.ToString(); return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); } static string divIt(BI a, BI b, int digs) { int al = a.ToString().Length, bl = b.ToString().Length; a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs); string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); } static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; string res = ""; for (int i = 0; i < x.Length; i++) res += string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; } static void Main(string[] args) { WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc"); int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) { BI[] lst = new BI[15]; lst[0] = lst[1] = 1; for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2]; n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j; on = n; n = b * n + nm1; nm1 = on; } WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}\n{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb" .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), "", joined(lst)); } n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j; on = n; n += nm1; nm1 = on; } WriteLine("\nAu to 256 digits:"); WriteLine(t); WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t == doOne(1, 256)); } }
258j256":%~/+/+/ .*~^:10 x:*i.2 2 1.6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911374847540880753868917521266338622235369317931800607667263544333890865959395829056383226613199282902678806752087668925017116962070322210432162695486262963136144
Keep all operations the same but rewrite the snippet in J.
using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static BI IntSqRoot(BI v, BI res) { BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1; dl = d; d = term - res; } return term; } static string doOne(int b, int digs) { int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)), bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g); bs += b * BI.Parse('1' + new string('0', digs)); bs >>= 1; bs += 4; string st = bs.ToString(); return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); } static string divIt(BI a, BI b, int digs) { int al = a.ToString().Length, bl = b.ToString().Length; a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs); string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); } static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; string res = ""; for (int i = 0; i < x.Length; i++) res += string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; } static void Main(string[] args) { WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc"); int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) { BI[] lst = new BI[15]; lst[0] = lst[1] = 1; for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2]; n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j; on = n; n = b * n + nm1; nm1 = on; } WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}\n{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb" .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), "", joined(lst)); } n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j; on = n; n += nm1; nm1 = on; } WriteLine("\nAu to 256 digits:"); WriteLine(t); WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t == doOne(1, 256)); } }
258j256":%~/+/+/ .*~^:10 x:*i.2 2 1.6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911374847540880753868917521266338622235369317931800607667263544333890865959395829056383226613199282902678806752087668925017116962070322210432162695486262963136144
Please provide an equivalent version of this C# code in J.
using System; namespace Rosetta { internal class Vector { private double[] b; internal readonly int rows; internal Vector(int rows) { this.rows = rows; b = new double[rows]; } internal Vector(double[] initArray) { b = (double[])initArray.Clone(); rows = b.Length; } internal Vector Clone() { Vector v = new Vector(b); return v; } internal double this[int row] { get { return b[row]; } set { b[row] = value; } } internal void SwapRows(int r1, int r2) { if (r1 == r2) return; double tmp = b[r1]; b[r1] = b[r2]; b[r2] = tmp; } internal double norm(double[] weights) { double sum = 0; for (int i = 0; i < rows; i++) { double d = b[i] * weights[i]; sum += d*d; } return Math.Sqrt(sum); } internal void print() { for (int i = 0; i < rows; i++) Console.WriteLine(b[i]); Console.WriteLine(); } public static Vector operator-(Vector lhs, Vector rhs) { Vector v = new Vector(lhs.rows); for (int i = 0; i < lhs.rows; i++) v[i] = lhs[i] - rhs[i]; return v; } } class Matrix { private double[] b; internal readonly int rows, cols; internal Matrix(int rows, int cols) { this.rows = rows; this.cols = cols; b = new double[rows * cols]; } internal Matrix(int size) { this.rows = size; this.cols = size; b = new double[rows * cols]; for (int i = 0; i < size; i++) this[i, i] = 1; } internal Matrix(int rows, int cols, double[] initArray) { this.rows = rows; this.cols = cols; b = (double[])initArray.Clone(); if (b.Length != rows * cols) throw new Exception("bad init array"); } internal double this[int row, int col] { get { return b[row * cols + col]; } set { b[row * cols + col] = value; } } public static Vector operator*(Matrix lhs, Vector rhs) { if (lhs.cols != rhs.rows) throw new Exception("I can't multiply matrix by vector"); Vector v = new Vector(lhs.rows); for (int i = 0; i < lhs.rows; i++) { double sum = 0; for (int j = 0; j < rhs.rows; j++) sum += lhs[i,j]*rhs[j]; v[i] = sum; } return v; } internal void SwapRows(int r1, int r2) { if (r1 == r2) return; int firstR1 = r1 * cols; int firstR2 = r2 * cols; for (int i = 0; i < cols; i++) { double tmp = b[firstR1 + i]; b[firstR1 + i] = b[firstR2 + i]; b[firstR2 + i] = tmp; } } internal bool InvPartial() { const double Eps = 1e-12; if (rows != cols) throw new Exception("rows != cols for Inv"); Matrix M = new Matrix(rows); for (int diag = 0; diag < rows; diag++) { int max_row = diag; double max_val = Math.Abs(this[diag, diag]); double d; for (int row = diag + 1; row < rows; row++) if ((d = Math.Abs(this[row, diag])) > max_val) { max_row = row; max_val = d; } if (max_val <= Eps) return false; SwapRows(diag, max_row); M.SwapRows(diag, max_row); double invd = 1 / this[diag, diag]; for (int col = diag; col < cols; col++) { this[diag, col] *= invd; } for (int col = 0; col < cols; col++) { M[diag, col] *= invd; } for (int row = 0; row < rows; row++) { d = this[row, diag]; if (row != diag) { for (int col = diag; col < this.cols; col++) { this[row, col] -= d * this[diag, col]; } for (int col = 0; col < this.cols; col++) { M[row, col] -= d * M[diag, col]; } } } } b = M.b; return true; } internal void print() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) Console.Write(this[i,j].ToString()+" "); Console.WriteLine(); } } } }
require 'math/misc/linear' augmentR_I1=: ,. e.@i.@# matrix_invGJ=: # }."1 [: gauss_jordan@augmentR_I1
Change the following C# code into J without altering its purpose.
using System; namespace Rosetta { internal class Vector { private double[] b; internal readonly int rows; internal Vector(int rows) { this.rows = rows; b = new double[rows]; } internal Vector(double[] initArray) { b = (double[])initArray.Clone(); rows = b.Length; } internal Vector Clone() { Vector v = new Vector(b); return v; } internal double this[int row] { get { return b[row]; } set { b[row] = value; } } internal void SwapRows(int r1, int r2) { if (r1 == r2) return; double tmp = b[r1]; b[r1] = b[r2]; b[r2] = tmp; } internal double norm(double[] weights) { double sum = 0; for (int i = 0; i < rows; i++) { double d = b[i] * weights[i]; sum += d*d; } return Math.Sqrt(sum); } internal void print() { for (int i = 0; i < rows; i++) Console.WriteLine(b[i]); Console.WriteLine(); } public static Vector operator-(Vector lhs, Vector rhs) { Vector v = new Vector(lhs.rows); for (int i = 0; i < lhs.rows; i++) v[i] = lhs[i] - rhs[i]; return v; } } class Matrix { private double[] b; internal readonly int rows, cols; internal Matrix(int rows, int cols) { this.rows = rows; this.cols = cols; b = new double[rows * cols]; } internal Matrix(int size) { this.rows = size; this.cols = size; b = new double[rows * cols]; for (int i = 0; i < size; i++) this[i, i] = 1; } internal Matrix(int rows, int cols, double[] initArray) { this.rows = rows; this.cols = cols; b = (double[])initArray.Clone(); if (b.Length != rows * cols) throw new Exception("bad init array"); } internal double this[int row, int col] { get { return b[row * cols + col]; } set { b[row * cols + col] = value; } } public static Vector operator*(Matrix lhs, Vector rhs) { if (lhs.cols != rhs.rows) throw new Exception("I can't multiply matrix by vector"); Vector v = new Vector(lhs.rows); for (int i = 0; i < lhs.rows; i++) { double sum = 0; for (int j = 0; j < rhs.rows; j++) sum += lhs[i,j]*rhs[j]; v[i] = sum; } return v; } internal void SwapRows(int r1, int r2) { if (r1 == r2) return; int firstR1 = r1 * cols; int firstR2 = r2 * cols; for (int i = 0; i < cols; i++) { double tmp = b[firstR1 + i]; b[firstR1 + i] = b[firstR2 + i]; b[firstR2 + i] = tmp; } } internal bool InvPartial() { const double Eps = 1e-12; if (rows != cols) throw new Exception("rows != cols for Inv"); Matrix M = new Matrix(rows); for (int diag = 0; diag < rows; diag++) { int max_row = diag; double max_val = Math.Abs(this[diag, diag]); double d; for (int row = diag + 1; row < rows; row++) if ((d = Math.Abs(this[row, diag])) > max_val) { max_row = row; max_val = d; } if (max_val <= Eps) return false; SwapRows(diag, max_row); M.SwapRows(diag, max_row); double invd = 1 / this[diag, diag]; for (int col = diag; col < cols; col++) { this[diag, col] *= invd; } for (int col = 0; col < cols; col++) { M[diag, col] *= invd; } for (int row = 0; row < rows; row++) { d = this[row, diag]; if (row != diag) { for (int col = diag; col < this.cols; col++) { this[row, col] -= d * this[diag, col]; } for (int col = 0; col < this.cols; col++) { M[row, col] -= d * M[diag, col]; } } } } b = M.b; return true; } internal void print() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) Console.Write(this[i,j].ToString()+" "); Console.WriteLine(); } } } }
require 'math/misc/linear' augmentR_I1=: ,. e.@i.@# matrix_invGJ=: # }."1 [: gauss_jordan@augmentR_I1
Write a version of this C# function in J with identical behavior.
using System; class Program { static bool dc8(uint n) { uint res = 1, count, p, d; for ( ; (n & 1) == 0; n >>= 1) res++; for (count = 1; n % 3 == 0; n /= 3) count++; for (p = 5, d = 4; p * p <= n; p += d = 6 - d) for (res *= count, count = 1; n % p == 0; n /= p) count++; return n > 1 ? res * count == 4 : res * count == 8; } static void Main(string[] args) { Console.WriteLine("First 50 numbers which are the cube roots of the products of " + "their proper divisors:"); for (uint n = 1, count = 0, lmt = 500; count < 5e6; ++n) if (n == 1 || dc8(n)) if (++count <= 50) Console.Write("{0,3}{1}",n, count % 10 == 0 ? '\n' : ' '); else if (count == lmt) Console.Write("{0,16:n0}th: {1:n0}\n", count, n, lmt *= 10); } }
F=: 1 8 e.~_ */@:>:@q:"0 ]
Can you help me rewrite this code in J instead of C#, keeping it the same logically?
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using IntMap = System.Collections.Generic.Dictionary<int, int>; public static class CyclotomicPolynomial { public static void Main2() { Console.WriteLine("Task 1: Cyclotomic polynomials for n <= 30:"); for (int i = 1; i <= 30; i++) { var p = GetCyclotomicPolynomial(i); Console.WriteLine($"CP[{i}] = {p.ToString()}"); } Console.WriteLine(); Console.WriteLine("Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:"); for (int i = 1, n = 0; i <= 10; i++) { while (true) { n++; var p = GetCyclotomicPolynomial(n); if (p.Any(t => Math.Abs(t.Coefficient) == i)) { Console.WriteLine($"CP[{n}] has coefficient with magnitude = {i}"); n--; break; } } } } private const int MaxFactors = 100_000; private const int Algorithm = 2; private static readonly Term x = new Term(1, 1); private static readonly Dictionary<int, Polynomial> polyCache = new Dictionary<int, Polynomial> { [1] = x - 1 }; private static readonly Dictionary<int, IntMap> factorCache = new Dictionary<int, IntMap> { [2] = new IntMap { [2] = 1 } }; private static Polynomial GetCyclotomicPolynomial(in int n) { if (polyCache.TryGetValue(n, out var result)) return result; var factors = GetFactors(n); if (factors.ContainsKey(n)) { result = new Polynomial(from exp in ..n select x[exp]); } else if (factors.Count == 2 && factors.Contains(2, 1) && factors.Contains(n/2, 1)) { result = new Polynomial(from i in ..(n/2) select (IsOdd(i) ? -x : x)[i]); } else if (factors.Count == 1 && factors.TryGetValue(2, out int h)) { result = x[1<<(h-1)] + 1; } else if (factors.Count == 1 && !factors.ContainsKey(n)) { (int p, int k) = factors.First(); result = new Polynomial(from i in ..p select x[i * (int)Math.Pow(p, k-1)]); } else if (factors.Count == 2 && factors.ContainsKey(2)) { (int p, int k) = factors.First(entry => entry.Key != 2); int twoExp = 1 << (factors[2] - 1); result = new Polynomial(from i in ..p select (IsOdd(i) ? -x : x)[i * twoExp * (int)Math.Pow(p, k-1)]); } else if (factors.ContainsKey(2) && IsOdd(n/2) && n/2 > 1) { Polynomial cycloDiv2 = GetCyclotomicPolynomial(n/2); result = new Polynomial(from term in cycloDiv2 select IsOdd(term.Exponent) ? -term : term); #pragma warning disable CS0162 } else if (Algorithm == 0) { var divisors = GetDivisors(n); result = x[n] - 1; foreach (int d in divisors) result /= GetCyclotomicPolynomial(d); } else if (Algorithm == 1) { var divisors = GetDivisors(n).ToList(); int maxDivisor = divisors.Max(); result = (x[n] - 1) / (x[maxDivisor] - 1); foreach (int d in divisors.Where(div => maxDivisor % div == 0)) { result /= GetCyclotomicPolynomial(d); } } else if (Algorithm == 2) { int m = 1; result = GetCyclotomicPolynomial(m); var primes = factors.Keys.ToList(); primes.Sort(); foreach (int prime in primes) { var cycloM = result; result = new Polynomial(from term in cycloM select term.Coefficient * x[term.Exponent * prime]); result /= cycloM; m *= prime; } int s = n / m; result = new Polynomial(from term in result select term.Coefficient * x[term.Exponent * s]); #pragma warning restore CS0162 } else { throw new InvalidOperationException("Invalid algorithm"); } polyCache[n] = result; return result; } private static bool IsOdd(int i) => (i & 1) != 0; private static bool Contains(this IntMap map, int key, int value) => map.TryGetValue(key, out int v) && v == value; private static int GetOrZero(this IntMap map, int key) => map.TryGetValue(key, out int v) ? v : 0; private static IEnumerable<T> Select<T>(this Range r, Func<int, T> f) => Enumerable.Range(r.Start.Value, r.End.Value - r.Start.Value).Select(f); private static IntMap GetFactors(in int n) { if (factorCache.TryGetValue(n, out var factors)) return factors; factors = new IntMap(); if (!IsOdd(n)) { foreach (var entry in GetFactors(n/2)) factors.Add(entry.Key, entry.Value); factors[2] = factors.GetOrZero(2) + 1; return Cache(n, factors); } for (int i = 3; i * i <= n; i+=2) { if (n % i == 0) { foreach (var entry in GetFactors(n/i)) factors.Add(entry.Key, entry.Value); factors[i] = factors.GetOrZero(i) + 1; return Cache(n, factors); } } factors[n] = 1; return Cache(n, factors); } private static IntMap Cache(int n, IntMap factors) { if (n < MaxFactors) factorCache[n] = factors; return factors; } private static IEnumerable<int> GetDivisors(int n) { for (int i = 1; i * i <= n; i++) { if (n % i == 0) { yield return i; int div = n / i; if (div != i && div != n) yield return div; } } } public sealed class Polynomial : IEnumerable<Term> { public Polynomial() { } public Polynomial(params Term[] terms) : this(terms.AsEnumerable()) { } public Polynomial(IEnumerable<Term> terms) { Terms.AddRange(terms); Simplify(); } private List<Term>? terms; private List<Term> Terms => terms ??= new List<Term>(); public int Count => terms?.Count ?? 0; public int Degree => Count == 0 ? -1 : Terms[0].Exponent; public int LeadingCoefficient => Count == 0 ? 0 : Terms[0].Coefficient; public IEnumerator<Term> GetEnumerator() => Terms.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public override string ToString() => Count == 0 ? "0" : string.Join(" + ", Terms).Replace("+ -", "- "); public static Polynomial operator *(Polynomial p, Term t) => new Polynomial(from s in p select s * t); public static Polynomial operator +(Polynomial p, Polynomial q) => new Polynomial(p.Terms.Concat(q.Terms)); public static Polynomial operator -(Polynomial p, Polynomial q) => new Polynomial(p.Terms.Concat(q.Terms.Select(t => -t))); public static Polynomial operator *(Polynomial p, Polynomial q) => new Polynomial(from s in p from t in q select s * t); public static Polynomial operator /(Polynomial p, Polynomial q) => p.Divide(q).quotient; public (Polynomial quotient, Polynomial remainder) Divide(Polynomial divisor) { if (Degree < 0) return (new Polynomial(), this); Polynomial quotient = new Polynomial(); Polynomial remainder = this; int lcv = divisor.LeadingCoefficient; int dv = divisor.Degree; while (remainder.Degree >= divisor.Degree) { int lcr = remainder.LeadingCoefficient; Term div = new Term(lcr / lcv, remainder.Degree - dv); quotient.Terms.Add(div); remainder += divisor * -div; } quotient.Simplify(); remainder.Simplify(); return (quotient, remainder); } private void Simplify() { if (Count < 2) return; Terms.Sort((a, b) => -a.CompareTo(b)); for (int i = Terms.Count - 1; i > 0; i--) { Term s = Terms[i-1]; Term t = Terms[i]; if (t.Exponent == s.Exponent) { Terms[i-1] = new Term(s.Coefficient + t.Coefficient, s.Exponent); Terms.RemoveAt(i); } } Terms.RemoveAll(t => t.IsZero); } } public readonly struct Term : IEquatable<Term>, IComparable<Term> { public Term(int coefficient, int exponent = 0) => (Coefficient, Exponent) = (coefficient, exponent); public Term this[int exponent] => new Term(Coefficient, exponent); public int Coefficient { get; } public int Exponent { get; } public bool IsZero => Coefficient == 0; public static Polynomial operator +(Term left, Term right) => new Polynomial(left, right); public static Polynomial operator -(Term left, Term right) => new Polynomial(left, -right); public static implicit operator Term(int coefficient) => new Term(coefficient); public static Term operator -(Term t) => new Term(-t.Coefficient, t.Exponent); public static Term operator *(Term left, Term right) => new Term(left.Coefficient * right.Coefficient, left.Exponent + right.Exponent); public static bool operator ==(Term left, Term right) => left.Equals(right); public static bool operator !=(Term left, Term right) => !left.Equals(right); public static bool operator <(Term left, Term right) => left.CompareTo(right) < 0; public static bool operator >(Term left, Term right) => left.CompareTo(right) > 0; public static bool operator <=(Term left, Term right) => left.CompareTo(right) <= 0; public static bool operator >=(Term left, Term right) => left.CompareTo(right) >= 0; public bool Equals(Term other) => Exponent == other.Exponent && Coefficient == other.Coefficient; public override bool Equals(object? obj) => obj is Term t && Equals(t); public override int GetHashCode() => Coefficient.GetHashCode() * 31 + Exponent.GetHashCode(); public int CompareTo(Term other) { int c = Exponent.CompareTo(other.Exponent); if (c != 0) return c; return Coefficient.CompareTo(other.Coefficient); } public override string ToString() => (Coefficient, Exponent) switch { (0, _) => "0", (_, 0) => $"{Coefficient}", (1, 1) => "x", (-1, 1) => "-x", (_, 1) => $"{Coefficient}x", (1, _) => $"x^{Exponent}", (-1, _) => $"-x^{Exponent}", _ => $"{Coefficient}x^{Exponent}" }; } }
cyclo=: {{<.-:1+(++) p. 1;^0j2p1* y%~1+I.1=y+.1+i.y}}
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 IntMap = System.Collections.Generic.Dictionary<int, int>; public static class CyclotomicPolynomial { public static void Main2() { Console.WriteLine("Task 1: Cyclotomic polynomials for n <= 30:"); for (int i = 1; i <= 30; i++) { var p = GetCyclotomicPolynomial(i); Console.WriteLine($"CP[{i}] = {p.ToString()}"); } Console.WriteLine(); Console.WriteLine("Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:"); for (int i = 1, n = 0; i <= 10; i++) { while (true) { n++; var p = GetCyclotomicPolynomial(n); if (p.Any(t => Math.Abs(t.Coefficient) == i)) { Console.WriteLine($"CP[{n}] has coefficient with magnitude = {i}"); n--; break; } } } } private const int MaxFactors = 100_000; private const int Algorithm = 2; private static readonly Term x = new Term(1, 1); private static readonly Dictionary<int, Polynomial> polyCache = new Dictionary<int, Polynomial> { [1] = x - 1 }; private static readonly Dictionary<int, IntMap> factorCache = new Dictionary<int, IntMap> { [2] = new IntMap { [2] = 1 } }; private static Polynomial GetCyclotomicPolynomial(in int n) { if (polyCache.TryGetValue(n, out var result)) return result; var factors = GetFactors(n); if (factors.ContainsKey(n)) { result = new Polynomial(from exp in ..n select x[exp]); } else if (factors.Count == 2 && factors.Contains(2, 1) && factors.Contains(n/2, 1)) { result = new Polynomial(from i in ..(n/2) select (IsOdd(i) ? -x : x)[i]); } else if (factors.Count == 1 && factors.TryGetValue(2, out int h)) { result = x[1<<(h-1)] + 1; } else if (factors.Count == 1 && !factors.ContainsKey(n)) { (int p, int k) = factors.First(); result = new Polynomial(from i in ..p select x[i * (int)Math.Pow(p, k-1)]); } else if (factors.Count == 2 && factors.ContainsKey(2)) { (int p, int k) = factors.First(entry => entry.Key != 2); int twoExp = 1 << (factors[2] - 1); result = new Polynomial(from i in ..p select (IsOdd(i) ? -x : x)[i * twoExp * (int)Math.Pow(p, k-1)]); } else if (factors.ContainsKey(2) && IsOdd(n/2) && n/2 > 1) { Polynomial cycloDiv2 = GetCyclotomicPolynomial(n/2); result = new Polynomial(from term in cycloDiv2 select IsOdd(term.Exponent) ? -term : term); #pragma warning disable CS0162 } else if (Algorithm == 0) { var divisors = GetDivisors(n); result = x[n] - 1; foreach (int d in divisors) result /= GetCyclotomicPolynomial(d); } else if (Algorithm == 1) { var divisors = GetDivisors(n).ToList(); int maxDivisor = divisors.Max(); result = (x[n] - 1) / (x[maxDivisor] - 1); foreach (int d in divisors.Where(div => maxDivisor % div == 0)) { result /= GetCyclotomicPolynomial(d); } } else if (Algorithm == 2) { int m = 1; result = GetCyclotomicPolynomial(m); var primes = factors.Keys.ToList(); primes.Sort(); foreach (int prime in primes) { var cycloM = result; result = new Polynomial(from term in cycloM select term.Coefficient * x[term.Exponent * prime]); result /= cycloM; m *= prime; } int s = n / m; result = new Polynomial(from term in result select term.Coefficient * x[term.Exponent * s]); #pragma warning restore CS0162 } else { throw new InvalidOperationException("Invalid algorithm"); } polyCache[n] = result; return result; } private static bool IsOdd(int i) => (i & 1) != 0; private static bool Contains(this IntMap map, int key, int value) => map.TryGetValue(key, out int v) && v == value; private static int GetOrZero(this IntMap map, int key) => map.TryGetValue(key, out int v) ? v : 0; private static IEnumerable<T> Select<T>(this Range r, Func<int, T> f) => Enumerable.Range(r.Start.Value, r.End.Value - r.Start.Value).Select(f); private static IntMap GetFactors(in int n) { if (factorCache.TryGetValue(n, out var factors)) return factors; factors = new IntMap(); if (!IsOdd(n)) { foreach (var entry in GetFactors(n/2)) factors.Add(entry.Key, entry.Value); factors[2] = factors.GetOrZero(2) + 1; return Cache(n, factors); } for (int i = 3; i * i <= n; i+=2) { if (n % i == 0) { foreach (var entry in GetFactors(n/i)) factors.Add(entry.Key, entry.Value); factors[i] = factors.GetOrZero(i) + 1; return Cache(n, factors); } } factors[n] = 1; return Cache(n, factors); } private static IntMap Cache(int n, IntMap factors) { if (n < MaxFactors) factorCache[n] = factors; return factors; } private static IEnumerable<int> GetDivisors(int n) { for (int i = 1; i * i <= n; i++) { if (n % i == 0) { yield return i; int div = n / i; if (div != i && div != n) yield return div; } } } public sealed class Polynomial : IEnumerable<Term> { public Polynomial() { } public Polynomial(params Term[] terms) : this(terms.AsEnumerable()) { } public Polynomial(IEnumerable<Term> terms) { Terms.AddRange(terms); Simplify(); } private List<Term>? terms; private List<Term> Terms => terms ??= new List<Term>(); public int Count => terms?.Count ?? 0; public int Degree => Count == 0 ? -1 : Terms[0].Exponent; public int LeadingCoefficient => Count == 0 ? 0 : Terms[0].Coefficient; public IEnumerator<Term> GetEnumerator() => Terms.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public override string ToString() => Count == 0 ? "0" : string.Join(" + ", Terms).Replace("+ -", "- "); public static Polynomial operator *(Polynomial p, Term t) => new Polynomial(from s in p select s * t); public static Polynomial operator +(Polynomial p, Polynomial q) => new Polynomial(p.Terms.Concat(q.Terms)); public static Polynomial operator -(Polynomial p, Polynomial q) => new Polynomial(p.Terms.Concat(q.Terms.Select(t => -t))); public static Polynomial operator *(Polynomial p, Polynomial q) => new Polynomial(from s in p from t in q select s * t); public static Polynomial operator /(Polynomial p, Polynomial q) => p.Divide(q).quotient; public (Polynomial quotient, Polynomial remainder) Divide(Polynomial divisor) { if (Degree < 0) return (new Polynomial(), this); Polynomial quotient = new Polynomial(); Polynomial remainder = this; int lcv = divisor.LeadingCoefficient; int dv = divisor.Degree; while (remainder.Degree >= divisor.Degree) { int lcr = remainder.LeadingCoefficient; Term div = new Term(lcr / lcv, remainder.Degree - dv); quotient.Terms.Add(div); remainder += divisor * -div; } quotient.Simplify(); remainder.Simplify(); return (quotient, remainder); } private void Simplify() { if (Count < 2) return; Terms.Sort((a, b) => -a.CompareTo(b)); for (int i = Terms.Count - 1; i > 0; i--) { Term s = Terms[i-1]; Term t = Terms[i]; if (t.Exponent == s.Exponent) { Terms[i-1] = new Term(s.Coefficient + t.Coefficient, s.Exponent); Terms.RemoveAt(i); } } Terms.RemoveAll(t => t.IsZero); } } public readonly struct Term : IEquatable<Term>, IComparable<Term> { public Term(int coefficient, int exponent = 0) => (Coefficient, Exponent) = (coefficient, exponent); public Term this[int exponent] => new Term(Coefficient, exponent); public int Coefficient { get; } public int Exponent { get; } public bool IsZero => Coefficient == 0; public static Polynomial operator +(Term left, Term right) => new Polynomial(left, right); public static Polynomial operator -(Term left, Term right) => new Polynomial(left, -right); public static implicit operator Term(int coefficient) => new Term(coefficient); public static Term operator -(Term t) => new Term(-t.Coefficient, t.Exponent); public static Term operator *(Term left, Term right) => new Term(left.Coefficient * right.Coefficient, left.Exponent + right.Exponent); public static bool operator ==(Term left, Term right) => left.Equals(right); public static bool operator !=(Term left, Term right) => !left.Equals(right); public static bool operator <(Term left, Term right) => left.CompareTo(right) < 0; public static bool operator >(Term left, Term right) => left.CompareTo(right) > 0; public static bool operator <=(Term left, Term right) => left.CompareTo(right) <= 0; public static bool operator >=(Term left, Term right) => left.CompareTo(right) >= 0; public bool Equals(Term other) => Exponent == other.Exponent && Coefficient == other.Coefficient; public override bool Equals(object? obj) => obj is Term t && Equals(t); public override int GetHashCode() => Coefficient.GetHashCode() * 31 + Exponent.GetHashCode(); public int CompareTo(Term other) { int c = Exponent.CompareTo(other.Exponent); if (c != 0) return c; return Coefficient.CompareTo(other.Coefficient); } public override string ToString() => (Coefficient, Exponent) switch { (0, _) => "0", (_, 0) => $"{Coefficient}", (1, 1) => "x", (-1, 1) => "-x", (_, 1) => $"{Coefficient}x", (1, _) => $"x^{Exponent}", (-1, _) => $"-x^{Exponent}", _ => $"{Coefficient}x^{Exponent}" }; } }
cyclo=: {{<.-:1+(++) p. 1;^0j2p1* y%~1+I.1=y+.1+i.y}}
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; public static class MinimalSteps { public static void Main() { var (divisors, subtractors) = (new int[] { 2, 3 }, new [] { 1 }); var lookup = CreateLookup(2_000, divisors, subtractors); Console.WriteLine($"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]"); PrintRange(lookup, 10); PrintMaxMins(lookup); lookup = CreateLookup(20_000, divisors, subtractors); PrintMaxMins(lookup); Console.WriteLine(); subtractors = new [] { 2 }; lookup = CreateLookup(2_000, divisors, subtractors); Console.WriteLine($"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]"); PrintRange(lookup, 10); PrintMaxMins(lookup); lookup = CreateLookup(20_000, divisors, subtractors); PrintMaxMins(lookup); } private static void PrintRange((char op, int param, int steps)[] lookup, int limit) { for (int goal = 1; goal <= limit; goal++) { var x = lookup[goal]; if (x.param == 0) { Console.WriteLine($"{goal} cannot be reached with these numbers."); continue; } Console.Write($"{goal} takes {x.steps} {(x.steps == 1 ? "step" : "steps")}: "); for (int n = goal; n > 1; ) { Console.Write($"{n},{x.op}{x.param}=> "); n = x.op == '/' ? n / x.param : n - x.param; x = lookup[n]; } Console.WriteLine("1"); } } private static void PrintMaxMins((char op, int param, int steps)[] lookup) { var maxSteps = lookup.Max(x => x.steps); var items = lookup.Select((x, i) => (i, x)).Where(t => t.x.steps == maxSteps).ToList(); Console.WriteLine(items.Count == 1 ? $"There is one number below {lookup.Length-1} that requires {maxSteps} steps: {items[0].i}" : $"There are {items.Count} numbers below {lookup.Length-1} that require {maxSteps} steps: {items.Select(t => t.i).Delimit()}" ); } private static (char op, int param, int steps)[] CreateLookup(int goal, int[] divisors, int[] subtractors) { var lookup = new (char op, int param, int steps)[goal+1]; lookup[1] = ('/', 1, 0); for (int n = 1; n < lookup.Length; n++) { var ln = lookup[n]; if (ln.param == 0) continue; for (int d = 0; d < divisors.Length; d++) { int target = n * divisors[d]; if (target > goal) break; if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('/', divisors[d], ln.steps + 1); } for (int s = 0; s < subtractors.Length; s++) { int target = n + subtractors[s]; if (target > goal) break; if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('-', subtractors[s], ln.steps + 1); } } return lookup; } private static string Delimit<T>(this IEnumerable<T> source) => string.Join(", ", source); }
step=: {{ ~.((#~ 1<:]),y-/m),(#~ (=<.)),y%/n }} steps=: {{ m step n^:(1 - 1 e. ])^:a: }} show=: {{ paths=.,:,:0 0 1 m=.,m [ n=.,n for_ok.}.|.m steps n y do. last=.{."2 paths subs=. (1,.m,.0)+"2]0 0 1*"1 last+"1 0/m divs=. (2,.n,.0)+"2]0 0 1*"1 last*"1 0/n prev=. subs,"2 divs paths=. (,({:"1 prev)e.ok)#,/prev,"1 2/"2 paths end. ;@((<":y),,)"2((' -/'{~{.);":@{:)"1}:"2}:"1 paths }}
Translate this program into J but keep the logic exactly as in C#.
using System; using System.Collections.Generic; class Program { static List<int> PrimesUpTo(int limit, bool verbose = false) { var sw = System.Diagnostics.Stopwatch.StartNew(); var members = new SortedSet<int>{ 1 }; int stp = 1, prime = 2, n, nxtpr, rtlim = 1 + (int)Math.Sqrt(limit), nl, ac = 2, rc = 1; List<int> primes = new List<int>(), tl = new List<int>(); while (prime < rtlim) { nl = Math.Min(prime * stp, limit); if (stp < limit) { tl.Clear(); foreach (var w in members) for (n = w + stp; n <= nl; n += stp) tl.Add(n); members.UnionWith(tl); ac += tl.Count; } stp = nl; nxtpr = 5; tl.Clear(); foreach (var w in members) { if (nxtpr == 5 && w > prime) nxtpr = w; if ((n = prime * w) > nl) break; else tl.Add(n); } foreach (var itm in tl) members.Remove(itm); rc += tl.Count; primes.Add(prime); prime = prime == 2 ? 3 : nxtpr; } members.Remove(1); primes.AddRange(members); sw.Stop(); if (verbose) Console.WriteLine("Up to {0}, added:{1}, removed:{2}, primes counted:{3}, time:{4} ms", limit, ac, rc, primes.Count, sw.Elapsed.TotalMilliseconds); return primes; } static void Main(string[] args) { Console.WriteLine("[{0}]", string.Join(", ", PrimesUpTo(150, true))); PrimesUpTo(1000000, true); } }
pritchard=: {{N=. y root=. >.@%: N spokes=. 1 primes=. '' p=. 0 while. p<:root do. primes=. primes, p=. 2+(}.spokes) i.1 rim=. #spokes spokes=. (N<.p*rim)$spokes spokes=. 0 ((#spokes) (>#]) _1+p*1+i.rim)} spokes end. N (>:#]) primes,1+}.,I.spokes }}
Translate the given C# code snippet into J without altering its behavior.
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace TransportationProblem { class Shipment { public Shipment(double q, double cpu, int r, int c) { Quantity = q; CostPerUnit = cpu; R = r; C = c; } public double CostPerUnit { get; } public double Quantity { get; set; } public int R { get; } public int C { get; } } class Program { private static int[] demand; private static int[] supply; private static double[,] costs; private static Shipment[,] matrix; static void Init(string filename) { string line; using (StreamReader file = new StreamReader(filename)) { line = file.ReadLine(); var numArr = line.Split(); int numSources = int.Parse(numArr[0]); int numDestinations = int.Parse(numArr[1]); List<int> src = new List<int>(); List<int> dst = new List<int>(); line = file.ReadLine(); numArr = line.Split(); for (int i = 0; i < numSources; i++) { src.Add(int.Parse(numArr[i])); } line = file.ReadLine(); numArr = line.Split(); for (int i = 0; i < numDestinations; i++) { dst.Add(int.Parse(numArr[i])); } int totalSrc = src.Sum(); int totalDst = dst.Sum(); if (totalSrc > totalDst) { dst.Add(totalSrc - totalDst); } else if (totalDst > totalSrc) { src.Add(totalDst - totalSrc); } supply = src.ToArray(); demand = dst.ToArray(); costs = new double[supply.Length, demand.Length]; matrix = new Shipment[supply.Length, demand.Length]; for (int i = 0; i < numSources; i++) { line = file.ReadLine(); numArr = line.Split(); for (int j = 0; j < numDestinations; j++) { costs[i, j] = int.Parse(numArr[j]); } } } } static void NorthWestCornerRule() { for (int r = 0, northwest = 0; r < supply.Length; r++) { for (int c = northwest; c < demand.Length; c++) { int quantity = Math.Min(supply[r], demand[c]); if (quantity > 0) { matrix[r, c] = new Shipment(quantity, costs[r, c], r, c); supply[r] -= quantity; demand[c] -= quantity; if (supply[r] == 0) { northwest = c; break; } } } } } static void SteppingStone() { double maxReduction = 0; Shipment[] move = null; Shipment leaving = null; FixDegenerateCase(); for (int r = 0; r < supply.Length; r++) { for (int c = 0; c < demand.Length; c++) { if (matrix[r, c] != null) { continue; } Shipment trial = new Shipment(0, costs[r, c], r, c); Shipment[] path = GetClosedPath(trial); double reduction = 0; double lowestQuantity = int.MaxValue; Shipment leavingCandidate = null; bool plus = true; foreach (var s in path) { if (plus) { reduction += s.CostPerUnit; } else { reduction -= s.CostPerUnit; if (s.Quantity < lowestQuantity) { leavingCandidate = s; lowestQuantity = s.Quantity; } } plus = !plus; } if (reduction < maxReduction) { move = path; leaving = leavingCandidate; maxReduction = reduction; } } } if (move != null) { double q = leaving.Quantity; bool plus = true; foreach (var s in move) { s.Quantity += plus ? q : -q; matrix[s.R, s.C] = s.Quantity == 0 ? null : s; plus = !plus; } SteppingStone(); } } static List<Shipment> MatrixToList() { List<Shipment> newList = new List<Shipment>(); foreach (var item in matrix) { if (null != item) { newList.Add(item); } } return newList; } static Shipment[] GetClosedPath(Shipment s) { List<Shipment> path = MatrixToList(); path.Add(s); int before; do { before = path.Count; path.RemoveAll(ship => { var nbrs = GetNeighbors(ship, path); return nbrs[0] == null || nbrs[1] == null; }); } while (before != path.Count); Shipment[] stones = path.ToArray(); Shipment prev = s; for (int i = 0; i < stones.Length; i++) { stones[i] = prev; prev = GetNeighbors(prev, path)[i % 2]; } return stones; } static Shipment[] GetNeighbors(Shipment s, List<Shipment> lst) { Shipment[] nbrs = new Shipment[2]; foreach (var o in lst) { if (o != s) { if (o.R == s.R && nbrs[0] == null) { nbrs[0] = o; } else if (o.C == s.C && nbrs[1] == null) { nbrs[1] = o; } if (nbrs[0] != null && nbrs[1] != null) { break; } } } return nbrs; } static void FixDegenerateCase() { const double eps = double.Epsilon; if (supply.Length + demand.Length - 1 != MatrixToList().Count) { for (int r = 0; r < supply.Length; r++) { for (int c = 0; c < demand.Length; c++) { if (matrix[r, c] == null) { Shipment dummy = new Shipment(eps, costs[r, c], r, c); if (GetClosedPath(dummy).Length == 0) { matrix[r, c] = dummy; return; } } } } } } static void PrintResult(string filename) { Console.WriteLine("Optimal solution {0}\n", filename); double totalCosts = 0; for (int r = 0; r < supply.Length; r++) { for (int c = 0; c < demand.Length; c++) { Shipment s = matrix[r, c]; if (s != null && s.R == r && s.C == c) { Console.Write(" {0,3} ", s.Quantity); totalCosts += (s.Quantity * s.CostPerUnit); } else { Console.Write(" - "); } } Console.WriteLine(); } Console.WriteLine("\nTotal costs: {0}\n", totalCosts); } static void Main() { foreach (var filename in new string[] { "input1.txt", "input2.txt", "input3.txt" }) { Init(filename); NorthWestCornerRule(); SteppingStone(); PrintResult(filename); } } } }
ndxasgn=: conjunction define : ((m{y)v x) m} y ) trans=: adverb define : need=. x supl=. y cost=. m dims=. supl ,&# need r=. dims$0 while. 1 e., xfr=. supl *&*/ need do. 'iS iN'=. ndxs=. dims#:(i. <./), cost % xfr n=. (iS { supl) <. iN { need need=. n iN ndxasgn - need supl=. n iS ndxasgn - supl r=. n (<ndxs)} r end. )
Port the provided C# code into J while preserving the original functionality.
using System; class Program { static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew(); int a, b, c, i, n, s3, ab; var res = new int[65]; for (n = 1, i = 0; n < 1850; n++) { bool found = true; for (a = 1; a < n; a++) for (b = a + 1, ab = a * b + a + b; b < n; b++, ab += a + 1) { if (ab > n) break; for (c = b + 1, s3 = ab + (b + a) * b; c < n; c++, s3 += b + a) { if (s3 == n) found = false; if (s3 >= n) break; } } if (found) res[i++] = n; } sw.Stop(); Console.WriteLine("The 65 known Idoneal numbers:"); for (i = 0; i < res.Length; i++) Console.Write("{0,5}{1}", res[i], i % 13 == 12 ? "\n" : ""); Console.Write("Calculations took {0} ms", sw.Elapsed.TotalMilliseconds); } }
requre'stats' _10]\(1+i.255)-.+/1*/\.|:1+3 comb 255 1 2 3 4 5 6 7 8 9 10 12 13 15 16 18 21 22 24 25 28 30 33 37 40 42 45 48 57 58 60 70 72 78 85 88 93 102 105 112 120 130 133 165 168 177 190 210 232 240 253
Change the following Java code into Ruby without altering its purpose.
public class NthPrime { public static void main(String[] args) { System.out.printf("The 10,001st prime is %,d.\n", nthPrime(10001)); } private static int nthPrime(int n) { assert n > 0; PrimeGenerator primeGen = new PrimeGenerator(10000, 100000); int prime = primeGen.nextPrime(); while (--n > 0) prime = primeGen.nextPrime(); return prime; } }
require "prime" puts Prime.lazy.drop(10_000).next
Produce a functionally identical Ruby code for the snippet given in Java.
public class NthPrime { public static void main(String[] args) { System.out.printf("The 10,001st prime is %,d.\n", nthPrime(10001)); } private static int nthPrime(int n) { assert n > 0; PrimeGenerator primeGen = new PrimeGenerator(10000, 100000); int prime = primeGen.nextPrime(); while (--n > 0) prime = primeGen.nextPrime(); return prime; } }
require "prime" puts Prime.lazy.drop(10_000).next
Transform the following Java implementation into Ruby, maintaining the same output and logic.
class SpecialPrimes { private static boolean isPrime(int n) { if (n < 2) return false; if (n%2 == 0) return n == 2; if (n%3 == 0) return n == 3; int d = 5; while (d*d <= n) { if (n%d == 0) return false; d += 2; if (n%d == 0) return false; d += 4; } return true; } public static void main(String[] args) { System.out.println("Special primes under 1,050:"); System.out.println("Prime1 Prime2 Gap"); int lastSpecial = 3; int lastGap = 1; System.out.printf("%6d %6d %3d\n", 2, 3, lastGap); for (int i = 5; i < 1050; i += 2) { if (isPrime(i) && (i-lastSpecial) > lastGap) { lastGap = i - lastSpecial; System.out.printf("%6d %6d %3d\n", lastSpecial, i, lastGap); lastSpecial = i; } } } }
func special_primes(upto) { var gap = 0 var prev = 2 var list = [[prev, gap]] loop { var n = prev+gap n = n.next_prime break if (n > upto) gap = n-prev list << [n, gap] prev = n } return list } special_primes(1050).each_2d {|p,gap| say " }
Write the same algorithm in Ruby as shown in this Java implementation.
class SpecialPrimes { private static boolean isPrime(int n) { if (n < 2) return false; if (n%2 == 0) return n == 2; if (n%3 == 0) return n == 3; int d = 5; while (d*d <= n) { if (n%d == 0) return false; d += 2; if (n%d == 0) return false; d += 4; } return true; } public static void main(String[] args) { System.out.println("Special primes under 1,050:"); System.out.println("Prime1 Prime2 Gap"); int lastSpecial = 3; int lastGap = 1; System.out.printf("%6d %6d %3d\n", 2, 3, lastGap); for (int i = 5; i < 1050; i += 2) { if (isPrime(i) && (i-lastSpecial) > lastGap) { lastGap = i - lastSpecial; System.out.printf("%6d %6d %3d\n", lastSpecial, i, lastGap); lastSpecial = i; } } } }
func special_primes(upto) { var gap = 0 var prev = 2 var list = [[prev, gap]] loop { var n = prev+gap n = n.next_prime break if (n > upto) gap = n-prev list << [n, gap] prev = n } return list } special_primes(1050).each_2d {|p,gap| say " }
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version.
public class LynchBell { static String s = ""; public static void main(String args[]) { int i = 98764321; boolean isUnique = true; boolean canBeDivided = true; while (i>0) { s = String.valueOf(i); isUnique = uniqueDigits(i); if (isUnique) { canBeDivided = testNumber(i); if(canBeDivided) { System.out.println("Number found: " + i); i=0; } } i--; } } public static boolean uniqueDigits(int i) { for (int k = 0; k<s.length();k++) { for(int l=k+1; l<s.length();l++) { if(s.charAt(l)=='0' || s.charAt(l)=='5') { return false; } if(s.charAt(k) == s.charAt(l)) { return false; } } } return true; } public static boolean testNumber(int i) { int j = 0; boolean divisible = true; for (char ch: s.toCharArray()) { j = Character.getNumericValue(ch); divisible = ((i%j)==0); if (!divisible) { return false; } } return true; } }
magic_number = 9*8*7 div = (9876432 // magic_number) * magic_number candidates = div.step(to: 0, by: -magic_number) res = candidates.find do |c| digits = c.to_s.chars.map(&.to_i) (digits & [0,5]).empty? && digits == digits.uniq end puts "Largest decimal number is
Write the same code in Ruby as shown below in Java.
public class LynchBell { static String s = ""; public static void main(String args[]) { int i = 98764321; boolean isUnique = true; boolean canBeDivided = true; while (i>0) { s = String.valueOf(i); isUnique = uniqueDigits(i); if (isUnique) { canBeDivided = testNumber(i); if(canBeDivided) { System.out.println("Number found: " + i); i=0; } } i--; } } public static boolean uniqueDigits(int i) { for (int k = 0; k<s.length();k++) { for(int l=k+1; l<s.length();l++) { if(s.charAt(l)=='0' || s.charAt(l)=='5') { return false; } if(s.charAt(k) == s.charAt(l)) { return false; } } } return true; } public static boolean testNumber(int i) { int j = 0; boolean divisible = true; for (char ch: s.toCharArray()) { j = Character.getNumericValue(ch); divisible = ((i%j)==0); if (!divisible) { return false; } } return true; } }
magic_number = 9*8*7 div = (9876432 // magic_number) * magic_number candidates = div.step(to: 0, by: -magic_number) res = candidates.find do |c| digits = c.to_s.chars.map(&.to_i) (digits & [0,5]).empty? && digits == digits.uniq end puts "Largest decimal number is
Maintain the same structure and functionality when rewriting this code in Ruby.
public class JacobiSymbol { public static void main(String[] args) { int max = 30; System.out.printf("n\\k "); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", k); } System.out.printf("%n"); for ( int n = 1 ; n <= max ; n += 2 ) { System.out.printf("%2d ", n); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", jacobiSymbol(k, n)); } System.out.printf("%n"); } } private static int jacobiSymbol(int k, int n) { if ( k < 0 || n % 2 == 0 ) { throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n); } k %= n; int jacobi = 1; while ( k > 0 ) { while ( k % 2 == 0 ) { k /= 2; int r = n % 8; if ( r == 3 || r == 5 ) { jacobi = -jacobi; } } int temp = n; n = k; k = temp; if ( k % 4 == 3 && n % 4 == 3 ) { jacobi = -jacobi; } k %= n; } if ( n == 1 ) { return jacobi; } return 0; } }
def jacobi(a, n) raise ArgumentError.new "n must b positive and odd" if n < 1 || n.even? res = 1 until (a %= n) == 0 while a.even? a >>= 1 res = -res if [3, 5].includes? n % 8 end a, n = n, a res = -res if a % 4 == n % 4 == 3 end n == 1 ? res : 0 end puts "Jacobian symbols for jacobi(a, n)" puts "n\\a 0 1 2 3 4 5 6 7 8 9 10" puts "------------------------------------" 1.step(to: 17, by: 2) do |n| printf("%2d ", n) (0..10).each { |a| printf(" % 2d", jacobi(a, n)) } puts end
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version.
public class JacobiSymbol { public static void main(String[] args) { int max = 30; System.out.printf("n\\k "); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", k); } System.out.printf("%n"); for ( int n = 1 ; n <= max ; n += 2 ) { System.out.printf("%2d ", n); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", jacobiSymbol(k, n)); } System.out.printf("%n"); } } private static int jacobiSymbol(int k, int n) { if ( k < 0 || n % 2 == 0 ) { throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n); } k %= n; int jacobi = 1; while ( k > 0 ) { while ( k % 2 == 0 ) { k /= 2; int r = n % 8; if ( r == 3 || r == 5 ) { jacobi = -jacobi; } } int temp = n; n = k; k = temp; if ( k % 4 == 3 && n % 4 == 3 ) { jacobi = -jacobi; } k %= n; } if ( n == 1 ) { return jacobi; } return 0; } }
def jacobi(a, n) raise ArgumentError.new "n must b positive and odd" if n < 1 || n.even? res = 1 until (a %= n) == 0 while a.even? a >>= 1 res = -res if [3, 5].includes? n % 8 end a, n = n, a res = -res if a % 4 == n % 4 == 3 end n == 1 ? res : 0 end puts "Jacobian symbols for jacobi(a, n)" puts "n\\a 0 1 2 3 4 5 6 7 8 9 10" puts "------------------------------------" 1.step(to: 17, by: 2) do |n| printf("%2d ", n) (0..10).each { |a| printf(" % 2d", jacobi(a, n)) } puts end
Port the following code from Java to Ruby with equivalent syntax and logic.
import java.util.Scanner; public class MatrixArithmetic { public static double[][] minor(double[][] a, int x, int y){ int length = a.length-1; double[][] result = new double[length][length]; for(int i=0;i<length;i++) for(int j=0;j<length;j++){ if(i<x && j<y){ result[i][j] = a[i][j]; }else if(i>=x && j<y){ result[i][j] = a[i+1][j]; }else if(i<x && j>=y){ result[i][j] = a[i][j+1]; }else{ result[i][j] = a[i+1][j+1]; } } return result; } public static double det(double[][] a){ if(a.length == 1){ return a[0][0]; }else{ int sign = 1; double sum = 0; for(int i=0;i<a.length;i++){ sum += sign * a[0][i] * det(minor(a,0,i)); sign *= -1; } return sum; } } public static double perm(double[][] a){ if(a.length == 1){ return a[0][0]; }else{ double sum = 0; for(int i=0;i<a.length;i++){ sum += a[0][i] * perm(minor(a,0,i)); } return sum; } } public static void main(String args[]){ Scanner sc = new Scanner(System.in); int size = sc.nextInt(); double[][] a = new double[size][size]; for(int i=0;i<size;i++) for(int j=0;j<size;j++){ a[i][j] = sc.nextDouble(); } sc.close(); System.out.println("Determinant: "+det(a)); System.out.println("Permanent: "+perm(a)); } }
require 'matrix' class Matrix def permanent r = (0...row_count).to_a r.permutation.inject(0) do |sum, sigma| sum += sigma.zip(r).inject(1){|prod, (row, col)| prod *= self[row, col] } end end end m1 = Matrix[[1,2],[3,4]] m2 = Matrix[[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]] m3 = Matrix[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]] [m1, m2, m3].each do |m| puts "determinant:\t puts end
Convert this Java block to Ruby, preserving its control flow and logic.
import java.util.Scanner; public class MatrixArithmetic { public static double[][] minor(double[][] a, int x, int y){ int length = a.length-1; double[][] result = new double[length][length]; for(int i=0;i<length;i++) for(int j=0;j<length;j++){ if(i<x && j<y){ result[i][j] = a[i][j]; }else if(i>=x && j<y){ result[i][j] = a[i+1][j]; }else if(i<x && j>=y){ result[i][j] = a[i][j+1]; }else{ result[i][j] = a[i+1][j+1]; } } return result; } public static double det(double[][] a){ if(a.length == 1){ return a[0][0]; }else{ int sign = 1; double sum = 0; for(int i=0;i<a.length;i++){ sum += sign * a[0][i] * det(minor(a,0,i)); sign *= -1; } return sum; } } public static double perm(double[][] a){ if(a.length == 1){ return a[0][0]; }else{ double sum = 0; for(int i=0;i<a.length;i++){ sum += a[0][i] * perm(minor(a,0,i)); } return sum; } } public static void main(String args[]){ Scanner sc = new Scanner(System.in); int size = sc.nextInt(); double[][] a = new double[size][size]; for(int i=0;i<size;i++) for(int j=0;j<size;j++){ a[i][j] = sc.nextDouble(); } sc.close(); System.out.println("Determinant: "+det(a)); System.out.println("Permanent: "+perm(a)); } }
require 'matrix' class Matrix def permanent r = (0...row_count).to_a r.permutation.inject(0) do |sum, sigma| sum += sigma.zip(r).inject(1){|prod, (row, col)| prod *= self[row, col] } end end end m1 = Matrix[[1,2],[3,4]] m2 = Matrix[[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]] m3 = Matrix[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]] [m1, m2, m3].each do |m| puts "determinant:\t puts end
Port the following code from Java to Ruby with equivalent syntax and logic.
private static final Random rng = new Random(); void sattoloCycle(Object[] items) { for (int i = items.length-1; i > 0; i--) { int j = rng.nextInt(i); Object tmp = items[i]; items[i] = items[j]; items[j] = tmp; } }
> class Array > def sattolo_cycle! > (length - 1).downto(1) do |i| * j = rand(i) > self[i], self[j] = self[j], self[i] > end > self > end > end => :sattolo_cycle! > > 10.times do * p [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].sattolo_cycle! > end [10, 6, 9, 7, 8, 1, 3, 2, 5, 4] [3, 7, 5, 10, 4, 8, 1, 2, 6, 9] [10, 3, 4, 8, 9, 7, 1, 5, 6, 2] [8, 7, 4, 2, 6, 9, 1, 5, 10, 3] [2, 7, 5, 10, 8, 3, 6, 9, 4, 1] [2, 10, 8, 6, 1, 3, 5, 9, 7, 4] [8, 5, 6, 1, 4, 9, 2, 10, 7, 3] [5, 4, 10, 7, 2, 1, 8, 9, 3, 6] [9, 8, 4, 2, 6, 1, 5, 10, 3, 7] [9, 4, 2, 7, 6, 1, 10, 3, 8, 5] => 10
Generate an equivalent Ruby version of this Java code.
private static final Random rng = new Random(); void sattoloCycle(Object[] items) { for (int i = items.length-1; i > 0; i--) { int j = rng.nextInt(i); Object tmp = items[i]; items[i] = items[j]; items[j] = tmp; } }
> class Array > def sattolo_cycle! > (length - 1).downto(1) do |i| * j = rand(i) > self[i], self[j] = self[j], self[i] > end > self > end > end => :sattolo_cycle! > > 10.times do * p [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].sattolo_cycle! > end [10, 6, 9, 7, 8, 1, 3, 2, 5, 4] [3, 7, 5, 10, 4, 8, 1, 2, 6, 9] [10, 3, 4, 8, 9, 7, 1, 5, 6, 2] [8, 7, 4, 2, 6, 9, 1, 5, 10, 3] [2, 7, 5, 10, 8, 3, 6, 9, 4, 1] [2, 10, 8, 6, 1, 3, 5, 9, 7, 4] [8, 5, 6, 1, 4, 9, 2, 10, 7, 3] [5, 4, 10, 7, 2, 1, 8, 9, 3, 6] [9, 8, 4, 2, 6, 1, 5, 10, 3, 7] [9, 4, 2, 7, 6, 1, 10, 3, 8, 5] => 10
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version.
import java.util.Arrays; public class CycleSort { public static void main(String[] args) { int[] arr = {5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1}; System.out.println(Arrays.toString(arr)); int writes = cycleSort(arr); System.out.println(Arrays.toString(arr)); System.out.println("writes: " + writes); } static int cycleSort(int[] a) { int writes = 0; for (int cycleStart = 0; cycleStart < a.length - 1; cycleStart++) { int val = a[cycleStart]; int pos = cycleStart; for (int i = cycleStart + 1; i < a.length; i++) if (a[i] < val) pos++; if (pos == cycleStart) continue; while (val == a[pos]) pos++; int tmp = a[pos]; a[pos] = val; val = tmp; writes++; while (pos != cycleStart) { pos = cycleStart; for (int i = cycleStart + 1; i < a.length; i++) if (a[i] < val) pos++; while (val == a[pos]) pos++; tmp = a[pos]; a[pos] = val; val = tmp; writes++; } } return writes; } }
def cycleSort!(array) writes = 0 for cycleStart in 0 .. array.size-2 item = array[cycleStart] pos = cycleStart for i in cycleStart+1 ... array.size pos += 1 if array[i] < item end next if pos == cycleStart pos += 1 while item == array[pos] array[pos], item = item, array[pos] writes += 1 while pos != cycleStart pos = cycleStart for i in cycleStart+1 ... array.size pos += 1 if array[i] < item end pos += 1 while item == array[pos] array[pos], item = item, array[pos] writes += 1 end end writes end p a = [0, 1, 2, 2, 2, 2, 1, 9, 3.5, 5, 8, 4, 7, 0, 6] puts "writes : p a
Translate this program into Ruby but keep the logic exactly as in Java.
import java.util.Arrays; public class CycleSort { public static void main(String[] args) { int[] arr = {5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1}; System.out.println(Arrays.toString(arr)); int writes = cycleSort(arr); System.out.println(Arrays.toString(arr)); System.out.println("writes: " + writes); } static int cycleSort(int[] a) { int writes = 0; for (int cycleStart = 0; cycleStart < a.length - 1; cycleStart++) { int val = a[cycleStart]; int pos = cycleStart; for (int i = cycleStart + 1; i < a.length; i++) if (a[i] < val) pos++; if (pos == cycleStart) continue; while (val == a[pos]) pos++; int tmp = a[pos]; a[pos] = val; val = tmp; writes++; while (pos != cycleStart) { pos = cycleStart; for (int i = cycleStart + 1; i < a.length; i++) if (a[i] < val) pos++; while (val == a[pos]) pos++; tmp = a[pos]; a[pos] = val; val = tmp; writes++; } } return writes; } }
def cycleSort!(array) writes = 0 for cycleStart in 0 .. array.size-2 item = array[cycleStart] pos = cycleStart for i in cycleStart+1 ... array.size pos += 1 if array[i] < item end next if pos == cycleStart pos += 1 while item == array[pos] array[pos], item = item, array[pos] writes += 1 while pos != cycleStart pos = cycleStart for i in cycleStart+1 ... array.size pos += 1 if array[i] < item end pos += 1 while item == array[pos] array[pos], item = item, array[pos] writes += 1 end end writes end p a = [0, 1, 2, 2, 2, 2, 1, 9, 3.5, 5, 8, 4, 7, 0, 6] puts "writes : p a
Convert this Java block to Ruby, preserving its control flow and logic.
import java.math.BigInteger; import java.util.Scanner; public class twinPrimes { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Search Size: "); BigInteger max = input.nextBigInteger(); int counter = 0; for(BigInteger x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){ BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE); if(x.add(BigInteger.TWO).compareTo(max) <= 0) { counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0; } } System.out.println(counter + " twin prime pairs."); } public static boolean findPrime(BigInteger x, BigInteger sqrtNum){ for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){ if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){ return false; } } return true; } }
require 'prime' (1..8).each do |n| count = Prime.each(10**n).each_cons(2).count{|p1, p2| p2-p1 == 2} puts "Twin primes below 10** end
Change the following Java code into Ruby without altering its purpose.
import java.math.BigInteger; import java.util.List; public class Brazilian { private static final List<Integer> primeList = List.of( 2, 3, 5, 7, 9, 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, 169, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 247, 251, 257, 263, 269, 271, 277, 281, 283, 293, 299, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 377, 379, 383, 389, 397, 401, 403, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 481, 487, 491, 499, 503, 509, 521, 523, 533, 541, 547, 557, 559, 563, 569, 571, 577, 587, 593, 599, 601, 607, 611, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 689, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 767, 769, 773, 787, 793, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 871, 877, 881, 883, 887, 907, 911, 919, 923, 929, 937, 941, 947, 949, 953, 967, 971, 977, 983, 991, 997 ); public static boolean isPrime(int n) { if (n < 2) { return false; } for (Integer prime : primeList) { if (n == prime) { return true; } if (n % prime == 0) { return false; } if (prime * prime > n) { return true; } } BigInteger bi = BigInteger.valueOf(n); return bi.isProbablePrime(10); } private static boolean sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) { if (n % b != f) { return false; } } return true; } private static boolean isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0) return true; for (int b = 2; b < n - 1; ++b) { if (sameDigits(n, b)) { return true; } } return false; } public static void main(String[] args) { for (String kind : List.of("", "odd ", "prime ")) { boolean quiet = false; int bigLim = 99_999; int limit = 20; System.out.printf("First %d %sBrazilian numbers:\n", limit, kind); int c = 0; int n = 7; while (c < bigLim) { if (isBrazilian(n)) { if (!quiet) System.out.printf("%d ", n); if (++c == limit) { System.out.println("\n"); quiet = true; } } if (quiet && !"".equals(kind)) continue; switch (kind) { case "": n++; break; case "odd ": n += 2; break; case "prime ": do { n += 2; } while (!isPrime(n)); break; default: throw new AssertionError("Oops"); } } if ("".equals(kind)) { System.out.printf("The %dth Brazilian number is: %d\n\n", bigLim + 1, n); } } } }
def sameDigits(n,b) f = n % b while (n /= b) > 0 do if n % b != f then return false end end return true end def isBrazilian(n) if n < 7 then return false end if n % 2 == 0 then return true end for b in 2 .. n - 2 do if sameDigits(n, b) then return true end end return false end def isPrime(n) if n < 2 then return false end if n % 2 == 0 then return n == 2 end if n % 3 == 0 then return n == 3 end d = 5 while d * d <= n do if n % d == 0 then return false end d = d + 2 if n % d == 0 then return false end d = d + 4 end return true end def main for kind in ["", "odd ", "prime "] do quiet = false bigLim = 99999 limit = 20 puts "First %d %sBrazilian numbers:" % [limit, kind] c = 0 n = 7 while c < bigLim do if isBrazilian(n) then if not quiet then print "%d " % [n] end c = c + 1 if c == limit then puts puts quiet = true end end if quiet and kind != "" then next end if kind == "" then n = n + 1 elsif kind == "odd " then n = n + 2 elsif kind == "prime " then loop do n = n + 2 if isPrime(n) then break end end else raise "Unexpected" end end if kind == "" then puts "The %dth Brazillian number is: %d" % [bigLim + 1, n] puts end end end main()
Write a version of this Java function in Ruby with identical behavior.
import java.math.BigInteger; import java.util.List; public class Brazilian { private static final List<Integer> primeList = List.of( 2, 3, 5, 7, 9, 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, 169, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 247, 251, 257, 263, 269, 271, 277, 281, 283, 293, 299, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 377, 379, 383, 389, 397, 401, 403, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 481, 487, 491, 499, 503, 509, 521, 523, 533, 541, 547, 557, 559, 563, 569, 571, 577, 587, 593, 599, 601, 607, 611, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 689, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 767, 769, 773, 787, 793, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 871, 877, 881, 883, 887, 907, 911, 919, 923, 929, 937, 941, 947, 949, 953, 967, 971, 977, 983, 991, 997 ); public static boolean isPrime(int n) { if (n < 2) { return false; } for (Integer prime : primeList) { if (n == prime) { return true; } if (n % prime == 0) { return false; } if (prime * prime > n) { return true; } } BigInteger bi = BigInteger.valueOf(n); return bi.isProbablePrime(10); } private static boolean sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) { if (n % b != f) { return false; } } return true; } private static boolean isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0) return true; for (int b = 2; b < n - 1; ++b) { if (sameDigits(n, b)) { return true; } } return false; } public static void main(String[] args) { for (String kind : List.of("", "odd ", "prime ")) { boolean quiet = false; int bigLim = 99_999; int limit = 20; System.out.printf("First %d %sBrazilian numbers:\n", limit, kind); int c = 0; int n = 7; while (c < bigLim) { if (isBrazilian(n)) { if (!quiet) System.out.printf("%d ", n); if (++c == limit) { System.out.println("\n"); quiet = true; } } if (quiet && !"".equals(kind)) continue; switch (kind) { case "": n++; break; case "odd ": n += 2; break; case "prime ": do { n += 2; } while (!isPrime(n)); break; default: throw new AssertionError("Oops"); } } if ("".equals(kind)) { System.out.printf("The %dth Brazilian number is: %d\n\n", bigLim + 1, n); } } } }
def sameDigits(n,b) f = n % b while (n /= b) > 0 do if n % b != f then return false end end return true end def isBrazilian(n) if n < 7 then return false end if n % 2 == 0 then return true end for b in 2 .. n - 2 do if sameDigits(n, b) then return true end end return false end def isPrime(n) if n < 2 then return false end if n % 2 == 0 then return n == 2 end if n % 3 == 0 then return n == 3 end d = 5 while d * d <= n do if n % d == 0 then return false end d = d + 2 if n % d == 0 then return false end d = d + 4 end return true end def main for kind in ["", "odd ", "prime "] do quiet = false bigLim = 99999 limit = 20 puts "First %d %sBrazilian numbers:" % [limit, kind] c = 0 n = 7 while c < bigLim do if isBrazilian(n) then if not quiet then print "%d " % [n] end c = c + 1 if c == limit then puts puts quiet = true end end if quiet and kind != "" then next end if kind == "" then n = n + 1 elsif kind == "odd " then n = n + 2 elsif kind == "prime " then loop do n = n + 2 if isPrime(n) then break end end else raise "Unexpected" end end if kind == "" then puts "The %dth Brazillian number is: %d" % [bigLim + 1, n] puts end end end main()
Convert this Java block to Ruby, preserving its control flow and logic.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; public class CreateFile { public static void main(String[] args) throws IOException { String os = System.getProperty("os.name"); if (os.contains("Windows")) { Path path = Paths.get("tape.file"); Files.write(path, Collections.singletonList("Hello World!")); } else { Path path = Paths.get("/dev/tape"); Files.write(path, Collections.singletonList("Hello World!")); } } }
filename = {% if flag?(:win32) %} "TAPE.FILE" {% else %} "/dev/tape" {% end %} File.write filename, "howdy, planet!"
Translate the given Java code snippet into Ruby without altering its behavior.
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
require 'set' a = [0] used = Set[0] used1000 = Set[0] foundDup = false n = 1 while n <= 15 or not foundDup or used1000.size < 1001 nxt = a[n - 1] - n if nxt < 1 or used === nxt then nxt = nxt + 2 * n end alreadyUsed = used === nxt a << nxt if not alreadyUsed then used << nxt if nxt >= 0 and nxt <= 1000 then used1000 << nxt end end if n == 14 then print "The first 15 terms of the Recaman's sequence are ", a, "\n" end if not foundDup and alreadyUsed then print "The first duplicated term is a[", n, "] = ", nxt, "\n" foundDup = true end if used1000.size == 1001 then print "Terms up to a[", n, "] are needed to generate 0 to 1000\n" end n = n + 1 end
Ensure the translated Ruby code behaves exactly like the original Java snippet.
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
require 'set' a = [0] used = Set[0] used1000 = Set[0] foundDup = false n = 1 while n <= 15 or not foundDup or used1000.size < 1001 nxt = a[n - 1] - n if nxt < 1 or used === nxt then nxt = nxt + 2 * n end alreadyUsed = used === nxt a << nxt if not alreadyUsed then used << nxt if nxt >= 0 and nxt <= 1000 then used1000 << nxt end end if n == 14 then print "The first 15 terms of the Recaman's sequence are ", a, "\n" end if not foundDup and alreadyUsed then print "The first duplicated term is a[", n, "] = ", nxt, "\n" foundDup = true end if used1000.size == 1001 then print "Terms up to a[", n, "] are needed to generate 0 to 1000\n" end n = n + 1 end
Keep all operations the same but rewrite the snippet in Ruby.
import java.util.function.Function; public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); return r.apply(r); } public static void main(String... arguments) { Function<Integer,Integer> fib = Y(f -> n -> (n <= 2) ? 1 : (f.apply(n - 1) + f.apply(n - 2)) ); Function<Integer,Integer> fac = Y(f -> n -> (n <= 1) ? 1 : (n * f.apply(n - 1)) ); System.out.println("fib(10) = " + fib.apply(10)); System.out.println("fac(10) = " + fac.apply(10)); } }
y = lambda do |f| lambda {|g| g[g]}[lambda do |g| f[lambda {|*args| g[g][*args]}] end] end fac = lambda{|f| lambda{|n| n < 2 ? 1 : n * f[n-1]}} p Array.new(10) {|i| y[fac][i]} fib = lambda{|f| lambda{|n| n < 2 ? n : f[n-1] + f[n-2]}} p Array.new(10) {|i| y[fib][i]}
Produce a language-to-language conversion: from Java to Ruby, same semantics.
public class CirclesTotalArea { private static double distSq(double x1, double y1, double x2, double y2) { return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); } private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) { double r2 = circ[2] * circ[2]; return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 && distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 && distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 && distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2; } private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) { if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] && rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; } double r2 = circ[2] + Math.max(rect[2], rect[3]); r2 = r2 * r2; return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 && distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 && distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 && distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2; } private static boolean[] surelyOutside; private static double totalArea(double[] rect, double[][] circs, int d) { int surelyOutsideCount = 0; for(int i = 0; i < circs.length; i++) { if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; } if(rectangleSurelyOutsideCircle(rect, circs[i])) { surelyOutside[i] = true; surelyOutsideCount++; } else { surelyOutside[i] = false; } } if(surelyOutsideCount == circs.length) { return 0; } if(d < 1) { return rect[2] * rect[3] / 3; } if(surelyOutsideCount > 0) { double[][] newCircs = new double[circs.length - surelyOutsideCount][3]; int loc = 0; for(int i = 0; i < circs.length; i++) { if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; } } circs = newCircs; } double w = rect[2] / 2; double h = rect[3] / 2; double[][] pieces = { { rect[0], rect[1], w, h }, { rect[0] + w, rect[1], w, h }, { rect[0], rect[1] - h, w, h }, { rect[0] + w, rect[1] - h, w, h } }; double total = 0; for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); } return total; } public static double totalArea(double[][] circs, int d) { double maxx = Double.NEGATIVE_INFINITY; double minx = Double.POSITIVE_INFINITY; double maxy = Double.NEGATIVE_INFINITY; double miny = Double.POSITIVE_INFINITY; for(double[] circ: circs) { if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; } if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; } if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; } if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; } } double[] rect = { minx, maxy, maxx - minx, maxy - miny }; surelyOutside = new boolean[circs.length]; return totalArea(rect, circs, d); } public static void main(String[] args) { double[][] circs = { { 1.6417233788, 1.6121789534, 0.0848270516 }, {-1.4944608174, 1.2077959613, 1.1039549836 }, { 0.6110294452, -0.6907087527, 0.9089162485 }, { 0.3844862411, 0.2923344616, 0.2375743054 }, {-0.2495892950, -0.3832854473, 1.0845181219 }, {1.7813504266, 1.6178237031, 0.8162655711 }, {-0.1985249206, -0.8343333301, 0.0538864941 }, {-1.7011985145, -0.1263820964, 0.4776976918 }, {-0.4319462812, 1.4104420482, 0.7886291537 }, {0.2178372997, -0.9499557344, 0.0357871187 }, {-0.6294854565, -1.3078893852, 0.7653357688 }, {1.7952608455, 0.6281269104, 0.2727652452 }, {1.4168575317, 1.0683357171, 1.1016025378 }, {1.4637371396, 0.9463877418, 1.1846214562 }, {-0.5263668798, 1.7315156631, 1.4428514068 }, {-1.2197352481, 0.9144146579, 1.0727263474 }, {-0.1389358881, 0.1092805780, 0.7350208828 }, {1.5293954595, 0.0030278255, 1.2472867347 }, {-0.5258728625, 1.3782633069, 1.3495508831 }, {-0.1403562064, 0.2437382535, 1.3804956588 }, {0.8055826339, -0.0482092025, 0.3327165165 }, {-0.6311979224, 0.7184578971, 0.2491045282 }, {1.4685857879, -0.8347049536, 1.3670667538 }, {-0.6855727502, 1.6465021616, 1.0593087096 }, {0.0152957411, 0.0638919221, 0.9771215985 } }; double ans = totalArea(circs, 24); System.out.println("Approx. area is " + ans); System.out.println("Error is " + Math.abs(21.56503660 - ans)); } }
circles = [ [ 1.6417233788, 1.6121789534, 0.0848270516], [-1.4944608174, 1.2077959613, 1.1039549836], [ 0.6110294452, -0.6907087527, 0.9089162485], [ 0.3844862411, 0.2923344616, 0.2375743054], [-0.2495892950, -0.3832854473, 1.0845181219], [ 1.7813504266, 1.6178237031, 0.8162655711], [-0.1985249206, -0.8343333301, 0.0538864941], [-1.7011985145, -0.1263820964, 0.4776976918], [-0.4319462812, 1.4104420482, 0.7886291537], [ 0.2178372997, -0.9499557344, 0.0357871187], [-0.6294854565, -1.3078893852, 0.7653357688], [ 1.7952608455, 0.6281269104, 0.2727652452], [ 1.4168575317, 1.0683357171, 1.1016025378], [ 1.4637371396, 0.9463877418, 1.1846214562], [-0.5263668798, 1.7315156631, 1.4428514068], [-1.2197352481, 0.9144146579, 1.0727263474], [-0.1389358881, 0.1092805780, 0.7350208828], [ 1.5293954595, 0.0030278255, 1.2472867347], [-0.5258728625, 1.3782633069, 1.3495508831], [-0.1403562064, 0.2437382535, 1.3804956588], [ 0.8055826339, -0.0482092025, 0.3327165165], [-0.6311979224, 0.7184578971, 0.2491045282], [ 1.4685857879, -0.8347049536, 1.3670667538], [-0.6855727502, 1.6465021616, 1.0593087096], [ 0.0152957411, 0.0638919221, 0.9771215985], ] def minmax_circle(circles) xmin = circles.map {|xc, yc, radius| xc - radius}.min xmax = circles.map {|xc, yc, radius| xc + radius}.max ymin = circles.map {|xc, yc, radius| yc - radius}.min ymax = circles.map {|xc, yc, radius| yc + radius}.max [xmin, xmax, ymin, ymax] end def select_circle(circles) circles = circles.sort_by{|cx,cy,r| -r} size = circles.size select = [*0...size] for i in 0...size-1 xi,yi,ri = circles[i].to_a for j in i+1...size xj,yj,rj = circles[j].to_a select -= [j] if (xi-xj)**2 + (yi-yj)**2 <= (ri-rj)**2 end end circles.values_at(*select) end circles = select_circle(circles)
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically?
public class CirclesTotalArea { private static double distSq(double x1, double y1, double x2, double y2) { return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); } private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) { double r2 = circ[2] * circ[2]; return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 && distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 && distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 && distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2; } private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) { if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] && rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; } double r2 = circ[2] + Math.max(rect[2], rect[3]); r2 = r2 * r2; return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 && distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 && distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 && distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2; } private static boolean[] surelyOutside; private static double totalArea(double[] rect, double[][] circs, int d) { int surelyOutsideCount = 0; for(int i = 0; i < circs.length; i++) { if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; } if(rectangleSurelyOutsideCircle(rect, circs[i])) { surelyOutside[i] = true; surelyOutsideCount++; } else { surelyOutside[i] = false; } } if(surelyOutsideCount == circs.length) { return 0; } if(d < 1) { return rect[2] * rect[3] / 3; } if(surelyOutsideCount > 0) { double[][] newCircs = new double[circs.length - surelyOutsideCount][3]; int loc = 0; for(int i = 0; i < circs.length; i++) { if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; } } circs = newCircs; } double w = rect[2] / 2; double h = rect[3] / 2; double[][] pieces = { { rect[0], rect[1], w, h }, { rect[0] + w, rect[1], w, h }, { rect[0], rect[1] - h, w, h }, { rect[0] + w, rect[1] - h, w, h } }; double total = 0; for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); } return total; } public static double totalArea(double[][] circs, int d) { double maxx = Double.NEGATIVE_INFINITY; double minx = Double.POSITIVE_INFINITY; double maxy = Double.NEGATIVE_INFINITY; double miny = Double.POSITIVE_INFINITY; for(double[] circ: circs) { if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; } if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; } if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; } if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; } } double[] rect = { minx, maxy, maxx - minx, maxy - miny }; surelyOutside = new boolean[circs.length]; return totalArea(rect, circs, d); } public static void main(String[] args) { double[][] circs = { { 1.6417233788, 1.6121789534, 0.0848270516 }, {-1.4944608174, 1.2077959613, 1.1039549836 }, { 0.6110294452, -0.6907087527, 0.9089162485 }, { 0.3844862411, 0.2923344616, 0.2375743054 }, {-0.2495892950, -0.3832854473, 1.0845181219 }, {1.7813504266, 1.6178237031, 0.8162655711 }, {-0.1985249206, -0.8343333301, 0.0538864941 }, {-1.7011985145, -0.1263820964, 0.4776976918 }, {-0.4319462812, 1.4104420482, 0.7886291537 }, {0.2178372997, -0.9499557344, 0.0357871187 }, {-0.6294854565, -1.3078893852, 0.7653357688 }, {1.7952608455, 0.6281269104, 0.2727652452 }, {1.4168575317, 1.0683357171, 1.1016025378 }, {1.4637371396, 0.9463877418, 1.1846214562 }, {-0.5263668798, 1.7315156631, 1.4428514068 }, {-1.2197352481, 0.9144146579, 1.0727263474 }, {-0.1389358881, 0.1092805780, 0.7350208828 }, {1.5293954595, 0.0030278255, 1.2472867347 }, {-0.5258728625, 1.3782633069, 1.3495508831 }, {-0.1403562064, 0.2437382535, 1.3804956588 }, {0.8055826339, -0.0482092025, 0.3327165165 }, {-0.6311979224, 0.7184578971, 0.2491045282 }, {1.4685857879, -0.8347049536, 1.3670667538 }, {-0.6855727502, 1.6465021616, 1.0593087096 }, {0.0152957411, 0.0638919221, 0.9771215985 } }; double ans = totalArea(circs, 24); System.out.println("Approx. area is " + ans); System.out.println("Error is " + Math.abs(21.56503660 - ans)); } }
circles = [ [ 1.6417233788, 1.6121789534, 0.0848270516], [-1.4944608174, 1.2077959613, 1.1039549836], [ 0.6110294452, -0.6907087527, 0.9089162485], [ 0.3844862411, 0.2923344616, 0.2375743054], [-0.2495892950, -0.3832854473, 1.0845181219], [ 1.7813504266, 1.6178237031, 0.8162655711], [-0.1985249206, -0.8343333301, 0.0538864941], [-1.7011985145, -0.1263820964, 0.4776976918], [-0.4319462812, 1.4104420482, 0.7886291537], [ 0.2178372997, -0.9499557344, 0.0357871187], [-0.6294854565, -1.3078893852, 0.7653357688], [ 1.7952608455, 0.6281269104, 0.2727652452], [ 1.4168575317, 1.0683357171, 1.1016025378], [ 1.4637371396, 0.9463877418, 1.1846214562], [-0.5263668798, 1.7315156631, 1.4428514068], [-1.2197352481, 0.9144146579, 1.0727263474], [-0.1389358881, 0.1092805780, 0.7350208828], [ 1.5293954595, 0.0030278255, 1.2472867347], [-0.5258728625, 1.3782633069, 1.3495508831], [-0.1403562064, 0.2437382535, 1.3804956588], [ 0.8055826339, -0.0482092025, 0.3327165165], [-0.6311979224, 0.7184578971, 0.2491045282], [ 1.4685857879, -0.8347049536, 1.3670667538], [-0.6855727502, 1.6465021616, 1.0593087096], [ 0.0152957411, 0.0638919221, 0.9771215985], ] def minmax_circle(circles) xmin = circles.map {|xc, yc, radius| xc - radius}.min xmax = circles.map {|xc, yc, radius| xc + radius}.max ymin = circles.map {|xc, yc, radius| yc - radius}.min ymax = circles.map {|xc, yc, radius| yc + radius}.max [xmin, xmax, ymin, ymax] end def select_circle(circles) circles = circles.sort_by{|cx,cy,r| -r} size = circles.size select = [*0...size] for i in 0...size-1 xi,yi,ri = circles[i].to_a for j in i+1...size xj,yj,rj = circles[j].to_a select -= [j] if (xi-xj)**2 + (yi-yj)**2 <= (ri-rj)**2 end end circles.values_at(*select) end circles = select_circle(circles)
Write the same code in Ruby as shown below in Java.
public class Factorion { public static void main(String [] args){ System.out.println("Base 9:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,9); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 10:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,10); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 11:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,11); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 12:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,12); if(multiplied == i){ System.out.print(i + "\t"); } } } public static int factorialRec(int n){ int result = 1; return n == 0 ? result : result * n * factorialRec(n-1); } public static int operate(String s, int base){ int sum = 0; String strx = fromDeci(base, Integer.parseInt(s)); for(int i = 0; i < strx.length(); i++){ if(strx.charAt(i) == 'A'){ sum += factorialRec(10); }else if(strx.charAt(i) == 'B') { sum += factorialRec(11); }else if(strx.charAt(i) == 'C') { sum += factorialRec(12); }else { sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base)); } } return sum; } static char reVal(int num) { if (num >= 0 && num <= 9) return (char)(num + 48); else return (char)(num - 10 + 65); } static String fromDeci(int base, int num){ StringBuilder s = new StringBuilder(); while (num > 0) { s.append(reVal(num % base)); num /= base; } return new String(new StringBuilder(s).reverse()); } }
def factorion?(n, base) n.digits(base).sum{|digit| (1..digit).inject(1, :*)} == n end (9..12).each do |base| puts "Base end
Port the following code from Java to Ruby with equivalent syntax and logic.
public class Factorion { public static void main(String [] args){ System.out.println("Base 9:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,9); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 10:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,10); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 11:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,11); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 12:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,12); if(multiplied == i){ System.out.print(i + "\t"); } } } public static int factorialRec(int n){ int result = 1; return n == 0 ? result : result * n * factorialRec(n-1); } public static int operate(String s, int base){ int sum = 0; String strx = fromDeci(base, Integer.parseInt(s)); for(int i = 0; i < strx.length(); i++){ if(strx.charAt(i) == 'A'){ sum += factorialRec(10); }else if(strx.charAt(i) == 'B') { sum += factorialRec(11); }else if(strx.charAt(i) == 'C') { sum += factorialRec(12); }else { sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base)); } } return sum; } static char reVal(int num) { if (num >= 0 && num <= 9) return (char)(num + 48); else return (char)(num - 10 + 65); } static String fromDeci(int base, int num){ StringBuilder s = new StringBuilder(); while (num > 0) { s.append(reVal(num % base)); num /= base; } return new String(new StringBuilder(s).reverse()); } }
def factorion?(n, base) n.digits(base).sum{|digit| (1..digit).inject(1, :*)} == n end (9..12).each do |base| puts "Base end
Translate this program into Ruby but keep the logic exactly as in Java.
public class DivisorSum { private static long divisorSum(long n) { var total = 1L; var power = 2L; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (long p = 3; p * p <= n; p += 2) { long sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; } total *= sum; } if (n > 1) { total *= n + 1; } return total; } public static void main(String[] args) { final long limit = 100; System.out.printf("Sum of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; ++n) { System.out.printf("%4d", divisorSum(n)); if (n % 10 == 0) { System.out.println(); } } } }
def divisor_sum(n) total = 1 power = 2 while (n & 1) == 0 total = total + power power = power << 1 n = n >> 1 end p = 3 while p * p <= n sum = 1 power = p while n % p == 0 sum = sum + power power = power * p n = (n / p).floor end total = total * sum p = p + 2 end if n > 1 then total = total * (n + 1) end return total end LIMIT = 100 print "Sum of divisors for the first ", LIMIT, " positive integers:\n" for n in 1 .. LIMIT print "%4d" % [divisor_sum(n)] if n % 10 == 0 then print "\n" end end
Change the programming language of this snippet from Java to Ruby without modifying what it does.
public class DivisorSum { private static long divisorSum(long n) { var total = 1L; var power = 2L; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (long p = 3; p * p <= n; p += 2) { long sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; } total *= sum; } if (n > 1) { total *= n + 1; } return total; } public static void main(String[] args) { final long limit = 100; System.out.printf("Sum of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; ++n) { System.out.printf("%4d", divisorSum(n)); if (n % 10 == 0) { System.out.println(); } } } }
def divisor_sum(n) total = 1 power = 2 while (n & 1) == 0 total = total + power power = power << 1 n = n >> 1 end p = 3 while p * p <= n sum = 1 power = p while n % p == 0 sum = sum + power power = power * p n = (n / p).floor end total = total * sum p = p + 2 end if n > 1 then total = total * (n + 1) end return total end LIMIT = 100 print "Sum of divisors for the first ", LIMIT, " positive integers:\n" for n in 1 .. LIMIT print "%4d" % [divisor_sum(n)] if n % 10 == 0 then print "\n" end end
Convert this Java block to Ruby, preserving its control flow and logic.
import java.util.*; public class SortComp1 { public static void main(String[] args) { List<String> items = Arrays.asList("violet", "red", "green", "indigo", "blue", "yellow", "orange"); List<String> sortedItems = new ArrayList<>(); Comparator<String> interactiveCompare = new Comparator<String>() { int count = 0; Scanner s = new Scanner(System.in); public int compare(String s1, String s2) { System.out.printf("(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: ", ++count, s1, s2); return s.nextInt(); } }; for (String item : items) { System.out.printf("Inserting '%s' into %s\n", item, sortedItems); int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare); if (spotToInsert < 0) spotToInsert = ~spotToInsert; sortedItems.add(spotToInsert, item); } System.out.println(sortedItems); } }
items = ["violet", "red", "green", "indigo", "blue", "yellow", "orange"] count = 0 sortedItems = [] items.each {|item| puts "Inserting ' spotToInsert = sortedItems.bsearch_index{|x| count += 1 print "( gets.start_with?('y') } || sortedItems.length sortedItems.insert(spotToInsert, item) } p sortedItems
Write the same algorithm in Ruby as shown in this Java implementation.
import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class FermatNumbers { public static void main(String[] args) { System.out.println("First 10 Fermat numbers:"); for ( int i = 0 ; i < 10 ; i++ ) { System.out.printf("F[%d] = %s\n", i, fermat(i)); } System.out.printf("%nFirst 12 Fermat numbers factored:%n"); for ( int i = 0 ; i < 13 ; i++ ) { System.out.printf("F[%d] = %s\n", i, getString(getFactors(i, fermat(i)))); } } private static String getString(List<BigInteger> factors) { if ( factors.size() == 1 ) { return factors.get(0) + " (PRIME)"; } return factors.stream().map(v -> v.toString()).map(v -> v.startsWith("-") ? "(C" + v.replace("-", "") + ")" : v).collect(Collectors.joining(" * ")); } private static Map<Integer, String> COMPOSITE = new HashMap<>(); static { COMPOSITE.put(9, "5529"); COMPOSITE.put(10, "6078"); COMPOSITE.put(11, "1037"); COMPOSITE.put(12, "5488"); COMPOSITE.put(13, "2884"); } private static List<BigInteger> getFactors(int fermatIndex, BigInteger n) { List<BigInteger> factors = new ArrayList<>(); BigInteger factor = BigInteger.ONE; while ( true ) { if ( n.isProbablePrime(100) ) { factors.add(n); break; } else { if ( COMPOSITE.containsKey(fermatIndex) ) { String stop = COMPOSITE.get(fermatIndex); if ( n.toString().startsWith(stop) ) { factors.add(new BigInteger("-" + n.toString().length())); break; } } factor = pollardRhoFast(n); if ( factor.compareTo(BigInteger.ZERO) == 0 ) { factors.add(n); break; } else { factors.add(factor); n = n.divide(factor); } } } return factors; } private static final BigInteger TWO = BigInteger.valueOf(2); private static BigInteger fermat(int n) { return TWO.pow((int)Math.pow(2, n)).add(BigInteger.ONE); } @SuppressWarnings("unused") private static BigInteger pollardRho(BigInteger n) { BigInteger x = BigInteger.valueOf(2); BigInteger y = BigInteger.valueOf(2); BigInteger d = BigInteger.ONE; while ( d.compareTo(BigInteger.ONE) == 0 ) { x = pollardRhoG(x, n); y = pollardRhoG(pollardRhoG(y, n), n); d = x.subtract(y).abs().gcd(n); } if ( d.compareTo(n) == 0 ) { return BigInteger.ZERO; } return d; } private static BigInteger pollardRhoFast(BigInteger n) { long start = System.currentTimeMillis(); BigInteger x = BigInteger.valueOf(2); BigInteger y = BigInteger.valueOf(2); BigInteger d = BigInteger.ONE; int count = 0; BigInteger z = BigInteger.ONE; while ( true ) { x = pollardRhoG(x, n); y = pollardRhoG(pollardRhoG(y, n), n); d = x.subtract(y).abs(); z = z.multiply(d).mod(n); count++; if ( count == 100 ) { d = z.gcd(n); if ( d.compareTo(BigInteger.ONE) != 0 ) { break; } z = BigInteger.ONE; count = 0; } } long end = System.currentTimeMillis(); System.out.printf(" Pollard rho try factor %s elapsed time = %d ms (factor = %s).%n", n, (end-start), d); if ( d.compareTo(n) == 0 ) { return BigInteger.ZERO; } return d; } private static BigInteger pollardRhoG(BigInteger x, BigInteger n) { return x.multiply(x).add(BigInteger.ONE).mod(n); } }
require "big" def factors(n) factors = `factor factors.group_by(&.itself).map { |prime, exp| [prime, exp.size] } end def fermat(n); (1.to_big_i << (1 << n)) | 1 end puts "Value for each Fermat Number F0 .. F9." (0..9).each { |n| puts "F puts puts "Factors for each Fermat Number F0 .. F8." (0..8).each { |n| puts "F
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version.
public class BeadSort { public static void main(String[] args) { BeadSort now=new BeadSort(); int[] arr=new int[(int)(Math.random()*11)+5]; for(int i=0;i<arr.length;i++) arr[i]=(int)(Math.random()*10); System.out.print("Unsorted: "); now.display1D(arr); int[] sort=now.beadSort(arr); System.out.print("Sorted: "); now.display1D(sort); } int[] beadSort(int[] arr) { int max=a[0]; for(int i=1;i<arr.length;i++) if(arr[i]>max) max=arr[i]; char[][] grid=new char[arr.length][max]; int[] levelcount=new int[max]; for(int i=0;i<max;i++) { levelcount[i]=0; for(int j=0;j<arr.length;j++) grid[j][i]='_'; } for(int i=0;i<arr.length;i++) { int num=arr[i]; for(int j=0;num>0;j++) { grid[levelcount[j]++][j]='*'; num--; } } System.out.println(); display2D(grid); int[] sorted=new int[arr.length]; for(int i=0;i<arr.length;i++) { int putt=0; for(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++) putt++; sorted[i]=putt; } return sorted; } void display1D(int[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } void display1D(char[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } void display2D(char[][] arr) { for(int i=0;i<arr.length;i++) display1D(arr[i]); System.out.println(); } }
class Array def beadsort map {|e| [1] * e}.columns.columns.map(&:length) end def columns y = length x = map(&:length).max Array.new(x) do |row| Array.new(y) { |column| self[column][row] }.compact end end end p [5,3,1,7,4,1,1].beadsort
Convert this Java block to Ruby, preserving its control flow and logic.
import java.util.*; import java.util.stream.IntStream; public class CastingOutNines { public static void main(String[] args) { System.out.println(castOut(16, 1, 255)); System.out.println(castOut(10, 1, 99)); System.out.println(castOut(17, 1, 288)); } static List<Integer> castOut(int base, int start, int end) { int[] ran = IntStream .range(0, base - 1) .filter(x -> x % (base - 1) == (x * x) % (base - 1)) .toArray(); int x = start / (base - 1); List<Integer> result = new ArrayList<>(); while (true) { for (int n : ran) { int k = (base - 1) * x + n; if (k < start) continue; if (k > end) return result; result.add(k); } x++; } } }
N = 2 base = 10 c1 = 0 c2 = 0 for k in 1 .. (base ** N) - 1 c1 = c1 + 1 if k % (base - 1) == (k * k) % (base - 1) then c2 = c2 + 1 print "%d " % [k] end end puts print "Trying %d numbers instead of %d numbers saves %f%%" % [c2, c1, 100.0 - 100.0 * c2 / c1]
Convert this Java snippet to Ruby and keep its semantics consistent.
import java.util.*; import java.util.stream.IntStream; public class CastingOutNines { public static void main(String[] args) { System.out.println(castOut(16, 1, 255)); System.out.println(castOut(10, 1, 99)); System.out.println(castOut(17, 1, 288)); } static List<Integer> castOut(int base, int start, int end) { int[] ran = IntStream .range(0, base - 1) .filter(x -> x % (base - 1) == (x * x) % (base - 1)) .toArray(); int x = start / (base - 1); List<Integer> result = new ArrayList<>(); while (true) { for (int n : ran) { int k = (base - 1) * x + n; if (k < start) continue; if (k > end) return result; result.add(k); } x++; } } }
N = 2 base = 10 c1 = 0 c2 = 0 for k in 1 .. (base ** N) - 1 c1 = c1 + 1 if k % (base - 1) == (k * k) % (base - 1) then c2 = c2 + 1 print "%d " % [k] end end puts print "Trying %d numbers instead of %d numbers saves %f%%" % [c2, c1, 100.0 - 100.0 * c2 / c1]
Write a version of this Java function in Ruby with identical behavior.
import java.io.*; import java.text.*; import java.util.*; public class SimpleDatabase { final static String filename = "simdb.csv"; public static void main(String[] args) { if (args.length < 1 || args.length > 3) { printUsage(); return; } switch (args[0].toLowerCase()) { case "add": addItem(args); break; case "latest": printLatest(args); break; case "all": printAll(); break; default: printUsage(); break; } } private static class Item implements Comparable<Item>{ final String name; final String date; final String category; Item(String n, String d, String c) { name = n; date = d; category = c; } @Override public int compareTo(Item item){ return date.compareTo(item.date); } @Override public String toString() { return String.format("%s,%s,%s%n", name, date, category); } } private static void addItem(String[] input) { if (input.length < 2) { printUsage(); return; } List<Item> db = load(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = sdf.format(new Date()); String cat = (input.length == 3) ? input[2] : "none"; db.add(new Item(input[1], date, cat)); store(db); } private static void printLatest(String[] a) { List<Item> db = load(); if (db.isEmpty()) { System.out.println("No entries in database."); return; } Collections.sort(db); if (a.length == 2) { for (Item item : db) if (item.category.equals(a[1])) System.out.println(item); } else { System.out.println(db.get(0)); } } private static void printAll() { List<Item> db = load(); if (db.isEmpty()) { System.out.println("No entries in database."); return; } Collections.sort(db); for (Item item : db) System.out.println(item); } private static List<Item> load() { List<Item> db = new ArrayList<>(); try (Scanner sc = new Scanner(new File(filename))) { while (sc.hasNext()) { String[] item = sc.nextLine().split(","); db.add(new Item(item[0], item[1], item[2])); } } catch (IOException e) { System.out.println(e); } return db; } private static void store(List<Item> db) { try (FileWriter fw = new FileWriter(filename)) { for (Item item : db) fw.write(item.toString()); } catch (IOException e) { System.out.println(e); } } private static void printUsage() { System.out.println("Usage:"); System.out.println(" simdb cmd [categoryName]"); System.out.println(" add add item, followed by optional category"); System.out.println(" latest print last added item(s), followed by " + "optional category"); System.out.println(" all print all"); System.out.println(" For instance: add \"some item name\" " + "\"some category name\""); } }
require 'date' require 'json' require 'securerandom' class SimpleDatabase def initialize(dbname, *fields) @dbname = dbname @filename = @dbname + ".dat" @fields = fields @maxl = @fields.collect {|f| f.length}.max @data = { 'fields' => fields, 'items' => {}, 'history' => [], 'tags' => {}, } end attr_reader :dbname, :fields def self.open(dbname) db = new(dbname) db.read db end def read() if not File.exists?(@filename) raise ArgumentError, "Database end @data = JSON.parse(File.read(@filename)) @fields = @data['fields'] @maxl = @fields.collect {|f| f.length}.max end def write() File.open(@filename, 'w') {|f| f.write(JSON.generate(@data))} end def add(*values) id = SecureRandom.uuid @data['items'][id] = Hash[ @fields.zip(values) ] @data['history'] << [Time.now.to_f, id] id end def tag(id, *tags) tags.each do |tag| if @data['tags'][tag].nil? @data['tags'][tag] = [id] else @data['tags'][tag] << id end end id end def latest @data['history'].sort_by {|val| val[0]}.last.last end def get_item(id) @data['items'][id] end def tags() @data['tags'].keys.sort end def ids_for_tag(tag) @data['tags'][tag] end def tags_for_id(id) @data['tags'].keys.inject([]) do |tags, tag| tags << tag if @data['tags'][tag].include?(id) tags end end def display(id) item = get_item(id) fmt = "% puts fmt % ['id', id] @fields.each {|f| print fmt % [f, item[f]]} puts fmt % ['tags', tags_for_id(id).join(',')] added = @data['history'].find {|x| x[1] == id}.first puts fmt % ['date added', Time.at(added).ctime] puts "" end def each() @data['history'].each {|time, id| yield id} end def each_item_with_tag(tag) @data['tags'][tag].each {|id| yield id} end end def usage() puts <<END usage: commands: help create dbname field ... fields dbname add dbname value ... tag dbname id tag ... tags dbname list dbname [tag ...] latest dbname latest_by_tag dbname END end def open_database(args) dbname = args.shift begin SimpleDatabase.open(dbname) rescue ArgumentError => e STDERR.puts e.message exit 1 end end def process_command_line(command, *args) case command when 'help' usage when 'create' db = SimpleDatabase.new(*args) db.write puts "Database when 'fields' db = open_database(args) puts "Database puts db.fields.join(',') when 'add' db = open_database(args) id = db.add(*args) db.write puts "Database when 'tag' db = open_database(args) id = args.shift db.tag(id, *args) db.write db.display(id) when 'tags' db = open_database(args) puts "Database puts db.tags.join(',') when 'list' db = open_database(args) if args.empty? db.each {|id| db.display(id)} else args.each do |tag| puts "Items tagged db.each_item_with_tag(tag) {|id| db.display(id)} end end when 'latest' db = open_database(args) db.display(db.latest) when 'latest_by_tag' db = open_database(args) db.tags.each do |tag| puts tag db.display(db.ids_for_tag(tag).last) end else puts "Error: unknown command ' usage end end process_command_line *ARGV
Generate an equivalent Ruby version of this Java code.
package keybord.macro.demo; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; class KeyboardMacroDemo { public static void main( String [] args ) { final JFrame frame = new JFrame(); String directions = "<html><b>Ctrl-S</b> to show frame title<br>" +"<b>Ctrl-H</b> to hide it</html>"; frame.add( new JLabel(directions)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addKeyListener( new KeyAdapter(){ public void keyReleased( KeyEvent e ) { if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){ frame.setTitle("Hello there"); }else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){ frame.setTitle(""); } } }); frame.pack(); frame.setVisible(true); } }
Shoes.app do @info = para "NO KEY is PRESSED." keypress do |k| @info.replace " end end
Convert this Java block to Ruby, preserving its control flow and logic.
public class TauFunction { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } public static void main(String[] args) { final int limit = 100; System.out.printf("Count of divisors for the first %d positive integers:\n", limit); for (long n = 1; n <= limit; ++n) { System.out.printf("%3d", divisorCount(n)); if (n % 20 == 0) { System.out.println(); } } } }
require 'prime' def tau(n) = n.prime_division.inject(1){|res, (d, exp)| res *= exp + 1} (1..100).map{|n| tau(n).to_s.rjust(3) }.each_slice(20){|ar| puts ar.join}
Port the following code from Java to Ruby with equivalent syntax and logic.
public class TauFunction { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } public static void main(String[] args) { final int limit = 100; System.out.printf("Count of divisors for the first %d positive integers:\n", limit); for (long n = 1; n <= limit; ++n) { System.out.printf("%3d", divisorCount(n)); if (n % 20 == 0) { System.out.println(); } } } }
require 'prime' def tau(n) = n.prime_division.inject(1){|res, (d, exp)| res *= exp + 1} (1..100).map{|n| tau(n).to_s.rjust(3) }.each_slice(20){|ar| puts ar.join}
Maintain the same structure and functionality when rewriting this code in Ruby.
public class MöbiusFunction { public static void main(String[] args) { System.out.printf("First 199 terms of the möbius function are as follows:%n "); for ( int n = 1 ; n < 200 ; n++ ) { System.out.printf("%2d ", möbiusFunction(n)); if ( (n+1) % 20 == 0 ) { System.out.printf("%n"); } } } private static int MU_MAX = 1_000_000; private static int[] MU = null; private static int möbiusFunction(int n) { if ( MU != null ) { return MU[n]; } MU = new int[MU_MAX+1]; int sqrt = (int) Math.sqrt(MU_MAX); for ( int i = 0 ; i < MU_MAX ; i++ ) { MU[i] = 1; } for ( int i = 2 ; i <= sqrt ; i++ ) { if ( MU[i] == 1 ) { for ( int j = i ; j <= MU_MAX ; j += i ) { MU[j] *= -i; } for ( int j = i*i ; j <= MU_MAX ; j += i*i ) { MU[j] = 0; } } } for ( int i = 2 ; i <= MU_MAX ; i++ ) { if ( MU[i] == i ) { MU[i] = 1; } else if ( MU[i] == -i ) { MU[i] = -1; } else if ( MU[i] < 0 ) { MU[i] = 1; } else if ( MU[i] > 0 ) { MU[i] = -1; } } return MU[n]; } }
require 'prime' def μ(n) pd = n.prime_division return 0 unless pd.map(&:last).all?(1) pd.size.even? ? 1 : -1 end ([" "] + (1..199).map{|n|"%2s" % μ(n)}).each_slice(20){|line| puts line.join(" ") }
Write the same algorithm in Ruby as shown in this Java implementation.
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { memory[i] = 0; } ip = 0; dp = 0; } private void load(String program) { if (program.length() > MEMORY_SIZE - 2) { throw new RuntimeException("Not enough memory."); } reset(); for (; dp < program.length(); dp++) { memory[dp] = program.charAt(dp); } border = dp; dp += 1; } public void execute(String program) { load(program); char instruction = memory[ip]; while (instruction != 0) { switch (instruction) { case '>': dp++; if (dp == MEMORY_SIZE) { throw new RuntimeException("Out of memory."); } break; case '<': dp--; if (dp == border) { throw new RuntimeException("Invalid data pointer."); } break; case '+': memory[dp]++; break; case '-': memory[dp]--; break; case '.': System.out.print(memory[dp]); break; case ',': try { memory[dp] = (char) System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } break; case '[': if (memory[dp] == 0) { skipLoop(); } break; case ']': if (memory[dp] != 0) { loop(); } break; default: throw new RuntimeException("Unknown instruction."); } instruction = memory[++ip]; } } private void skipLoop() { int loopCount = 0; while (memory[ip] != 0) { if (memory[ip] == '[') { loopCount++; } else if (memory[ip] == ']') { loopCount--; if (loopCount == 0) { return; } } ip++; } if (memory[ip] == 0) { throw new RuntimeException("Unable to find a matching ']'."); } } private void loop() { int loopCount = 0; while (ip >= 0) { if (memory[ip] == ']') { loopCount++; } else if (memory[ip] == '[') { loopCount--; if (loopCount == 0) { return; } } ip--; } if (ip == -1) { throw new RuntimeException("Unable to find a matching '['."); } } public static void main(String[] args) { Interpreter interpreter = new Interpreter(); interpreter.execute(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+."); } }
define tape_length = 50_000; define eof_val = -1; define unbalanced_exit_code = 1; var cmd = 0; var cell = 0; var code = []; var loops = []; var tape = tape_length.of(0); func get_input { static input_buffer = []; input_buffer.len || (input_buffer = ((STDIN.readline \\ return eof_val).chomp.chars.map{.ord})); input_buffer.shift \\ eof_val; } func jump { var depth = 0; while (depth >= 0) { ++cmd < code.len || Sys.exit(unbalanced_exit_code); if (code[cmd] == '[') { ++depth; } elsif (code[cmd] == ']') { --depth; } } } var commands = Hash.new( '>' => { ++cell }, '<' => { --cell }, '+' => { ++tape[cell] }, '-' => { --tape[cell] }, '.' => { tape[cell].chr.print }, ',' => { tape[cell] = get_input() }, '[' => { tape[cell] ? loops.append(cmd) : jump() }, ']' => { cmd = (loops.pop - 1) }, ); STDOUT.autoflush(1); code = ARGF.slurp.chars.grep {|c| commands.exists(c)}; var code_len = code.len; while (cmd < code_len) { commands{code[cmd]}.run; cmd++; }
Generate a Ruby translation of this Java snippet without changing its computational steps.
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { memory[i] = 0; } ip = 0; dp = 0; } private void load(String program) { if (program.length() > MEMORY_SIZE - 2) { throw new RuntimeException("Not enough memory."); } reset(); for (; dp < program.length(); dp++) { memory[dp] = program.charAt(dp); } border = dp; dp += 1; } public void execute(String program) { load(program); char instruction = memory[ip]; while (instruction != 0) { switch (instruction) { case '>': dp++; if (dp == MEMORY_SIZE) { throw new RuntimeException("Out of memory."); } break; case '<': dp--; if (dp == border) { throw new RuntimeException("Invalid data pointer."); } break; case '+': memory[dp]++; break; case '-': memory[dp]--; break; case '.': System.out.print(memory[dp]); break; case ',': try { memory[dp] = (char) System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } break; case '[': if (memory[dp] == 0) { skipLoop(); } break; case ']': if (memory[dp] != 0) { loop(); } break; default: throw new RuntimeException("Unknown instruction."); } instruction = memory[++ip]; } } private void skipLoop() { int loopCount = 0; while (memory[ip] != 0) { if (memory[ip] == '[') { loopCount++; } else if (memory[ip] == ']') { loopCount--; if (loopCount == 0) { return; } } ip++; } if (memory[ip] == 0) { throw new RuntimeException("Unable to find a matching ']'."); } } private void loop() { int loopCount = 0; while (ip >= 0) { if (memory[ip] == ']') { loopCount++; } else if (memory[ip] == '[') { loopCount--; if (loopCount == 0) { return; } } ip--; } if (ip == -1) { throw new RuntimeException("Unable to find a matching '['."); } } public static void main(String[] args) { Interpreter interpreter = new Interpreter(); interpreter.execute(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+."); } }
define tape_length = 50_000; define eof_val = -1; define unbalanced_exit_code = 1; var cmd = 0; var cell = 0; var code = []; var loops = []; var tape = tape_length.of(0); func get_input { static input_buffer = []; input_buffer.len || (input_buffer = ((STDIN.readline \\ return eof_val).chomp.chars.map{.ord})); input_buffer.shift \\ eof_val; } func jump { var depth = 0; while (depth >= 0) { ++cmd < code.len || Sys.exit(unbalanced_exit_code); if (code[cmd] == '[') { ++depth; } elsif (code[cmd] == ']') { --depth; } } } var commands = Hash.new( '>' => { ++cell }, '<' => { --cell }, '+' => { ++tape[cell] }, '-' => { --tape[cell] }, '.' => { tape[cell].chr.print }, ',' => { tape[cell] = get_input() }, '[' => { tape[cell] ? loops.append(cmd) : jump() }, ']' => { cmd = (loops.pop - 1) }, ); STDOUT.autoflush(1); code = ARGF.slurp.chars.grep {|c| commands.exists(c)}; var code_len = code.len; while (cmd < code_len) { commands{code[cmd]}.run; cmd++; }
Write the same algorithm in Ruby as shown in this Java implementation.
public class MertensFunction { public static void main(String[] args) { System.out.printf("First 199 terms of the merten function are as follows:%n "); for ( int n = 1 ; n < 200 ; n++ ) { System.out.printf("%2d ", mertenFunction(n)); if ( (n+1) % 20 == 0 ) { System.out.printf("%n"); } } for ( int exponent = 3 ; exponent<= 8 ; exponent++ ) { int zeroCount = 0; int zeroCrossingCount = 0; int positiveCount = 0; int negativeCount = 0; int mSum = 0; int mMin = Integer.MAX_VALUE; int mMinIndex = 0; int mMax = Integer.MIN_VALUE; int mMaxIndex = 0; int nMax = (int) Math.pow(10, exponent); for ( int n = 1 ; n <= nMax ; n++ ) { int m = mertenFunction(n); mSum += m; if ( m < mMin ) { mMin = m; mMinIndex = n; } if ( m > mMax ) { mMax = m; mMaxIndex = n; } if ( m > 0 ) { positiveCount++; } if ( m < 0 ) { negativeCount++; } if ( m == 0 ) { zeroCount++; } if ( m == 0 && mertenFunction(n - 1) != 0 ) { zeroCrossingCount++; } } System.out.printf("%nFor M(x) with x from 1 to %,d%n", nMax); System.out.printf("The maximum of M(x) is M(%,d) = %,d.%n", mMaxIndex, mMax); System.out.printf("The minimum of M(x) is M(%,d) = %,d.%n", mMinIndex, mMin); System.out.printf("The sum of M(x) is %,d.%n", mSum); System.out.printf("The count of positive M(x) is %,d, count of negative M(x) is %,d.%n", positiveCount, negativeCount); System.out.printf("M(x) has %,d zeroes in the interval.%n", zeroCount); System.out.printf("M(x) has %,d crossings in the interval.%n", zeroCrossingCount); } } private static int MU_MAX = 100_000_000; private static int[] MU = null; private static int[] MERTEN = null; private static int mertenFunction(int n) { if ( MERTEN != null ) { return MERTEN[n]; } MU = new int[MU_MAX+1]; MERTEN = new int[MU_MAX+1]; MERTEN[1] = 1; int sqrt = (int) Math.sqrt(MU_MAX); for ( int i = 0 ; i < MU_MAX ; i++ ) { MU[i] = 1; } for ( int i = 2 ; i <= sqrt ; i++ ) { if ( MU[i] == 1 ) { for ( int j = i ; j <= MU_MAX ; j += i ) { MU[j] *= -i; } for ( int j = i*i ; j <= MU_MAX ; j += i*i ) { MU[j] = 0; } } } int sum = 1; for ( int i = 2 ; i <= MU_MAX ; i++ ) { if ( MU[i] == i ) { MU[i] = 1; } else if ( MU[i] == -i ) { MU[i] = -1; } else if ( MU[i] < 0 ) { MU[i] = 1; } else if ( MU[i] > 0 ) { MU[i] = -1; } sum += MU[i]; MERTEN[i] = sum; } return MERTEN[n]; } }
require 'prime' def μ(n) return 1 if self == 1 pd = n.prime_division return 0 unless pd.map(&:last).all?(1) pd.size.even? ? 1 : -1 end def M(n) (1..n).sum{|n| μ(n)} end ([" "] + (1..199).map{|n|"%2s" % M(n)}).each_slice(20){|line| puts line.join(" ") } ar = (1..1000).map{|n| M(n)} puts "\nThe Mertens function is zero puts "it crosses zero
Write a version of this Java function in Ruby with identical behavior.
public class ProductOfDivisors { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } private static long divisorProduct(long n) { return (long) Math.pow(n, divisorCount(n) / 2.0); } public static void main(String[] args) { final long limit = 50; System.out.printf("Product of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; n++) { System.out.printf("%11d", divisorProduct(n)); if (n % 5 == 0) { System.out.println(); } } } }
def divisor_count(n) total = 1 while n % 2 == 0 do total = total + 1 n = n >> 1 end p = 3 while p * p <= n do count = 1 while n % p == 0 do count = count + 1 n = n / p end total = total * count p = p + 2 end if n > 1 then total = total * 2 end return total end def divisor_product(n) return (n ** (divisor_count(n) / 2.0)).floor end LIMIT = 50 print "Product of divisors for the first ", LIMIT, " positive integers:\n" for n in 1 .. LIMIT print "%11d" % [divisor_product(n)] if n % 5 == 0 then print "\n" end end
Change the following Java code into Ruby without altering its purpose.
public class ProductOfDivisors { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } private static long divisorProduct(long n) { return (long) Math.pow(n, divisorCount(n) / 2.0); } public static void main(String[] args) { final long limit = 50; System.out.printf("Product of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; n++) { System.out.printf("%11d", divisorProduct(n)); if (n % 5 == 0) { System.out.println(); } } } }
def divisor_count(n) total = 1 while n % 2 == 0 do total = total + 1 n = n >> 1 end p = 3 while p * p <= n do count = 1 while n % p == 0 do count = count + 1 n = n / p end total = total * count p = p + 2 end if n > 1 then total = total * 2 end return total end def divisor_product(n) return (n ** (divisor_count(n) / 2.0)).floor end LIMIT = 50 print "Product of divisors for the first ", LIMIT, " positive integers:\n" for n in 1 .. LIMIT print "%11d" % [divisor_product(n)] if n % 5 == 0 then print "\n" end end
Port the following code from Java to Ruby with equivalent syntax and logic.
import java.util.*; public class ErdosPrimes { public static void main(String[] args) { boolean[] sieve = primeSieve(1000000); int maxPrint = 2500; int maxCount = 7875; System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint); for (int count = 0, prime = 1; count < maxCount; ++prime) { if (erdos(sieve, prime)) { ++count; if (prime < maxPrint) { System.out.printf("%6d", prime); if (count % 10 == 0) System.out.println(); } if (count == maxCount) System.out.printf("\n\nThe %dth Erd\u0151s prime is %d.\n", maxCount, prime); } } } private static boolean erdos(boolean[] sieve, int p) { if (!sieve[p]) return false; for (int k = 1, f = 1; f < p; ++k, f *= k) { if (sieve[p - f]) return false; } return true; } private static boolean[] primeSieve(int limit) { boolean[] sieve = new boolean[limit]; Arrays.fill(sieve, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (int i = 4; i < limit; i += 2) sieve[i] = false; for (int p = 3; ; p += 2) { int q = p * p; if (q >= limit) break; if (sieve[p]) { int inc = 2 * p; for (; q < limit; q += inc) sieve[q] = false; } } return sieve; } }
func is_erdos_prime(p) { return true if p==2 return false if !p.is_prime var f = 1 for (var k = 2; f < p; k++) { p - f -> is_composite || return false f *= k } return true } say ("Erdős primes <= 2500: ", 1..2500 -> grep(is_erdos_prime)) say ("The 7875th Erdős prime is: ", is_erdos_prime.nth(7875))
Rewrite the snippet below in Ruby so it works the same as the original Java code.
import java.util.*; public class ErdosPrimes { public static void main(String[] args) { boolean[] sieve = primeSieve(1000000); int maxPrint = 2500; int maxCount = 7875; System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint); for (int count = 0, prime = 1; count < maxCount; ++prime) { if (erdos(sieve, prime)) { ++count; if (prime < maxPrint) { System.out.printf("%6d", prime); if (count % 10 == 0) System.out.println(); } if (count == maxCount) System.out.printf("\n\nThe %dth Erd\u0151s prime is %d.\n", maxCount, prime); } } } private static boolean erdos(boolean[] sieve, int p) { if (!sieve[p]) return false; for (int k = 1, f = 1; f < p; ++k, f *= k) { if (sieve[p - f]) return false; } return true; } private static boolean[] primeSieve(int limit) { boolean[] sieve = new boolean[limit]; Arrays.fill(sieve, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (int i = 4; i < limit; i += 2) sieve[i] = false; for (int p = 3; ; p += 2) { int q = p * p; if (q >= limit) break; if (sieve[p]) { int inc = 2 * p; for (; q < limit; q += inc) sieve[q] = false; } } return sieve; } }
func is_erdos_prime(p) { return true if p==2 return false if !p.is_prime var f = 1 for (var k = 2; f < p; k++) { p - f -> is_composite || return false f *= k } return true } say ("Erdős primes <= 2500: ", 1..2500 -> grep(is_erdos_prime)) say ("The 7875th Erdős prime is: ", is_erdos_prime.nth(7875))
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically?
public enum Pip { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace }
class Card SUITS = %i[ Clubs Hearts Spades Diamonds ] PIPS = %i[ 2 3 4 5 6 7 8 9 10 Jack Queen King Ace ] @@suit_value = Hash[ SUITS.each_with_index.to_a ] @@pip_value = Hash[ PIPS.each_with_index.to_a ] attr_reader :pip, :suit def initialize(pip,suit) @pip = pip @suit = suit end def to_s " end def <=>(other) (@@suit_value[@suit] <=> @@suit_value[other.suit]).nonzero? or @@pip_value[@pip] <=> @@pip_value[other.pip] end end class Deck def initialize @deck = Card::SUITS.product(Card::PIPS).map{|suit,pip| Card.new(pip,suit)} end def to_s @deck.inspect end def shuffle! @deck.shuffle! self end def deal(*args) @deck.shift(*args) end end deck = Deck.new.shuffle! puts card = deck.deal hand = deck.deal(5) puts hand.join(", ") puts hand.sort.join(", ")
Write the same algorithm in Ruby as shown in this Java implementation.
import java.util.ArrayList; import java.util.List; public class PerfectTotientNumbers { public static void main(String[] args) { computePhi(); int n = 20; System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n)); } private static final List<Integer> perfectTotient(int n) { int test = 2; List<Integer> results = new ArrayList<Integer>(); for ( int i = 0 ; i < n ; test++ ) { int phiLoop = test; int sum = 0; do { phiLoop = phi[phiLoop]; sum += phiLoop; } while ( phiLoop > 1); if ( sum == test ) { i++; results.add(test); } } return results; } private static final int max = 100000; private static final int[] phi = new int[max+1]; private static final void computePhi() { for ( int i = 1 ; i <= max ; i++ ) { phi[i] = i; } for ( int i = 2 ; i <= max ; i++ ) { if (phi[i] < i) continue; for ( int j = i ; j <= max ; j += i ) { phi[j] -= phi[j] / i; } } } }
require "prime" class Integer def φ prime_division.inject(1) {|res, (pr, exp)| res *= (pr-1) * pr**(exp-1) } end def perfect_totient? f, sum = self, 0 until f == 1 do f = f.φ sum += f end self == sum end end puts (1..).lazy.select(&:perfect_totient?).first(20).join(", ")
Port the following code from Java to Ruby with equivalent syntax and logic.
import java.util.ArrayList; import java.util.List; public class PerfectTotientNumbers { public static void main(String[] args) { computePhi(); int n = 20; System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n)); } private static final List<Integer> perfectTotient(int n) { int test = 2; List<Integer> results = new ArrayList<Integer>(); for ( int i = 0 ; i < n ; test++ ) { int phiLoop = test; int sum = 0; do { phiLoop = phi[phiLoop]; sum += phiLoop; } while ( phiLoop > 1); if ( sum == test ) { i++; results.add(test); } } return results; } private static final int max = 100000; private static final int[] phi = new int[max+1]; private static final void computePhi() { for ( int i = 1 ; i <= max ; i++ ) { phi[i] = i; } for ( int i = 2 ; i <= max ; i++ ) { if (phi[i] < i) continue; for ( int j = i ; j <= max ; j += i ) { phi[j] -= phi[j] / i; } } } }
require "prime" class Integer def φ prime_division.inject(1) {|res, (pr, exp)| res *= (pr-1) * pr**(exp-1) } end def perfect_totient? f, sum = self, 0 until f == 1 do f = f.φ sum += f end self == sum end end puts (1..).lazy.select(&:perfect_totient?).first(20).join(", ")
Produce a language-to-language conversion: from Java to Ruby, same semantics.
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class LahNumbers { public static void main(String[] args) { System.out.println("Show the unsigned Lah numbers up to n = 12:"); for ( int n = 0 ; n <= 12 ; n++ ) { System.out.printf("%5s", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%12s", lahNumber(n, k)); } System.out.printf("%n"); } System.out.println("Show the maximum value of L(100, k):"); int n = 100; BigInteger max = BigInteger.ZERO; for ( int k = 0 ; k <= n ; k++ ) { max = max.max(lahNumber(n, k)); } System.out.printf("%s", max); } private static Map<String,BigInteger> CACHE = new HashMap<>(); private static BigInteger lahNumber(int n, int k) { String key = n + "," + k; if ( CACHE.containsKey(key) ) { return CACHE.get(key); } BigInteger result; if ( n == 0 && k == 0 ) { result = BigInteger.ONE; } else if ( k == 0 ) { result = BigInteger.ZERO; } else if ( k > n ) { result = BigInteger.ZERO; } else if ( n == 1 && k == 1 ) { result = BigInteger.ONE; } else { result = BigInteger.valueOf(n-1+k).multiply(lahNumber(n-1,k)).add(lahNumber(n-1,k-1)); } CACHE.put(key, result); return result; } }
def fact(n) = n.zero? ? 1 : 1.upto(n).inject(&:*) def lah(n, k) case k when 1 then fact(n) when n then 1 when (..1),(n..) then 0 else n<1 ? 0 : (fact(n)*fact(n-1)) / (fact(k)*fact(k-1)) / fact(n-k) end end r = (0..12) puts "Unsigned Lah numbers: L(n, k):" puts "n/k r.each do |row| print "%-4s" % row puts " end puts "\nMaximum value from the L(100, *) row:"; puts (1..100).map{|a| lah(100,a)}.max
Generate a Ruby translation of this Java snippet without changing its computational steps.
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class LahNumbers { public static void main(String[] args) { System.out.println("Show the unsigned Lah numbers up to n = 12:"); for ( int n = 0 ; n <= 12 ; n++ ) { System.out.printf("%5s", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%12s", lahNumber(n, k)); } System.out.printf("%n"); } System.out.println("Show the maximum value of L(100, k):"); int n = 100; BigInteger max = BigInteger.ZERO; for ( int k = 0 ; k <= n ; k++ ) { max = max.max(lahNumber(n, k)); } System.out.printf("%s", max); } private static Map<String,BigInteger> CACHE = new HashMap<>(); private static BigInteger lahNumber(int n, int k) { String key = n + "," + k; if ( CACHE.containsKey(key) ) { return CACHE.get(key); } BigInteger result; if ( n == 0 && k == 0 ) { result = BigInteger.ONE; } else if ( k == 0 ) { result = BigInteger.ZERO; } else if ( k > n ) { result = BigInteger.ZERO; } else if ( n == 1 && k == 1 ) { result = BigInteger.ONE; } else { result = BigInteger.valueOf(n-1+k).multiply(lahNumber(n-1,k)).add(lahNumber(n-1,k-1)); } CACHE.put(key, result); return result; } }
def fact(n) = n.zero? ? 1 : 1.upto(n).inject(&:*) def lah(n, k) case k when 1 then fact(n) when n then 1 when (..1),(n..) then 0 else n<1 ? 0 : (fact(n)*fact(n-1)) / (fact(k)*fact(k-1)) / fact(n-k) end end r = (0..12) puts "Unsigned Lah numbers: L(n, k):" puts "n/k r.each do |row| print "%-4s" % row puts " end puts "\nMaximum value from the L(100, *) row:"; puts (1..100).map{|a| lah(100,a)}.max
Rewrite the snippet below in Ruby so it works the same as the original Java code.
import java.util.Arrays; public class TwoSum { public static void main(String[] args) { long sum = 21; int[] arr = {0, 2, 11, 19, 90}; System.out.println(Arrays.toString(twoSum(arr, sum))); } public static int[] twoSum(int[] a, long target) { int i = 0, j = a.length - 1; while (i < j) { long sum = a[i] + a[j]; if (sum == target) return new int[]{i, j}; if (sum < target) i++; else j--; } return null; } }
def two_sum(numbers, sum) numbers.each_with_index do |x,i| if j = numbers.index(sum - x) then return [i,j] end end [] end numbers = [0, 2, 11, 19, 90] p two_sum(numbers, 21) p two_sum(numbers, 25)
Write the same code in Ruby as shown below in Java.
import java.util.Arrays; public class TwoSum { public static void main(String[] args) { long sum = 21; int[] arr = {0, 2, 11, 19, 90}; System.out.println(Arrays.toString(twoSum(arr, sum))); } public static int[] twoSum(int[] a, long target) { int i = 0, j = a.length - 1; while (i < j) { long sum = a[i] + a[j]; if (sum == target) return new int[]{i, j}; if (sum < target) i++; else j--; } return null; } }
def two_sum(numbers, sum) numbers.each_with_index do |x,i| if j = numbers.index(sum - x) then return [i,j] end end [] end numbers = [0, 2, 11, 19, 90] p two_sum(numbers, 21) p two_sum(numbers, 25)
Convert this Java snippet to Ruby and keep its semantics consistent.
public class UnprimeableNumbers { private static int MAX = 10_000_000; private static boolean[] primes = new boolean[MAX]; public static void main(String[] args) { sieve(); System.out.println("First 35 unprimeable numbers:"); displayUnprimeableNumbers(35); int n = 600; System.out.printf("%nThe %dth unprimeable number = %,d%n%n", n, nthUnprimeableNumber(n)); int[] lowest = genLowest(); System.out.println("Least unprimeable number that ends in:"); for ( int i = 0 ; i <= 9 ; i++ ) { System.out.printf(" %d is %,d%n", i, lowest[i]); } } private static int[] genLowest() { int[] lowest = new int[10]; int count = 0; int test = 1; while ( count < 10 ) { test++; if ( unPrimable(test) && lowest[test % 10] == 0 ) { lowest[test % 10] = test; count++; } } return lowest; } private static int nthUnprimeableNumber(int maxCount) { int test = 1; int count = 0; int result = 0; while ( count < maxCount ) { test++; if ( unPrimable(test) ) { count++; result = test; } } return result; } private static void displayUnprimeableNumbers(int maxCount) { int test = 1; int count = 0; while ( count < maxCount ) { test++; if ( unPrimable(test) ) { count++; System.out.printf("%d ", test); } } System.out.println(); } private static boolean unPrimable(int test) { if ( primes[test] ) { return false; } String s = test + ""; for ( int i = 0 ; i < s.length() ; i++ ) { for ( int j = 0 ; j <= 9 ; j++ ) { if ( primes[Integer.parseInt(replace(s, i, j))] ) { return false; } } } return true; } private static String replace(String str, int position, int value) { char[] sChar = str.toCharArray(); sChar[position] = (char) value; return str.substring(0, position) + value + str.substring(position + 1); } private static final void sieve() { for ( int i = 2 ; i < MAX ; i++ ) { primes[i] = true; } for ( int i = 2 ; i < MAX ; i++ ) { if ( primes[i] ) { for ( int j = 2*i ; j < MAX ; j += i ) { primes[j] = false; } } } } }
require 'prime' def unprimable?(n) digits = %w(0 1 2 3 4 5 6 7 8 9) s = n.to_s size = s.size (size-1).downto(0) do |i| digits.each do |d| cand = s.dup cand[i]=d return false if cand.to_i.prime? end end true end ups = Enumerator.new {|y| (1..).each{|n| y << n if unprimable?(n)} } ar = ups.first(600) puts "First 35 unprimables:", ar[0,35].join(" ") puts "\n600th unprimable:", ar.last, "" (0..9).each do |d| print "First unprimeable with last digit puts (1..).detect{|k| unprimable?(k*10+d)}*10 + d end
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version.
public class Tau { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } public static void main(String[] args) { final long limit = 100; System.out.printf("The first %d tau numbers are:%n", limit); long count = 0; for (long n = 1; count < limit; ++n) { if (n % divisorCount(n) == 0) { System.out.printf("%6d", n); ++count; if (count % 10 == 0) { System.out.println(); } } } } }
require 'prime' taus = Enumerator.new do |y| (1..).each do |n| num_divisors = n.prime_division.inject(1){|prod, n| prod *= n[1] + 1 } y << n if n % num_divisors == 0 end end p taus.take(100)
Write the same code in Ruby as shown below in Java.
import java.math.BigInteger; public class PrimeSum { private static int digitSum(BigInteger bi) { int sum = 0; while (bi.compareTo(BigInteger.ZERO) > 0) { BigInteger[] dr = bi.divideAndRemainder(BigInteger.TEN); sum += dr[1].intValue(); bi = dr[0]; } return sum; } public static void main(String[] args) { BigInteger fiveK = BigInteger.valueOf(5_000); BigInteger bi = BigInteger.valueOf(2); while (bi.compareTo(fiveK) < 0) { if (digitSum(bi) == 25) { System.out.print(bi); System.out.print(" "); } bi = bi.nextProbablePrime(); } System.out.println(); } }
require 'prime' def digitSum(n) sum = 0 while n > 0 sum += n % 10 n /= 10 end return sum end for p in Prime.take_while { |p| p < 5000 } if digitSum(p) == 25 then print p, " " end end
Convert this Java block to Ruby, preserving its control flow and logic.
import java.math.BigInteger; public class PrimeSum { private static int digitSum(BigInteger bi) { int sum = 0; while (bi.compareTo(BigInteger.ZERO) > 0) { BigInteger[] dr = bi.divideAndRemainder(BigInteger.TEN); sum += dr[1].intValue(); bi = dr[0]; } return sum; } public static void main(String[] args) { BigInteger fiveK = BigInteger.valueOf(5_000); BigInteger bi = BigInteger.valueOf(2); while (bi.compareTo(fiveK) < 0) { if (digitSum(bi) == 25) { System.out.print(bi); System.out.print(" "); } bi = bi.nextProbablePrime(); } System.out.println(); } }
require 'prime' def digitSum(n) sum = 0 while n > 0 sum += n % 10 n /= 10 end return sum end for p in Prime.take_while { |p| p < 5000 } if digitSum(p) == 25 then print p, " " end end
Preserve the algorithm and functionality while converting the code from Java to Ruby.
public class PrimeDigits { private static boolean primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; if (r != 2 && r != 3 && r != 5 && r != 7) { return false; } n /= 10; sum += r; } return sum == 13; } public static void main(String[] args) { int c = 0; for (int i = 1; i < 1_000_000; i++) { if (primeDigitsSum13(i)) { System.out.printf("%6d ", i); if (c++ == 10) { c = 0; System.out.println(); } } } System.out.println(); } }
def primeDigitsSum13(n) sum = 0 while n > 0 r = n % 10 if r != 2 and r != 3 and r != 5 and r != 7 then return false end n = (n / 10).floor sum = sum + r end return sum == 13 end c = 0 for i in 1 .. 1000000 if primeDigitsSum13(i) then print "%6d " % [i] if c == 10 then c = 0 print "\n" else c = c + 1 end end end print "\n"
Convert this Java block to Ruby, preserving its control flow and logic.
public class PrimeDigits { private static boolean primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; if (r != 2 && r != 3 && r != 5 && r != 7) { return false; } n /= 10; sum += r; } return sum == 13; } public static void main(String[] args) { int c = 0; for (int i = 1; i < 1_000_000; i++) { if (primeDigitsSum13(i)) { System.out.printf("%6d ", i); if (c++ == 10) { c = 0; System.out.println(); } } } System.out.println(); } }
def primeDigitsSum13(n) sum = 0 while n > 0 r = n % 10 if r != 2 and r != 3 and r != 5 and r != 7 then return false end n = (n / 10).floor sum = sum + r end return sum == 13 end c = 0 for i in 1 .. 1000000 if primeDigitsSum13(i) then print "%6d " % [i] if c == 10 then c = 0 print "\n" else c = c + 1 end end end print "\n"
Rewrite the snippet below in Ruby so it works the same as the original Java code.
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class DeepCopy { public static void main(String[] args) { Person p1 = new Person("Clark", "Kent", new Address("1 World Center", "Metropolis", "NY", "010101")); Person p2 = p1; System.out.printf("Demonstrate shallow copy. Both are the same object.%n"); System.out.printf("Person p1 = %s%n", p1); System.out.printf("Person p2 = %s%n", p2); System.out.printf("Set city on person 2. City on both objects is changed.%n"); p2.getAddress().setCity("New York"); System.out.printf("Person p1 = %s%n", p1); System.out.printf("Person p2 = %s%n", p2); p1 = new Person("Clark", "Kent", new Address("1 World Center", "Metropolis", "NY", "010101")); p2 = new Person(p1); System.out.printf("%nDemonstrate copy constructor. Object p2 is a deep copy of p1.%n"); System.out.printf("Person p1 = %s%n", p1); System.out.printf("Person p2 = %s%n", p2); System.out.printf("Set city on person 2. City on objects is different.%n"); p2.getAddress().setCity("New York"); System.out.printf("Person p1 = %s%n", p1); System.out.printf("Person p2 = %s%n", p2); p2 = (Person) deepCopy(p1); System.out.printf("%nDemonstrate serialization. Object p2 is a deep copy of p1.%n"); System.out.printf("Person p1 = %s%n", p1); System.out.printf("Person p2 = %s%n", p2); System.out.printf("Set city on person 2. City on objects is different.%n"); p2.getAddress().setCity("New York"); System.out.printf("Person p1 = %s%n", p1); System.out.printf("Person p2 = %s%n", p2); p2 = (Person) p1.clone(); System.out.printf("%nDemonstrate cloning. Object p2 is a deep copy of p1.%n"); System.out.printf("Person p1 = %s%n", p1); System.out.printf("Person p2 = %s%n", p2); System.out.printf("Set city on person 2. City on objects is different.%n"); p2.getAddress().setCity("New York"); System.out.printf("Person p1 = %s%n", p1); System.out.printf("Person p2 = %s%n", p2); } private static Object deepCopy(Object object) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream outputStrm = new ObjectOutputStream(outputStream); outputStrm.writeObject(object); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); ObjectInputStream objInputStream = new ObjectInputStream(inputStream); return objInputStream.readObject(); } catch (Exception e) { e.printStackTrace(); return null; } } public static class Address implements Serializable, Cloneable { private static final long serialVersionUID = -7073778041809445593L; private String street; private String city; private String state; private String postalCode; public String getStreet() { return street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public String getPostalCode() { return postalCode; } @Override public String toString() { return "[street=" + street + ", city=" + city + ", state=" + state + ", code=" + postalCode + "]"; } public Address(String s, String c, String st, String p) { street = s; city = c; state = st; postalCode = p; } public Address(Address add) { street = add.street; city = add.city; state = add.state; postalCode = add.postalCode; } @Override public Object clone() { return new Address(this); } } public static class Person implements Serializable, Cloneable { private static final long serialVersionUID = -521810583786595050L; private String firstName; private String lastName; private Address address; public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public Address getAddress() { return address; } @Override public String toString() { return "[first name=" + firstName + ", last name=" + lastName + ", address=" + address + "]"; } public Person(String fn, String ln, Address add) { firstName = fn; lastName = ln; address = add; } public Person(Person person) { firstName = person.firstName; lastName = person.lastName; address = new Address(person.address); } @Override public Object clone() { return new Person(this); } } }
orig = { :num => 1, :ary => [2, 3] } orig[:cycle] = orig copy = Marshal.load(Marshal.dump orig) orig[:ary] << 4 orig[:rng] = (5..6) p orig p copy p [(orig.equal? orig[:cycle]), (copy.equal? copy[:cycle]), (not orig.equal? copy)]
Preserve the algorithm and functionality while converting the code from Java to Ruby.
import java.math.BigInteger; import java.util.Arrays; public class CircularPrimes { public static void main(String[] args) { System.out.println("First 19 circular primes:"); int p = 2; for (int count = 0; count < 19; ++p) { if (isCircularPrime(p)) { if (count > 0) System.out.print(", "); System.out.print(p); ++count; } } System.out.println(); System.out.println("Next 4 circular primes:"); int repunit = 1, digits = 1; for (; repunit < p; ++digits) repunit = 10 * repunit + 1; BigInteger bignum = BigInteger.valueOf(repunit); for (int count = 0; count < 4; ) { if (bignum.isProbablePrime(15)) { if (count > 0) System.out.print(", "); System.out.printf("R(%d)", digits); ++count; } ++digits; bignum = bignum.multiply(BigInteger.TEN); bignum = bignum.add(BigInteger.ONE); } System.out.println(); testRepunit(5003); testRepunit(9887); testRepunit(15073); testRepunit(25031); } private static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } private static int cycle(int n) { int m = n, p = 1; while (m >= 10) { p *= 10; m /= 10; } return m + 10 * (n % p); } private static boolean isCircularPrime(int p) { if (!isPrime(p)) return false; int p2 = cycle(p); while (p2 != p) { if (p2 < p || !isPrime(p2)) return false; p2 = cycle(p2); } return true; } private static void testRepunit(int digits) { BigInteger repunit = repunit(digits); if (repunit.isProbablePrime(15)) System.out.printf("R(%d) is probably prime.\n", digits); else System.out.printf("R(%d) is not prime.\n", digits); } private static BigInteger repunit(int digits) { char[] ch = new char[digits]; Arrays.fill(ch, '1'); return new BigInteger(new String(ch)); } }
require 'gmp' require 'prime' candidate_primes = Enumerator.new do |y| DIGS = [1,3,7,9] [2,3,5,7].each{|n| y << n.to_s} (2..).each do |size| DIGS.repeated_permutation(size) do |perm| y << perm.join if (perm == min_rotation(perm)) && GMP::Z(perm.join).probab_prime? > 0 end end end def min_rotation(ar) = Array.new(ar.size){|n| ar.rotate(n)}.min def circular?(num_str) chars = num_str.chars return GMP::Z(num_str).probab_prime? > 0 if chars.all?("1") chars.size.times.all? do GMP::Z(chars.rotate!.join).probab_prime? > 0 end end puts "First 19 circular primes:" puts candidate_primes.lazy.select{|cand| circular?(cand)}.take(19).to_a.join(", "),"" puts "First 5 prime repunits:" reps = Prime.each.lazy.select{|pr| circular?("1"*pr)}.take(5).to_a puts reps.map{|r| "R" + r.to_s}.join(", "), "" [5003, 9887, 15073, 25031].each {|rep| puts "R
Change the following Java code into Ruby without altering its purpose.
public class Frobenius { public static void main(String[] args) { final int limit = 1000000; System.out.printf("Frobenius numbers less than %d (asterisk marks primes):\n", limit); PrimeGenerator primeGen = new PrimeGenerator(1000, 100000); int prime1 = primeGen.nextPrime(); for (int count = 1; ; ++count) { int prime2 = primeGen.nextPrime(); int frobenius = prime1 * prime2 - prime1 - prime2; if (frobenius >= limit) break; System.out.printf("%6d%c%c", frobenius, isPrime(frobenius) ? '*' : ' ', count % 10 == 0 ? '\n' : ' '); prime1 = prime2; } System.out.println(); } private static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } }
require 'prime' Prime.each_cons(2) do |p1, p2| f = p1*p2-p1-p2 break if f > 10_000 puts f end
Convert the following code from Java to Ruby, ensuring the logic remains intact.
public class Frobenius { public static void main(String[] args) { final int limit = 1000000; System.out.printf("Frobenius numbers less than %d (asterisk marks primes):\n", limit); PrimeGenerator primeGen = new PrimeGenerator(1000, 100000); int prime1 = primeGen.nextPrime(); for (int count = 1; ; ++count) { int prime2 = primeGen.nextPrime(); int frobenius = prime1 * prime2 - prime1 - prime2; if (frobenius >= limit) break; System.out.printf("%6d%c%c", frobenius, isPrime(frobenius) ? '*' : ' ', count % 10 == 0 ? '\n' : ' '); prime1 = prime2; } System.out.println(); } private static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } }
require 'prime' Prime.each_cons(2) do |p1, p2| f = p1*p2-p1-p2 break if f > 10_000 puts f end
Change the following Java code into Ruby without altering its purpose.
import java.util.List; import java.util.ArrayList; import java.util.Arrays; public class PermutationSort { public static void main(String[] args) { int[] a={3,2,1,8,9,4,6}; System.out.println("Unsorted: " + Arrays.toString(a)); a=pSort(a); System.out.println("Sorted: " + Arrays.toString(a)); } public static int[] pSort(int[] a) { List<int[]> list=new ArrayList<int[]>(); permute(a,a.length,list); for(int[] x : list) if(isSorted(x)) return x; return a; } private static void permute(int[] a, int n, List<int[]> list) { if (n == 1) { int[] b=new int[a.length]; System.arraycopy(a, 0, b, 0, a.length); list.add(b); return; } for (int i = 0; i < n; i++) { swap(a, i, n-1); permute(a, n-1, list); swap(a, i, n-1); } } private static boolean isSorted(int[] a) { for(int i=1;i<a.length;i++) if(a[i-1]>a[i]) return false; return true; } private static void swap(int[] arr,int i, int j) { int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } }
class Array def permutationsort permutation.each{|perm| return perm if perm.sorted?} end def sorted? each_cons(2).all? {|a, b| a <= b} end end
Port the following code from Java to Ruby with equivalent syntax and logic.
import java.math.BigInteger; public class IntegerRoots { private static BigInteger iRoot(BigInteger base, int n) { if (base.compareTo(BigInteger.ZERO) < 0 || n <= 0) { throw new IllegalArgumentException(); } int n1 = n - 1; BigInteger n2 = BigInteger.valueOf(n); BigInteger n3 = BigInteger.valueOf(n1); BigInteger c = BigInteger.ONE; BigInteger d = n3.add(base).divide(n2); BigInteger e = n3.multiply(d).add(base.divide(d.pow(n1))).divide(n2); while (!c.equals(d) && !c.equals(e)) { c = d; d = e; e = n3.multiply(e).add(base.divide(e.pow(n1))).divide(n2); } if (d.compareTo(e) < 0) { return d; } return e; } public static void main(String[] args) { BigInteger b = BigInteger.valueOf(8); System.out.print("3rd integer root of 8 = "); System.out.println(iRoot(b, 3)); b = BigInteger.valueOf(9); System.out.print("3rd integer root of 9 = "); System.out.println(iRoot(b, 3)); b = BigInteger.valueOf(100).pow(2000).multiply(BigInteger.valueOf(2)); System.out.print("First 2001 digits of the square root of 2: "); System.out.println(iRoot(b, 2)); } }
def root(a,b) return b if b<2 a1, c = a-1, 1 f = -> x {(a1*x+b/(x**a1))/a} d = f[c] e = f[d] c, d, e = d, e, f[e] until [d,e].include?(c) [d,e].min end puts "First 2,001 digits of the square root of two:" puts root(2, 2*100**2000)
Write the same algorithm in Ruby as shown in this Java implementation.
import java.math.BigInteger; public class IntegerRoots { private static BigInteger iRoot(BigInteger base, int n) { if (base.compareTo(BigInteger.ZERO) < 0 || n <= 0) { throw new IllegalArgumentException(); } int n1 = n - 1; BigInteger n2 = BigInteger.valueOf(n); BigInteger n3 = BigInteger.valueOf(n1); BigInteger c = BigInteger.ONE; BigInteger d = n3.add(base).divide(n2); BigInteger e = n3.multiply(d).add(base.divide(d.pow(n1))).divide(n2); while (!c.equals(d) && !c.equals(e)) { c = d; d = e; e = n3.multiply(e).add(base.divide(e.pow(n1))).divide(n2); } if (d.compareTo(e) < 0) { return d; } return e; } public static void main(String[] args) { BigInteger b = BigInteger.valueOf(8); System.out.print("3rd integer root of 8 = "); System.out.println(iRoot(b, 3)); b = BigInteger.valueOf(9); System.out.print("3rd integer root of 9 = "); System.out.println(iRoot(b, 3)); b = BigInteger.valueOf(100).pow(2000).multiply(BigInteger.valueOf(2)); System.out.print("First 2001 digits of the square root of 2: "); System.out.println(iRoot(b, 2)); } }
def root(a,b) return b if b<2 a1, c = a-1, 1 f = -> x {(a1*x+b/(x**a1))/a} d = f[c] e = f[d] c, d, e = d, e, f[e] until [d,e].include?(c) [d,e].min end puts "First 2,001 digits of the square root of two:" puts root(2, 2*100**2000)
Generate a Ruby translation of this Java snippet without changing its computational steps.
public class ScriptedMain { public static int meaningOfLife() { return 42; } public static void main(String[] args) { System.out.println("Main: The meaning of life is " + meaningOfLife()); } }
def meaning_of_life 42 end if __FILE__ == $0 puts "Main: The meaning of life is end
Rewrite the snippet below in Ruby so it works the same as the original Java code.
public class ScriptedMain { public static int meaningOfLife() { return 42; } public static void main(String[] args) { System.out.println("Main: The meaning of life is " + meaningOfLife()); } }
def meaning_of_life 42 end if __FILE__ == $0 puts "Main: The meaning of life is end
Rewrite the snippet below in Ruby so it works the same as the original Java code.
public class NicePrimes { private static boolean isPrime(long n) { if (n < 2) { return false; } if (n % 2 == 0L) { return n == 2L; } if (n % 3 == 0L) { return n == 3L; } var p = 5L; while (p * p <= n) { if (n % p == 0L) { return false; } p += 2; if (n % p == 0L) { return false; } p += 4; } return true; } private static long digitalRoot(long n) { if (n == 0) { return 0; } return 1 + (n - 1) % 9; } public static void main(String[] args) { final long from = 500; final long to = 1000; int count = 0; System.out.printf("Nice primes between %d and %d%n", from, to); long n = from; while (n < to) { if (isPrime(digitalRoot(n)) && isPrime(n)) { count++; System.out.print(n); if (count % 10 == 0) { System.out.println(); } else { System.out.print(' '); } } n++; } System.out.println(); System.out.printf("%d nice primes found.%n", count); } }
require 'prime' class Integer def dig_root = (1+(self-1).remainder(9)) def nice? = prime? && dig_root.prime? end p (500..1000).select(&:nice?)
Convert this Java snippet to Ruby and keep its semantics consistent.
import java.util.Scanner; public class LastSunday { static final String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"}; public static int[] findLastSunday(int year) { boolean isLeap = isLeapYear(year); int[] days={31,isLeap?29:28,31,30,31,30,31,31,30,31,30,31}; int[] lastDay=new int[12]; for(int m=0;i<12;i++) { int d; for(d=days[m]; getWeekDay(year,m,d)!=0; d--) ; lastDay[m]=d; } return lastDay; } private static boolean isLeapYear(int year) { if(year%4==0) { if(year%100!=0) return true; else if (year%400==0) return true; } return false; } private static int getWeekDay(int y, int m, int d) { int f=y+d+3*m-1; m++; if(m<3) y--; else f-=(int)(0.4*m+2.3); f+=(int)(y/4)-(int)((y/100+1)*0.75); f%=7; return f; } private static void display(int year, int[] lastDay) { System.out.println("\nYEAR: "+year); for(int m=0;i<12;i++) System.out.println(months[m]+": "+lastDay[m]); } public static void main(String[] args) throws Exception { System.out.print("Enter year: "); Scanner s=new Scanner(System.in); int y=Integer.parseInt(s.next()); int[] lastDay = findLastSunday(y); display(y, lastDay); s.close(); } }
require 'date' def last_sundays_of_year(year = Date.today.year) (1..12).map do |month| d = Date.new(year, month, -1) d - d.wday end end puts last_sundays_of_year(2013)
Write the same algorithm in Ruby as shown in this Java implementation.
import java.util.Scanner; public class LastSunday { static final String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"}; public static int[] findLastSunday(int year) { boolean isLeap = isLeapYear(year); int[] days={31,isLeap?29:28,31,30,31,30,31,31,30,31,30,31}; int[] lastDay=new int[12]; for(int m=0;i<12;i++) { int d; for(d=days[m]; getWeekDay(year,m,d)!=0; d--) ; lastDay[m]=d; } return lastDay; } private static boolean isLeapYear(int year) { if(year%4==0) { if(year%100!=0) return true; else if (year%400==0) return true; } return false; } private static int getWeekDay(int y, int m, int d) { int f=y+d+3*m-1; m++; if(m<3) y--; else f-=(int)(0.4*m+2.3); f+=(int)(y/4)-(int)((y/100+1)*0.75); f%=7; return f; } private static void display(int year, int[] lastDay) { System.out.println("\nYEAR: "+year); for(int m=0;i<12;i++) System.out.println(months[m]+": "+lastDay[m]); } public static void main(String[] args) throws Exception { System.out.print("Enter year: "); Scanner s=new Scanner(System.in); int y=Integer.parseInt(s.next()); int[] lastDay = findLastSunday(y); display(y, lastDay); s.close(); } }
require 'date' def last_sundays_of_year(year = Date.today.year) (1..12).map do |month| d = Date.new(year, month, -1) d - d.wday end end puts last_sundays_of_year(2013)
Write the same algorithm in Ruby as shown in this Java implementation.
import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects; public class RandomLatinSquares { private static void printSquare(List<List<Integer>> latin) { for (List<Integer> row : latin) { Iterator<Integer> it = row.iterator(); System.out.print("["); if (it.hasNext()) { Integer col = it.next(); System.out.print(col); } while (it.hasNext()) { Integer col = it.next(); System.out.print(", "); System.out.print(col); } System.out.println("]"); } System.out.println(); } private static void latinSquare(int n) { if (n <= 0) { System.out.println("[]"); return; } List<List<Integer>> latin = new ArrayList<>(n); for (int i = 0; i < n; ++i) { List<Integer> inner = new ArrayList<>(n); for (int j = 0; j < n; ++j) { inner.add(j); } latin.add(inner); } Collections.shuffle(latin.get(0)); for (int i = 1; i < n - 1; ++i) { boolean shuffled = false; shuffling: while (!shuffled) { Collections.shuffle(latin.get(i)); for (int k = 0; k < i; ++k) { for (int j = 0; j < n; ++j) { if (Objects.equals(latin.get(k).get(j), latin.get(i).get(j))) { continue shuffling; } } } shuffled = true; } } for (int j = 0; j < n; ++j) { List<Boolean> used = new ArrayList<>(n); for (int i = 0; i < n; ++i) { used.add(false); } for (int i = 0; i < n - 1; ++i) { used.set(latin.get(i).get(j), true); } for (int k = 0; k < n; ++k) { if (!used.get(k)) { latin.get(n - 1).set(j, k); break; } } } printSquare(latin); } public static void main(String[] args) { latinSquare(5); latinSquare(5); latinSquare(10); } }
N = 5 def generate_square perms = (1..N).to_a.permutation(N).to_a.shuffle square = [] N.times do square << perms.pop perms.reject!{|perm| perm.zip(square.last).any?{|el1, el2| el1 == el2} } end square end def print_square(square) cell_size = N.digits.size + 1 strings = square.map!{|row| row.map!{|el| el.to_s.rjust(cell_size)}.join } puts strings, "\n" end 2.times{print_square( generate_square)}
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version.
import java.io.*; import java.util.*; public class Teacup { public static void main(String[] args) { if (args.length != 1) { System.err.println("usage: java Teacup dictionary"); System.exit(1); } try { findTeacupWords(loadDictionary(args[0])); } catch (Exception ex) { System.err.println(ex.getMessage()); } } private static Set<String> loadDictionary(String fileName) throws IOException { Set<String> words = new TreeSet<>(); try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { String word; while ((word = reader.readLine()) != null) words.add(word); return words; } } private static void findTeacupWords(Set<String> words) { List<String> teacupWords = new ArrayList<>(); Set<String> found = new HashSet<>(); for (String word : words) { int len = word.length(); if (len < 3 || found.contains(word)) continue; teacupWords.clear(); teacupWords.add(word); char[] chars = word.toCharArray(); for (int i = 0; i < len - 1; ++i) { String rotated = new String(rotate(chars)); if (rotated.equals(word) || !words.contains(rotated)) break; teacupWords.add(rotated); } if (teacupWords.size() == len) { found.addAll(teacupWords); System.out.print(word); for (int i = 1; i < len; ++i) System.out.print(" " + teacupWords.get(i)); System.out.println(); } } } private static char[] rotate(char[] ch) { char c = ch[0]; System.arraycopy(ch, 1, ch, 0, ch.length - 1); ch[ch.length - 1] = c; return ch; } }
lists = ["unixdict.txt", "wordlist.10000", "woordenlijst.txt"] lists.each do |list| words = open(list).readlines( chomp: true).reject{|w| w.size < 3 } grouped_by_size = words.group_by(&:size) tea_words = words.filter_map do |word| chars = word.chars next unless chars.none?{|c| c < chars.first } next if chars.uniq.size == 1 rotations = word.size.times.map {|i| chars.rotate(i).join } rotations if rotations.all?{|rot| grouped_by_size[rot.size].include? rot } end puts "", list + ":" tea_words.uniq(&:to_set).each{|ar| puts ar.join(", ") } end
Ensure the translated Ruby code behaves exactly like the original Java snippet.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FairshareBetweenTwoAndMore { public static void main(String[] args) { for ( int base : Arrays.asList(2, 3, 5, 11) ) { System.out.printf("Base %d = %s%n", base, thueMorseSequence(25, base)); } } private static List<Integer> thueMorseSequence(int terms, int base) { List<Integer> sequence = new ArrayList<Integer>(); for ( int i = 0 ; i < terms ; i++ ) { int sum = 0; int n = i; while ( n > 0 ) { sum += n % base; n /= base; } sequence.add(sum % base); } return sequence; } }
def turn(base, n) sum = 0 while n != 0 do rem = n % base n = n / base sum = sum + rem end return sum % base end def fairshare(base, count) print "Base %2d: " % [base] for i in 0 .. count - 1 do t = turn(base, i) print " %2d" % [t] end print "\n" end def turnCount(base, count) cnt = Array.new(base, 0) for i in 0 .. count - 1 do t = turn(base, i) cnt[t] = cnt[t] + 1 end minTurn = base * count maxTurn = -1 portion = 0 for i in 0 .. base - 1 do if cnt[i] > 0 then portion = portion + 1 end if cnt[i] < minTurn then minTurn = cnt[i] end if cnt[i] > maxTurn then maxTurn = cnt[i] end end print " With %d people: " % [base] if 0 == minTurn then print "Only %d have a turn\n" % portion elsif minTurn == maxTurn then print "%d\n" % [minTurn] else print "%d or %d\n" % [minTurn, maxTurn] end end def main fairshare(2, 25) fairshare(3, 25) fairshare(5, 25) fairshare(11, 25) puts "How many times does each get a turn in 50000 iterations?" turnCount(191, 50000) turnCount(1377, 50000) turnCount(49999, 50000) turnCount(50000, 50000) turnCount(50001, 50000) end main()
Convert the following code from Java to Ruby, ensuring the logic remains intact.
import java.util.ArrayList; import java.util.stream.IntStream; import java.util.stream.LongStream; public class EstheticNumbers { interface RecTriConsumer<A, B, C> { void accept(RecTriConsumer<A, B, C> f, A a, B b, C c); } private static boolean isEsthetic(long n, long b) { if (n == 0) { return false; } var i = n % b; var n2 = n / b; while (n2 > 0) { var j = n2 % b; if (Math.abs(i - j) != 1) { return false; } n2 /= b; i = j; } return true; } private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) { var esths = new ArrayList<Long>(); var dfs = new RecTriConsumer<Long, Long, Long>() { public void accept(Long n, Long m, Long i) { accept(this, n, m, i); } @Override public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) { if (n <= i && i <= m) { esths.add(i); } if (i == 0 || i > m) { return; } var d = i % 10; var i1 = i * 10 + d - 1; var i2 = i1 + 2; if (d == 0) { f.accept(f, n, m, i2); } else if (d == 9) { f.accept(f, n, m, i1); } else { f.accept(f, n, m, i1); f.accept(f, n, m, i2); } } }; LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i)); var le = esths.size(); System.out.printf("Base 10: %d esthetic numbers between %d and %d:%n", le, n, m); if (all) { for (int i = 0; i < esths.size(); i++) { System.out.printf("%d ", esths.get(i)); if ((i + 1) % perLine == 0) { System.out.println(); } } } else { for (int i = 0; i < perLine; i++) { System.out.printf("%d ", esths.get(i)); } System.out.println(); System.out.println("............"); for (int i = le - perLine; i < le; i++) { System.out.printf("%d ", esths.get(i)); } } System.out.println(); System.out.println(); } public static void main(String[] args) { IntStream.rangeClosed(2, 16).forEach(b -> { System.out.printf("Base %d: %dth to %dth esthetic numbers:%n", b, 4 * b, 6 * b); var n = 1L; var c = 0L; while (c < 6 * b) { if (isEsthetic(n, b)) { c++; if (c >= 4 * b) { System.out.printf("%s ", Long.toString(n, b)); } } n++; } System.out.println(); }); System.out.println(); listEsths(1000, 1010, 9999, 9898, 16, true); listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true); listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false); listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false); listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false); } }
def isEsthetic(n, b) if n == 0 then return false end i = n % b n2 = (n / b).floor while n2 > 0 j = n2 % b if (i - j).abs != 1 then return false end n2 = n2 / b i = j end return true end def listEsths(n, n2, m, m2, perLine, all) esths = Array.new dfs = lambda {|n, m, i| if n <= i and i <= m then esths << i end if i == 0 or i > m then return end d = i % 10 i1 = i * 10 + d - 1 i2 = i1 + 2 if d == 0 then dfs[n, m, i2] elsif d == 9 then dfs[n, m, i1] else dfs[n, m, i1] dfs[n, m, i2] end } for i in 0..9 dfs[n2, m2, i] end le = esths.length print "Base 10: %d esthetic numbers between %d and %d:\n" % [le, n, m] if all then esths.each_with_index { |esth, idx| print "%d " % [esth] if (idx + 1) % perLine == 0 then print "\n" end } print "\n" else for i in 0 .. perLine - 1 print "%d " % [esths[i]] end print "\n............\n" for i in le - perLine .. le - 1 print "%d " % [esths[i]] end print "\n" end print "\n" end def main for b in 2..16 print "Base %d: %dth to %dth esthetic numbers:\n" % [b, 4 * b, 6 * b] n = 1 c = 0 while c < 6 * b if isEsthetic(n, b) then c = c + 1 if c >= 4 * b then print "%s " % [n.to_s(b)] end end n = n + 1 end print "\n" end print "\n" listEsths(1000, 1010, 9999, 9898, 16, true) listEsths(1e8, 101010101, 13 * 1e7, 123456789, 9, true) listEsths(1e11, 101010101010, 13 * 1e10, 123456789898, 7, false) listEsths(1e14, 101010101010101, 13 * 1e13, 123456789898989, 5, false) listEsths(1e17, 101010101010101010, 13 * 1e16, 123456789898989898, 4, false) end main()
Translate the given Java code snippet into Ruby without altering its behavior.
package org.rosettacode.java; import java.util.Arrays; import java.util.stream.IntStream; public class HeapsAlgorithm { public static void main(String[] args) { Object[] array = IntStream.range(0, 4) .boxed() .toArray(); HeapsAlgorithm algorithm = new HeapsAlgorithm(); algorithm.recursive(array); System.out.println(); algorithm.loop(array); } void recursive(Object[] array) { recursive(array, array.length, true); } void recursive(Object[] array, int n, boolean plus) { if (n == 1) { output(array, plus); } else { for (int i = 0; i < n; i++) { recursive(array, n - 1, i == 0); swap(array, n % 2 == 0 ? i : 0, n - 1); } } } void output(Object[] array, boolean plus) { System.out.println(Arrays.toString(array) + (plus ? " +1" : " -1")); } void swap(Object[] array, int a, int b) { Object o = array[a]; array[a] = array[b]; array[b] = o; } void loop(Object[] array) { loop(array, array.length); } void loop(Object[] array, int n) { int[] c = new int[n]; output(array, true); boolean plus = false; for (int i = 0; i < n; ) { if (c[i] < i) { if (i % 2 == 0) { swap(array, 0, i); } else { swap(array, c[i], i); } output(array, plus); plus = !plus; c[i]++; i = 0; } else { c[i] = 0; i++; } } } }
def perms(n) p = Array.new(n+1){|i| -i} s = 1 loop do yield p[1..-1].map(&:abs), s k = 0 for i in 2..n k = i if p[i] < 0 and p[i].abs > p[i-1].abs and p[i].abs > p[k].abs end for i in 1...n k = i if p[i] > 0 and p[i].abs > p[i+1].abs and p[i].abs > p[k].abs end break if k.zero? for i in 1..n p[i] *= -1 if p[i].abs > p[k].abs end i = k + (p[k] <=> 0) p[k], p[i] = p[i], p[k] s = -s end end for i in 3..4 perms(i){|perm, sign| puts "Perm: puts end
Maintain the same structure and functionality when rewriting this code in Ruby.
import java.util.List; import java.util.Random; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; public class Rpg { private static final Random random = new Random(); public static int genAttribute() { return random.ints(1, 6 + 1) .limit(4) .sorted() .limit(3) .sum(); } public static void main(String[] args) { while (true) { List<Integer> stats = Stream.generate(Rpg::genAttribute) .limit(6) .collect(toList()); int sum = stats.stream().mapToInt(Integer::intValue).sum(); long count = stats.stream().filter(v -> v >= 15).count(); if (count >= 2 && sum >= 75) { System.out.printf("The 6 random numbers generated are: %s\n", stats); System.out.printf("Their sum is %s and %s of them are >= 15\n", sum, count); return; } } } }
def roll_stat dices = Array(Int32).new(4) { rand(1..6) } dices.sum - dices.min end def roll_character loop do stats = Array(Int32).new(6) { roll_stat } return stats if stats.sum >= 75 && stats.count(&.>=(15)) >= 2 end end 10.times do stats = roll_character puts "stats: end
Change the programming language of this snippet from Java to Ruby without modifying what it does.
import java.util.Arrays; public class Kolakoski { private static class Crutch { final int len; int[] s; int i; Crutch(int len) { this.len = len; s = new int[len]; i = 0; } void repeat(int count) { for (int j = 0; j < count; j++) { if (++i == len) return; s[i] = s[i - 1]; } } } private static int nextInCycle(final int[] self, int index) { return self[index % self.length]; } private static int[] kolakoski(final int[] self, int len) { Crutch c = new Crutch(len); int k = 0; while (c.i < len) { c.s[c.i] = nextInCycle(self, k); if (c.s[k] > 1) { c.repeat(c.s[k] - 1); } if (++c.i == len) return c.s; k++; } return c.s; } private static boolean possibleKolakoski(final int[] self) { int[] rle = new int[self.length]; int prev = self[0]; int count = 1; int pos = 0; for (int i = 1; i < self.length; i++) { if (self[i] == prev) { count++; } else { rle[pos++] = count; count = 1; prev = self[i]; } } for (int i = 0; i < pos; i++) { if (rle[i] != self[i]) { return false; } } return true; } public static void main(String[] args) { int[][] ias = new int[][]{ new int[]{1, 2}, new int[]{2, 1}, new int[]{1, 3, 1, 2}, new int[]{1, 3, 2, 1} }; int[] lens = new int[]{20, 20, 30, 30}; for (int i=0; i<ias.length; i++) { int len = lens[i]; int[] kol = kolakoski(ias[i], len); System.out.printf("First %d members of the sequence generated by %s: \n", len, Arrays.toString(ias[i])); System.out.printf("%s\n", Arrays.toString(kol)); System.out.printf("Possible Kolakoski sequence? %s\n\n", possibleKolakoski(kol)); } } }
def create_generator(ar) Enumerator.new do |y| cycle = ar.cycle s = [] loop do t = cycle.next s.push(t) v = s.shift y << v (v-1).times{s.push(t)} end end end def rle(ar) ar.slice_when{|a,b| a != b}.map(&:size) end [[20, [1,2]], [20, [2,1]], [30, [1,3,1,2]], [30, [1,3,2,1]]].each do |num,ar| puts "\nFirst p res = create_generator(ar).take(num) puts "Possible Kolakoski sequence? end
Write a version of this Java function in Ruby with identical behavior.
import java.util.Arrays; public class OEIS_A005179 { static int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (n % i == 0) { if (i == n / i) count++; else count += 2; } } return count; } public static void main(String[] args) { final int max = 15; int[] seq = new int[max]; System.out.printf("The first %d terms of the sequence are:\n", max); for (int i = 1, n = 0; n < max; ++i) { int k = count_divisors(i); if (k <= max && seq[k - 1] == 0) { seq[k- 1] = i; n++; } } System.out.println(Arrays.toString(seq)); } }
require 'prime' def num_divisors(n) n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) } end def first_with_num_divs(n) (1..).detect{|i| num_divisors(i) == n } end p (1..15).map{|n| first_with_num_divs(n) }
Port the provided Java code into Ruby while preserving the original functionality.
public class Sparkline { String bars="▁▂▃▄▅▆▇█"; public static void main(String[] args) { Sparkline now=new Sparkline(); float[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1}; now.display1D(arr); System.out.println(now.getSparkline(arr)); float[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f}; now.display1D(arr1); System.out.println(now.getSparkline(arr1)); } public void display1D(float[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } public String getSparkline(float[] arr) { float min=Integer.MAX_VALUE; float max=Integer.MIN_VALUE; for(int i=0;i<arr.length;i++) { if(arr[i]<min) min=arr[i]; if(arr[i]>max) max=arr[i]; } float range=max-min; int num=bars.length()-1; String line=""; for(int i=0;i<arr.length;i++) { line+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num))); } return line; } }
bar = ('▁'..'█').to_a loop {print 'Numbers please separated by space/commas: ' numbers = gets.split(/[\s,]+/).map(&:to_f) min, max = numbers.minmax puts "min: %5f; max: %5f"% [min, max] div = (max - min) / (bar.size - 1) puts min == max ? bar.last*numbers.size : numbers.map{|num| bar[((num - min) / div).to_i]}.join }
Write the same algorithm in Ruby as shown in this Java implementation.
public class LevenshteinAlignment { public static String[] alignment(String a, String b) { a = a.toLowerCase(); b = b.toLowerCase(); int[][] costs = new int[a.length()+1][b.length()+1]; for (int j = 0; j <= b.length(); j++) costs[0][j] = j; for (int i = 1; i <= a.length(); i++) { costs[i][0] = i; for (int j = 1; j <= b.length(); j++) { costs[i][j] = Math.min(1 + Math.min(costs[i-1][j], costs[i][j-1]), a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1); } } StringBuilder aPathRev = new StringBuilder(); StringBuilder bPathRev = new StringBuilder(); for (int i = a.length(), j = b.length(); i != 0 && j != 0; ) { if (costs[i][j] == (a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1)) { aPathRev.append(a.charAt(--i)); bPathRev.append(b.charAt(--j)); } else if (costs[i][j] == 1 + costs[i-1][j]) { aPathRev.append(a.charAt(--i)); bPathRev.append('-'); } else if (costs[i][j] == 1 + costs[i][j-1]) { aPathRev.append('-'); bPathRev.append(b.charAt(--j)); } } return new String[]{aPathRev.reverse().toString(), bPathRev.reverse().toString()}; } public static void main(String[] args) { String[] result = alignment("rosettacode", "raisethysword"); System.out.println(result[0]); System.out.println(result[1]); } }
require 'lcs' def levenshtein_align(a, b) apos, bpos = LCS.new(a, b).backtrack2 c = "" d = "" x0 = y0 = -1 dx = dy = 0 apos.zip(bpos) do |x,y| diff = x + dx - y - dy if diff < 0 dx -= diff c += "-" * (-diff) elsif diff > 0 dy += diff d += "-" * diff end c += a[x0+1..x] x0 = x d += b[y0+1..y] y0 = y end c += a[x0+1..-1] d += b[y0+1..-1] diff = a.length + y0 - b.length - x0 if diff < 0 c += "-" * (-diff) elsif diff > 0 d += "-" * diff end [c, d] end puts levenshtein_align("rosettacode", "raisethysword")
Change the following Java code into Ruby without altering its purpose.
import java.util.*; public class LIS { public static <E extends Comparable<? super E>> List<E> lis(List<E> n) { List<Node<E>> pileTops = new ArrayList<Node<E>>(); for (E x : n) { Node<E> node = new Node<E>(); node.value = x; int i = Collections.binarySearch(pileTops, node); if (i < 0) i = ~i; if (i != 0) node.pointer = pileTops.get(i-1); if (i != pileTops.size()) pileTops.set(i, node); else pileTops.add(node); } List<E> result = new ArrayList<E>(); for (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1); node != null; node = node.pointer) result.add(node.value); Collections.reverse(result); return result; } private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> { public E value; public Node<E> pointer; public int compareTo(Node<E> y) { return value.compareTo(y.value); } } public static void main(String[] args) { List<Integer> d = Arrays.asList(3,2,6,4,5,1); System.out.printf("an L.I.S. of %s is %s\n", d, lis(d)); d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15); System.out.printf("an L.I.S. of %s is %s\n", d, lis(d)); } }
Node = Struct.new(:val, :back) def lis(n) pileTops = [] for x in n low, high = 0, pileTops.size-1 while low <= high mid = low + (high - low) / 2 if pileTops[mid].val >= x high = mid - 1 else low = mid + 1 end end i = low node = Node.new(x) node.back = pileTops[i-1] if i > 0 pileTops[i] = node end result = [] node = pileTops.last while node result.unshift(node.val) node = node.back end result end p lis([3, 2, 6, 4, 5, 1]) p lis([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15])
Change the programming language of this snippet from Java to Ruby without modifying what it does.
import java.io.*; import java.util.*; public class NeighbourWords { public static void main(String[] args) { try { int minLength = 9; List<String> words = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) { String line; while ((line = reader.readLine()) != null) { if (line.length() >= minLength) words.add(line); } } Collections.sort(words); String previousWord = null; int count = 0; for (int i = 0, n = words.size(); i + minLength <= n; ++i) { StringBuilder sb = new StringBuilder(minLength); for (int j = 0; j < minLength; ++j) sb.append(words.get(i + j).charAt(j)); String word = sb.toString(); if (word.equals(previousWord)) continue; if (Collections.binarySearch(words, word) >= 0) System.out.printf("%2d. %s\n", ++count, word); previousWord = word; } } catch (Exception e) { e.printStackTrace(); } } }
new_word_size = 9 well_sized = File.readlines("unixdict.txt", chomp: true).reject{|word| word.size < new_word_size} list = well_sized.each_cons(new_word_size).filter_map do |slice| candidate = (0...new_word_size).inject(""){|res, idx| res << slice[idx][idx] } candidate if well_sized.include?(candidate) end puts list.uniq
Produce a functionally identical Ruby code for the snippet given in Java.
public static void main(String... args){ HashMap<String, Integer> vars = new HashMap<String, Integer>(); vars.put("Variable name", 3); vars.put("Next variable name", 5); Scanner sc = new Scanner(System.in); String str = sc.next(); vars.put(str, sc.nextInt()); System.out.println(vars.get("Variable name")); System.out.println(vars.get(str)); }
p "Enter a variable name" x = "@" + gets.chomp! instance_variable_set x, 42 p "The value of
Change the programming language of this snippet from Java to Ruby without modifying what it does.
import java.util.*; public class BrilliantNumbers { public static void main(String[] args) { var primesByDigits = getPrimesByDigits(100000000); System.out.println("First 100 brilliant numbers:"); List<Integer> brilliantNumbers = new ArrayList<>(); for (var primes : primesByDigits) { int n = primes.size(); for (int i = 0; i < n; ++i) { int prime1 = primes.get(i); for (int j = i; j < n; ++j) { int prime2 = primes.get(j); brilliantNumbers.add(prime1 * prime2); } } if (brilliantNumbers.size() >= 100) break; } Collections.sort(brilliantNumbers); for (int i = 0; i < 100; ++i) { char c = (i + 1) % 10 == 0 ? '\n' : ' '; System.out.printf("%,5d%c", brilliantNumbers.get(i), c); } System.out.println(); long power = 10; long count = 0; for (int p = 1; p < 2 * primesByDigits.size(); ++p) { var primes = primesByDigits.get(p / 2); long position = count + 1; long minProduct = 0; int n = primes.size(); for (int i = 0; i < n; ++i) { long prime1 = primes.get(i); var primes2 = primes.subList(i, n); int q = (int)((power + prime1 - 1) / prime1); int j = Collections.binarySearch(primes2, q); if (j == n) continue; if (j < 0) j = -(j + 1); long prime2 = primes2.get(j); long product = prime1 * prime2; if (minProduct == 0 || product < minProduct) minProduct = product; position += j; if (prime1 >= prime2) break; } System.out.printf("First brilliant number >= 10^%d is %,d at position %,d\n", p, minProduct, position); power *= 10; if (p % 2 == 1) { long size = primes.size(); count += size * (size + 1) / 2; } } } private static List<List<Integer>> getPrimesByDigits(int limit) { PrimeGenerator primeGen = new PrimeGenerator(100000, 100000); List<List<Integer>> primesByDigits = new ArrayList<>(); List<Integer> primes = new ArrayList<>(); for (int p = 10; p <= limit; ) { int prime = primeGen.nextPrime(); if (prime > p) { primesByDigits.add(primes); primes = new ArrayList<>(); p *= 10; } primes.add(prime); } return primesByDigits; } }
func is_briliant_number(n) { n.is_semiprime && (n.factor.map{.len}.uniq.len == 1) } func brilliant_numbers_count(n) { var count = 0 var len = n.isqrt.len for k in (1 .. len-1) { var pi = prime_count(10**(k-1), 10**k - 1) count += binomial(pi, 2)+pi } var min = (10**(len - 1)) var max = (10**len - 1) each_prime(min, max, {|p| count += prime_count(p, max `min` idiv(n, p)) }) return count } say "First 100 brilliant numbers:" 100.by(is_briliant_number).each_slice(10, {|*a| say a.map { '%4s' % _}.join(' ') }) say '' for n in (1 .. 12) { var v = (10**n .. Inf -> first_by(is_briliant_number)) printf("First brilliant number >= 10^%d is %s", n, v) printf(" at position %s\n", brilliant_numbers_count(v)) }
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically?
import java.util.*; public class BrilliantNumbers { public static void main(String[] args) { var primesByDigits = getPrimesByDigits(100000000); System.out.println("First 100 brilliant numbers:"); List<Integer> brilliantNumbers = new ArrayList<>(); for (var primes : primesByDigits) { int n = primes.size(); for (int i = 0; i < n; ++i) { int prime1 = primes.get(i); for (int j = i; j < n; ++j) { int prime2 = primes.get(j); brilliantNumbers.add(prime1 * prime2); } } if (brilliantNumbers.size() >= 100) break; } Collections.sort(brilliantNumbers); for (int i = 0; i < 100; ++i) { char c = (i + 1) % 10 == 0 ? '\n' : ' '; System.out.printf("%,5d%c", brilliantNumbers.get(i), c); } System.out.println(); long power = 10; long count = 0; for (int p = 1; p < 2 * primesByDigits.size(); ++p) { var primes = primesByDigits.get(p / 2); long position = count + 1; long minProduct = 0; int n = primes.size(); for (int i = 0; i < n; ++i) { long prime1 = primes.get(i); var primes2 = primes.subList(i, n); int q = (int)((power + prime1 - 1) / prime1); int j = Collections.binarySearch(primes2, q); if (j == n) continue; if (j < 0) j = -(j + 1); long prime2 = primes2.get(j); long product = prime1 * prime2; if (minProduct == 0 || product < minProduct) minProduct = product; position += j; if (prime1 >= prime2) break; } System.out.printf("First brilliant number >= 10^%d is %,d at position %,d\n", p, minProduct, position); power *= 10; if (p % 2 == 1) { long size = primes.size(); count += size * (size + 1) / 2; } } } private static List<List<Integer>> getPrimesByDigits(int limit) { PrimeGenerator primeGen = new PrimeGenerator(100000, 100000); List<List<Integer>> primesByDigits = new ArrayList<>(); List<Integer> primes = new ArrayList<>(); for (int p = 10; p <= limit; ) { int prime = primeGen.nextPrime(); if (prime > p) { primesByDigits.add(primes); primes = new ArrayList<>(); p *= 10; } primes.add(prime); } return primesByDigits; } }
func is_briliant_number(n) { n.is_semiprime && (n.factor.map{.len}.uniq.len == 1) } func brilliant_numbers_count(n) { var count = 0 var len = n.isqrt.len for k in (1 .. len-1) { var pi = prime_count(10**(k-1), 10**k - 1) count += binomial(pi, 2)+pi } var min = (10**(len - 1)) var max = (10**len - 1) each_prime(min, max, {|p| count += prime_count(p, max `min` idiv(n, p)) }) return count } say "First 100 brilliant numbers:" 100.by(is_briliant_number).each_slice(10, {|*a| say a.map { '%4s' % _}.join(' ') }) say '' for n in (1 .. 12) { var v = (10**n .. Inf -> first_by(is_briliant_number)) printf("First brilliant number >= 10^%d is %s", n, v) printf(" at position %s\n", brilliant_numbers_count(v)) }
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version.
import java.util.Arrays; import java.util.BitSet; import org.apache.commons.lang3.ArrayUtils; public class OrderDisjointItems { public static void main(String[] args) { final String[][] MNs = {{"the cat sat on the mat", "mat cat"}, {"the cat sat on the mat", "cat mat"}, {"A B C A B C A B C", "C A C A"}, {"A B C A B D A B E", "E A D A"}, {"A B", "B"}, {"A B", "B A"}, {"A B B A", "B A"}, {"X X Y", "X"}}; for (String[] a : MNs) { String[] r = orderDisjointItems(a[0].split(" "), a[1].split(" ")); System.out.printf("%s | %s -> %s%n", a[0], a[1], Arrays.toString(r)); } } static String[] orderDisjointItems(String[] m, String[] n) { for (String e : n) { int idx = ArrayUtils.indexOf(m, e); if (idx != -1) m[idx] = null; } for (int i = 0, j = 0; i < m.length; i++) { if (m[i] == null) m[i] = n[j++]; } return m; } static String[] orderDisjointItems2(String[] m, String[] n) { BitSet bitSet = new BitSet(m.length); for (String e : n) { int idx = -1; do { idx = ArrayUtils.indexOf(m, e, idx + 1); } while (idx != -1 && bitSet.get(idx)); if (idx != -1) bitSet.set(idx); } for (int i = 0, j = 0; i < m.length; i++) { if (bitSet.get(i)) m[i] = n[j++]; } return m; } }
def order_disjoint(m,n) print " m, n = m.split, n.split from = 0 n.each_slice(2) do |x,y| next unless y sd = m[from..-1] if x > y && (sd.include? x) && (sd.include? y) && (sd.index(x) > sd.index(y)) new_from = m.index(x)+1 m[m.index(x)+from], m[m.index(y)+from] = m[m.index(y)+from], m[m.index(x)+from] from = new_from end end puts m.join(' ') end [ ['the cat sat on the mat', 'mat cat'], ['the cat sat on the mat', 'cat mat'], ['A B C A B C A B C' , 'C A C A'], ['A B C A B D A B E' , 'E A D A'], ['A B' , 'B' ], ['A B' , 'B A' ], ['A B B A' , 'B A' ] ].each {|m,n| order_disjoint(m,n)}
Produce a language-to-language conversion: from Java to Ruby, same semantics.
import java.util.Arrays; import java.util.Comparator; public class RJSortStability { public static void main(String[] args) { String[] cityList = { "UK London", "US New York", "US Birmingham", "UK Birmingham", }; String[] cn = cityList.clone(); System.out.println("\nBefore sort:"); for (String city : cn) { System.out.println(city); } Arrays.sort(cn, new Comparator<String>() { public int compare(String lft, String rgt) { return lft.substring(4).compareTo(rgt.substring(4)); } }); System.out.println("\nAfter sort on city:"); for (String city : cn) { System.out.println(city); } cn = cityList.clone(); System.out.println("\nBefore sort:"); for (String city : cn) { System.out.println(city); } Arrays.sort(cn, new Comparator<String>() { public int compare(String lft, String rgt) { return lft.substring(0, 2).compareTo(rgt.substring(0, 2)); } }); System.out.println("\nAfter sort on country:"); for (String city : cn) { System.out.println(city); } System.out.println(); } }
ary = [["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]] p ary.sort {|a,b| a[1] <=> b[1]}
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version.
public static void main(String[] args) { System.out.println(concat("Rosetta", "Code", ":")); } public static String concat(String a, String b, String c) { return a + c + c + b; } Rosetta::Code
$ irb irb(main):001:0> def f(string1, string2, separator) irb(main):002:1> [string1, '', string2].join(separator) irb(main):003:1> end => :f irb(main):004:0> f('Rosetta', 'Code', ':') => "Rosetta::Code" irb(main):005:0> exit $
Port the following code from Java to Ruby with equivalent syntax and logic.
import java.io.File; import java.lang.reflect.Method; import java.net.URI; import java.util.Arrays; import javax.tools.JavaCompiler; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; public class Eval { private static final String CLASS_NAME = "TempPleaseDeleteMe"; private static class StringCompiler extends SimpleJavaFileObject { final String m_sourceCode; private StringCompiler( final String sourceCode ) { super( URI.create( "string: m_sourceCode = sourceCode; } @Override public CharSequence getCharContent( final boolean ignoreEncodingErrors ) { return m_sourceCode; } private boolean compile() { final JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); return javac.getTask( null, javac.getStandardFileManager( null, null, null ), null, null, null, Arrays.asList( this ) ).call(); } private double callEval( final double x ) throws Exception { final Class<?> clarse = Class.forName( CLASS_NAME ); final Method eval = clarse.getMethod( "eval", double.class ); return ( Double ) eval.invoke( null, x ); } } public static double evalWithX( final String code, final double x ) throws Exception { final StringCompiler sc = new StringCompiler( "class " + CLASS_NAME + "{public static double eval(double x){return (" + code + ");}}" ); if ( ! sc.compile() ) throw new RuntimeException( "Compiler error" ); return sc.callEval( x ); } public static void main( final String [] args ) throws Exception { final String expression = args [ 0 ]; final double x1 = Double.parseDouble( args [ 1 ] ); final double x2 = Double.parseDouble( args [ 2 ] ); System.out.println( evalWithX( expression, x1 ) - evalWithX( expression, x2 ) ); } }
def bind_x_to_value(x) binding end def eval_with_x(code, a, b) eval(code, bind_x_to_value(b)) - eval(code, bind_x_to_value(a)) end puts eval_with_x('2 ** x', 3, 5)