Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Generate a Ruby translation of this Java snippet without changing its computational steps. | public class Pancake {
private static int pancake(int n) {
int gap = 2;
int sum = 2;
int adj = -1;
while (sum < n) {
adj++;
gap = 2 * gap - 1;
sum += gap;
}
return n + adj;
}
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
for (int j = 1; j < 6; j++) {
int n = 5 * i + j;
System.out.printf("p(%2d) = %2d ", n, pancake(n));
}
System.out.println();
}
}
}
| def pancake(n)
gap = 2
sum = 2
adj = -1
while sum < n
adj = adj + 1
gap = gap * 2 - 1
sum = sum + gap
end
return n + adj
end
for i in 0 .. 3
for j in 1 .. 5
n = i * 5 + j
print "p(%2d) = %2d " % [n, pancake(n)]
end
print "\n"
end
|
Generate a Ruby translation of this Java snippet without changing its computational steps. | import java.util.ArrayList;
import java.util.List;
public class PythagoreanQuadruples {
public static void main(String[] args) {
long d = 2200;
System.out.printf("Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d));
}
private static List<Long> getPythagoreanQuadruples(long max) {
List<Long> list = new ArrayList<>();
long n = -1;
long m = -1;
while ( true ) {
long nTest = (long) Math.pow(2, n+1);
long mTest = (long) (5L * Math.pow(2, m+1));
long test = 0;
if ( nTest > mTest ) {
test = mTest;
m++;
}
else {
test = nTest;
n++;
}
if ( test < max ) {
list.add(test);
}
else {
break;
}
}
return list;
}
}
| n = 2200
l_add, l = Hash(Int32, Bool).new(false), Hash(Int32, Bool).new(false)
(1..n).each do |x|
x2 = x * x
(x..n).each { |y| l_add[x2 + y * y] = true }
end
s = 3
(1..n).each do |x|
s1 = s
s += 2
s2 = s
((x+1)..n).each do |y|
l[y] = true if l_add[s1]
s1 += s2
s2 += 2
end
end
puts (1..n).reject{ |x| l[x] }.join(" ")
|
Produce a functionally identical Ruby code for the snippet given in Java. | package org.rosettacode;
import java.util.ArrayList;
import java.util.List;
public class SumAndProductPuzzle {
private final long beginning;
private final int maxSum;
private static final int MIN_VALUE = 2;
private List<int[]> firstConditionExcludes = new ArrayList<>();
private List<int[]> secondConditionExcludes = new ArrayList<>();
public static void main(String... args){
if (args.length == 0){
new SumAndProductPuzzle(100).run();
new SumAndProductPuzzle(1684).run();
new SumAndProductPuzzle(1685).run();
} else {
for (String arg : args){
try{
new SumAndProductPuzzle(Integer.valueOf(arg)).run();
} catch (NumberFormatException e){
System.out.println("Please provide only integer arguments. " +
"Provided argument " + arg + " was not an integer. " +
"Alternatively, calling the program with no arguments " +
"will run the puzzle where maximum sum equals 100, 1684, and 1865.");
}
}
}
}
public SumAndProductPuzzle(int maxSum){
this.beginning = System.currentTimeMillis();
this.maxSum = maxSum;
System.out.println("Run with maximum sum of " + String.valueOf(maxSum) +
" started at " + String.valueOf(beginning) + ".");
}
public void run(){
for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){
for (int y = x + 1; y < maxSum - MIN_VALUE; y++){
if (isSumNoGreaterThanMax(x,y) &&
isSKnowsPCannotKnow(x,y) &&
isPKnowsNow(x,y) &&
isSKnowsNow(x,y)
){
System.out.println("Found solution x is " + String.valueOf(x) + " y is " + String.valueOf(y) +
" in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms.");
}
}
}
System.out.println("Run with maximum sum of " + String.valueOf(maxSum) +
" ended in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms.");
}
public boolean isSumNoGreaterThanMax(int x, int y){
return x + y <= maxSum;
}
public boolean isSKnowsPCannotKnow(int x, int y){
if (firstConditionExcludes.contains(new int[] {x, y})){
return false;
}
for (int[] addends : sumAddends(x, y)){
if ( !(productFactors(addends[0], addends[1]).size() > 1) ) {
firstConditionExcludes.add(new int[] {x, y});
return false;
}
}
return true;
}
public boolean isPKnowsNow(int x, int y){
if (secondConditionExcludes.contains(new int[] {x, y})){
return false;
}
int countSolutions = 0;
for (int[] factors : productFactors(x, y)){
if (isSKnowsPCannotKnow(factors[0], factors[1])){
countSolutions++;
}
}
if (countSolutions == 1){
return true;
} else {
secondConditionExcludes.add(new int[] {x, y});
return false;
}
}
public boolean isSKnowsNow(int x, int y){
int countSolutions = 0;
for (int[] addends : sumAddends(x, y)){
if (isPKnowsNow(addends[0], addends[1])){
countSolutions++;
}
}
return countSolutions == 1;
}
public List<int[]> sumAddends(int x, int y){
List<int[]> list = new ArrayList<>();
int sum = x + y;
for (int addend = MIN_VALUE; addend < sum - addend; addend++){
if (isSumNoGreaterThanMax(addend, sum - addend)){
list.add(new int[]{addend, sum - addend});
}
}
return list;
}
public List<int[]> productFactors(int x, int y){
List<int[]> list = new ArrayList<>();
int product = x * y;
for (int factor = MIN_VALUE; factor < product / factor; factor++){
if (product % factor == 0){
if (isSumNoGreaterThanMax(factor, product / factor)){
list.add(new int[]{factor, product / factor});
}
}
}
return list;
}
}
| def add(x,y) x + y end
def mul(x,y) x * y end
def sumEq(s,p) s.select{|q| add(*p) == add(*q)} end
def mulEq(s,p) s.select{|q| mul(*p) == mul(*q)} end
s1 = (a = *2...100).product(a).select{|x,y| x<y && x+y<100}
s2 = s1.select{|p| sumEq(s1,p).all?{|q| mulEq(s1,q).size != 1} }
s3 = s2.select{|p| (mulEq(s1,p) & s2).size == 1}
p s3.select{|p| (sumEq(s1,p) & s3).size == 1}
|
Produce a language-to-language conversion: from Java to Ruby, same semantics. | import static java.util.stream.IntStream.rangeClosed;
public class Test {
final static int nMax = 12;
static char[] superperm;
static int pos;
static int[] count = new int[nMax];
static int factSum(int n) {
return rangeClosed(1, n)
.map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum();
}
static boolean r(int n) {
if (n == 0)
return false;
char c = superperm[pos - n];
if (--count[n] == 0) {
count[n] = n;
if (!r(n - 1))
return false;
}
superperm[pos++] = c;
return true;
}
static void superPerm(int n) {
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
pos = n;
superperm = new char[factSum(n)];
for (int i = 0; i < n + 1; i++)
count[i] = i;
for (int i = 1; i < n + 1; i++)
superperm[i - 1] = chars.charAt(i);
while (r(n)) {
}
}
public static void main(String[] args) {
for (int n = 0; n < nMax; n++) {
superPerm(n);
System.out.printf("superPerm(%2d) len = %d", n, superperm.length);
System.out.println();
}
}
}
|
l = []
(1..6).each{|e|
a, i = [], e-2
(0..l.length-e+1).each{|g|
if not (n = l[g..g+e-2]).uniq!
a.concat(n[(a[0]? i : 0)..-1]).push(e).concat(n)
i = e-2
else
i -= 1
end
}
a.each{|n| print n}; puts "\n\n"
l = a
}
|
Produce a functionally identical Ruby code for the snippet given in Java. | import java.math.BigDecimal;
import java.util.List;
public class TestIntegerness {
private static boolean isLong(double d) {
return isLong(d, 0.0);
}
private static boolean isLong(double d, double tolerance) {
return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static boolean isBigInteger(BigDecimal bd) {
try {
bd.toBigIntegerExact();
return true;
} catch (ArithmeticException ex) {
return false;
}
}
private static class Rational {
long num;
long denom;
Rational(int num, int denom) {
this.num = num;
this.denom = denom;
}
boolean isLong() {
return num % denom == 0;
}
@Override
public String toString() {
return String.format("%s/%s", num, denom);
}
}
private static class Complex {
double real;
double imag;
Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
boolean isLong() {
return TestIntegerness.isLong(real) && imag == 0.0;
}
@Override
public String toString() {
if (imag >= 0.0) {
return String.format("%s + %si", real, imag);
}
return String.format("%s - %si", real, imag);
}
}
public static void main(String[] args) {
List<Double> da = List.of(25.000000, 24.999999, 25.000100);
for (Double d : da) {
boolean exact = isLong(d);
System.out.printf("%.6f is %s integer%n", d, exact ? "an" : "not an");
}
System.out.println();
double tolerance = 0.00001;
System.out.printf("With a tolerance of %.5f:%n", tolerance);
for (Double d : da) {
boolean fuzzy = isLong(d, tolerance);
System.out.printf("%.6f is %s integer%n", d, fuzzy ? "an" : "not an");
}
System.out.println();
List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY);
for (Double f : fa) {
boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString()));
System.out.printf("%s is %s integer%n", f, exact ? "an" : "not an");
}
System.out.println();
List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0));
for (Complex c : ca) {
boolean exact = c.isLong();
System.out.printf("%s is %s integer%n", c, exact ? "an" : "not an");
}
System.out.println();
List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2));
for (Rational r : ra) {
boolean exact = r.isLong();
System.out.printf("%s is %s integer%n", r, exact ? "an" : "not an");
}
}
}
| class Numeric
def to_i?
self == self.to_i rescue false
end
end
ar = [25.000000, 24.999999, 25.000100, -2.1e120, -5e-2,
Float::NAN, Float::INFINITY,
2r, 2.5r,
2+0i, 2+0.0i, 5-5i]
ar.each{|num| puts "
|
Convert this Java snippet to Ruby and keep its semantics consistent. | public class UlamNumbers {
public static void main(String[] args) {
long start = System.currentTimeMillis();
for (int n = 1; n <= 100000; n *= 10) {
System.out.printf("Ulam(%d) = %d\n", n, ulam(n));
}
long finish = System.currentTimeMillis();
System.out.printf("Elapsed time: %.3f seconds\n", (finish - start)/1000.0);
}
private static int ulam(int n) {
int[] ulams = new int[Math.max(n, 2)];
ulams[0] = 1;
ulams[1] = 2;
int sieveLength = 2;
int[] sieve = new int[sieveLength];
sieve[0] = sieve[1] = 1;
for (int u = 2, ulen = 2; ulen < n; ) {
sieveLength = u + ulams[ulen - 2];
sieve = extend(sieve, sieveLength);
for (int i = 0; i < ulen - 1; ++i)
++sieve[u + ulams[i] - 1];
for (int i = u; i < sieveLength; ++i) {
if (sieve[i] == 1) {
u = i + 1;
ulams[ulen++] = u;
break;
}
}
}
return ulams[n - 1];
}
private static int[] extend(int[] array, int minLength) {
if (minLength <= array.length)
return array;
int newLength = 2 * array.length;
while (newLength < minLength)
newLength *= 2;
int[] newArray = new int[newLength];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
}
| func ulam(n) {
static u = Set(1,2)
static ulams = [0, 1, 2]
return ulams[n] if (ulams.end >= n)
++n
for(var i = 3; true; ++i) {
var count = 0
ulams.each {|v|
if (u.has(i - v) && (v != i-v)) {
break if (count++ > 2)
}
}
if (count == 2) {
ulams << i
u << i
break if (ulams.len == n)
}
}
ulams.tail
}
for k in (1..3) {
say "The 10^
}
|
Write the same code in Ruby as shown below in Java. | public class TypeDetection {
private static void showType(Object a) {
if (a instanceof Integer) {
System.out.printf("'%s' is an integer\n", a);
} else if (a instanceof Double) {
System.out.printf("'%s' is a double\n", a);
} else if (a instanceof Character) {
System.out.printf("'%s' is a character\n", a);
} else {
System.out.printf("'%s' is some other type\n", a);
}
}
public static void main(String[] args) {
showType(5);
showType(7.5);
showType('d');
showType(true);
}
}
| def print_type(x)
puts "Compile-time type of
puts " Actual runtime type is
end
print_type 123
print_type 123.45
print_type rand < 0.5 ? "1" : 0
print_type rand < 1.5
print_type nil
print_type 'c'
print_type "str"
print_type [1,2]
print_type({ 2, "two" })
print_type({a: 1, b: 2})
print_type ->(x : Int32){ x+2 > 0 }
|
Write the same code in Ruby as shown below in Java. | public class SafePrimes {
public static void main(String... args) {
int SIEVE_SIZE = 10_000_000;
boolean[] isComposite = new boolean[SIEVE_SIZE];
isComposite[0] = true;
isComposite[1] = true;
for (int n = 2; n < SIEVE_SIZE; n++) {
if (isComposite[n]) {
continue;
}
for (int i = n * 2; i < SIEVE_SIZE; i += n) {
isComposite[i] = true;
}
}
int oldSafePrimeCount = 0;
int oldUnsafePrimeCount = 0;
int safePrimeCount = 0;
int unsafePrimeCount = 0;
StringBuilder safePrimes = new StringBuilder();
StringBuilder unsafePrimes = new StringBuilder();
int safePrimesStrCount = 0;
int unsafePrimesStrCount = 0;
for (int n = 2; n < SIEVE_SIZE; n++) {
if (n == 1_000_000) {
oldSafePrimeCount = safePrimeCount;
oldUnsafePrimeCount = unsafePrimeCount;
}
if (isComposite[n]) {
continue;
}
boolean isUnsafe = isComposite[(n - 1) >>> 1];
if (isUnsafe) {
if (unsafePrimeCount < 40) {
if (unsafePrimeCount > 0) {
unsafePrimes.append(", ");
}
unsafePrimes.append(n);
unsafePrimesStrCount++;
}
unsafePrimeCount++;
}
else {
if (safePrimeCount < 35) {
if (safePrimeCount > 0) {
safePrimes.append(", ");
}
safePrimes.append(n);
safePrimesStrCount++;
}
safePrimeCount++;
}
}
System.out.println("First " + safePrimesStrCount + " safe primes: " + safePrimes.toString());
System.out.println("Number of safe primes below 1,000,000: " + oldSafePrimeCount);
System.out.println("Number of safe primes below 10,000,000: " + safePrimeCount);
System.out.println("First " + unsafePrimesStrCount + " unsafe primes: " + unsafePrimes.toString());
System.out.println("Number of unsafe primes below 1,000,000: " + oldUnsafePrimeCount);
System.out.println("Number of unsafe primes below 10,000,000: " + unsafePrimeCount);
return;
}
}
| require "prime"
class Integer
def safe_prime?
((self-1)/2).prime?
end
end
def format_parts(n)
partitions = Prime.each(n).partition(&:safe_prime?).map(&:count)
"There are %d safes and %d unsafes below
end
puts "First 35 safe-primes:"
p Prime.each.lazy.select(&:safe_prime?).take(35).to_a
puts format_parts(1_000_000), "\n"
puts "First 40 unsafe-primes:"
p Prime.each.lazy.reject(&:safe_prime?).take(40).to_a
puts format_parts(10_000_000)
|
Preserve the algorithm and functionality while converting the code from Java to Ruby. | import java.util.*;
public class HashJoin {
public static void main(String[] args) {
String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"},
{"18", "Popeye"}, {"28", "Alan"}};
String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"},
{"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
{"Bob", "foo"}};
hashJoin(table1, 1, table2, 0).stream()
.forEach(r -> System.out.println(Arrays.deepToString(r)));
}
static List<String[][]> hashJoin(String[][] records1, int idx1,
String[][] records2, int idx2) {
List<String[][]> result = new ArrayList<>();
Map<String, List<String[]>> map = new HashMap<>();
for (String[] record : records1) {
List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());
v.add(record);
map.put(record[idx1], v);
}
for (String[] record : records2) {
List<String[]> lst = map.get(record[idx2]);
if (lst != null) {
lst.stream().forEach(r -> {
result.add(new String[][]{r, record});
});
}
}
return result;
}
}
| def hashJoin(table1, index1, table2, index2)
h = table1.group_by {|s| s[index1]}
h.default = []
table2.collect {|r|
h[r[index2]].collect {|s| [s, r]}
}.flatten(1)
end
table1 = [[27, "Jonah"],
[18, "Alan"],
[28, "Glory"],
[18, "Popeye"],
[28, "Alan"]]
table2 = [["Jonah", "Whales"],
["Jonah", "Spiders"],
["Alan", "Ghosts"],
["Alan", "Zombies"],
["Glory", "Buffy"]]
hashJoin(table1, 1, table2, 0).each { |row| p row }
|
Write the same algorithm in Ruby as shown in this Java implementation. | import java.util.function.Predicate;
public class PermutationsWithRepetitions {
public static void main(String[] args) {
char[] chars = {'a', 'b', 'c', 'd'};
permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);
}
static void permute(char[] a, int k, Predicate<int[]> decider) {
int n = a.length;
if (k < 1 || k > n)
throw new IllegalArgumentException("Illegal number of positions.");
int[] indexes = new int[n];
int total = (int) Math.pow(n, k);
while (total-- > 0) {
for (int i = 0; i < n - (n - k); i++)
System.out.print(a[indexes[i]]);
System.out.println();
if (decider.test(indexes))
break;
for (int i = 0; i < n; i++) {
if (indexes[i] >= n - 1) {
indexes[i] = 0;
} else {
indexes[i]++;
break;
}
}
}
}
}
| rp = [1,2,3].repeated_permutation(2)
p rp.to_a
p rp.take_while{|(a, b)| a + b < 5}
|
Convert this Java snippet to Ruby and keep its semantics consistent. | import java.util.function.Predicate;
public class PermutationsWithRepetitions {
public static void main(String[] args) {
char[] chars = {'a', 'b', 'c', 'd'};
permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);
}
static void permute(char[] a, int k, Predicate<int[]> decider) {
int n = a.length;
if (k < 1 || k > n)
throw new IllegalArgumentException("Illegal number of positions.");
int[] indexes = new int[n];
int total = (int) Math.pow(n, k);
while (total-- > 0) {
for (int i = 0; i < n - (n - k); i++)
System.out.print(a[indexes[i]]);
System.out.println();
if (decider.test(indexes))
break;
for (int i = 0; i < n; i++) {
if (indexes[i] >= n - 1) {
indexes[i] = 0;
} else {
indexes[i]++;
break;
}
}
}
}
}
| rp = [1,2,3].repeated_permutation(2)
p rp.to_a
p rp.take_while{|(a, b)| a + b < 5}
|
Convert the following code from Java to Ruby, ensuring the logic remains intact. | import com.sun.javafx.application.PlatformImpl;
import java.io.File;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class AudioAlarm {
public static void main(String[] args) throws InterruptedException {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number of seconds: ");
int seconds = Integer.parseInt(input.nextLine());
System.out.print("Enter a filename (must end with .mp3 or .wav): ");
String audio = input.nextLine();
TimeUnit.SECONDS.sleep(seconds);
Media media = new Media(new File(audio).toURI().toString());
AtomicBoolean stop = new AtomicBoolean();
Runnable onEnd = () -> stop.set(true);
PlatformImpl.startup(() -> {});
MediaPlayer player = new MediaPlayer(media);
player.setOnEndOfMedia(onEnd);
player.setOnError(onEnd);
player.setOnHalted(onEnd);
player.play();
while (!stop.get()) {
Thread.sleep(100);
}
System.exit(0);
}
}
| puts "Enter a number of seconds:"
seconds = gets.chomp.to_i
puts "Enter a MP3 file to be played"
mp3filepath = File.dirname(__FILE__) + "/" + gets.chomp + ".mp3"
sleep(seconds)
pid = fork{ exec 'mpg123','-q', mp3filepath }
|
Produce a language-to-language conversion: from Java to Ruby, same semantics. | import java.math.BigInteger;
import java.util.*;
class LeftTruncatablePrime
{
private static List<BigInteger> getNextLeftTruncatablePrimes(BigInteger n, int radix, int millerRabinCertainty)
{
List<BigInteger> probablePrimes = new ArrayList<BigInteger>();
String baseString = n.equals(BigInteger.ZERO) ? "" : n.toString(radix);
for (int i = 1; i < radix; i++)
{
BigInteger p = new BigInteger(Integer.toString(i, radix) + baseString, radix);
if (p.isProbablePrime(millerRabinCertainty))
probablePrimes.add(p);
}
return probablePrimes;
}
public static BigInteger getLargestLeftTruncatablePrime(int radix, int millerRabinCertainty)
{
List<BigInteger> lastList = null;
List<BigInteger> list = getNextLeftTruncatablePrimes(BigInteger.ZERO, radix, millerRabinCertainty);
while (!list.isEmpty())
{
lastList = list;
list = new ArrayList<BigInteger>();
for (BigInteger n : lastList)
list.addAll(getNextLeftTruncatablePrimes(n, radix, millerRabinCertainty));
}
if (lastList == null)
return null;
Collections.sort(lastList);
return lastList.get(lastList.size() - 1);
}
public static void main(String[] args)
{
if (args.length != 2) {
System.err.println("There must be exactly two command line arguments.");
return;
}
int maxRadix;
try {
maxRadix = Integer.parseInt(args[0]);
if (maxRadix < 3) throw new NumberFormatException();
} catch (NumberFormatException e) {
System.err.println("Radix must be an integer greater than 2.");
return;
}
int millerRabinCertainty;
try {
millerRabinCertainty = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
System.err.println("Miiller-Rabin Certainty must be an integer.");
return;
}
for (int radix = 3; radix <= maxRadix; radix++)
{
BigInteger largest = getLargestLeftTruncatablePrime(radix, millerRabinCertainty);
System.out.print("n=" + radix + ": ");
if (largest == null)
System.out.println("No left-truncatable prime");
else
System.out.println(largest + " (in base " + radix + "): " + largest.toString(radix));
}
}
}
|
require 'prime'
BASE = 3
MAX = 500
stems = Prime.each(BASE-1).to_a
(1..MAX-1).each {|i|
print "
t = []
b = BASE ** i
stems.each {|z|
(1..BASE-1).each {|n|
c = n*b+z
t.push(c) if c.prime?
}}
break if t.empty?
stems = t
}
puts "The largest left truncatable prime
|
Rewrite the snippet below in Ruby so it works the same as the original Java code. | import java.util.*;
public class Game24Player {
final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo",
"nnnnooo"};
final String ops = "+-*/^";
String solution;
List<Integer> digits;
public static void main(String[] args) {
new Game24Player().play();
}
void play() {
digits = getSolvableDigits();
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("Make 24 using these digits: ");
System.out.println(digits);
System.out.println("(Enter 'q' to quit, 's' for a solution)");
System.out.print("> ");
String line = in.nextLine();
if (line.equalsIgnoreCase("q")) {
System.out.println("\nThanks for playing");
return;
}
if (line.equalsIgnoreCase("s")) {
System.out.println(solution);
digits = getSolvableDigits();
continue;
}
char[] entry = line.replaceAll("[^*+-/)(\\d]", "").toCharArray();
try {
validate(entry);
if (evaluate(infixToPostfix(entry))) {
System.out.println("\nCorrect! Want to try another? ");
digits = getSolvableDigits();
} else {
System.out.println("\nNot correct.");
}
} catch (Exception e) {
System.out.printf("%n%s Try again.%n", e.getMessage());
}
}
}
void validate(char[] input) throws Exception {
int total1 = 0, parens = 0, opsCount = 0;
for (char c : input) {
if (Character.isDigit(c))
total1 += 1 << (c - '0') * 4;
else if (c == '(')
parens++;
else if (c == ')')
parens--;
else if (ops.indexOf(c) != -1)
opsCount++;
if (parens < 0)
throw new Exception("Parentheses mismatch.");
}
if (parens != 0)
throw new Exception("Parentheses mismatch.");
if (opsCount != 3)
throw new Exception("Wrong number of operators.");
int total2 = 0;
for (int d : digits)
total2 += 1 << d * 4;
if (total1 != total2)
throw new Exception("Not the same digits.");
}
boolean evaluate(char[] line) throws Exception {
Stack<Float> s = new Stack<>();
try {
for (char c : line) {
if ('0' <= c && c <= '9')
s.push((float) c - '0');
else
s.push(applyOperator(s.pop(), s.pop(), c));
}
} catch (EmptyStackException e) {
throw new Exception("Invalid entry.");
}
return (Math.abs(24 - s.peek()) < 0.001F);
}
float applyOperator(float a, float b, char c) {
switch (c) {
case '+':
return a + b;
case '-':
return b - a;
case '*':
return a * b;
case '/':
return b / a;
default:
return Float.NaN;
}
}
List<Integer> randomDigits() {
Random r = new Random();
List<Integer> result = new ArrayList<>(4);
for (int i = 0; i < 4; i++)
result.add(r.nextInt(9) + 1);
return result;
}
List<Integer> getSolvableDigits() {
List<Integer> result;
do {
result = randomDigits();
} while (!isSolvable(result));
return result;
}
boolean isSolvable(List<Integer> digits) {
Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);
permute(digits, dPerms, 0);
int total = 4 * 4 * 4;
List<List<Integer>> oPerms = new ArrayList<>(total);
permuteOperators(oPerms, 4, total);
StringBuilder sb = new StringBuilder(4 + 3);
for (String pattern : patterns) {
char[] patternChars = pattern.toCharArray();
for (List<Integer> dig : dPerms) {
for (List<Integer> opr : oPerms) {
int i = 0, j = 0;
for (char c : patternChars) {
if (c == 'n')
sb.append(dig.get(i++));
else
sb.append(ops.charAt(opr.get(j++)));
}
String candidate = sb.toString();
try {
if (evaluate(candidate.toCharArray())) {
solution = postfixToInfix(candidate);
return true;
}
} catch (Exception ignored) {
}
sb.setLength(0);
}
}
}
return false;
}
String postfixToInfix(String postfix) {
class Expression {
String op, ex;
int prec = 3;
Expression(String e) {
ex = e;
}
Expression(String e1, String e2, String o) {
ex = String.format("%s %s %s", e1, o, e2);
op = o;
prec = ops.indexOf(o) / 2;
}
}
Stack<Expression> expr = new Stack<>();
for (char c : postfix.toCharArray()) {
int idx = ops.indexOf(c);
if (idx != -1) {
Expression r = expr.pop();
Expression l = expr.pop();
int opPrec = idx / 2;
if (l.prec < opPrec)
l.ex = '(' + l.ex + ')';
if (r.prec <= opPrec)
r.ex = '(' + r.ex + ')';
expr.push(new Expression(l.ex, r.ex, "" + c));
} else {
expr.push(new Expression("" + c));
}
}
return expr.peek().ex;
}
char[] infixToPostfix(char[] infix) throws Exception {
StringBuilder sb = new StringBuilder();
Stack<Integer> s = new Stack<>();
try {
for (char c : infix) {
int idx = ops.indexOf(c);
if (idx != -1) {
if (s.isEmpty())
s.push(idx);
else {
while (!s.isEmpty()) {
int prec2 = s.peek() / 2;
int prec1 = idx / 2;
if (prec2 >= prec1)
sb.append(ops.charAt(s.pop()));
else
break;
}
s.push(idx);
}
} else if (c == '(') {
s.push(-2);
} else if (c == ')') {
while (s.peek() != -2)
sb.append(ops.charAt(s.pop()));
s.pop();
} else {
sb.append(c);
}
}
while (!s.isEmpty())
sb.append(ops.charAt(s.pop()));
} catch (EmptyStackException e) {
throw new Exception("Invalid entry.");
}
return sb.toString().toCharArray();
}
void permute(List<Integer> lst, Set<List<Integer>> res, int k) {
for (int i = k; i < lst.size(); i++) {
Collections.swap(lst, i, k);
permute(lst, res, k + 1);
Collections.swap(lst, k, i);
}
if (k == lst.size())
res.add(new ArrayList<>(lst));
}
void permuteOperators(List<List<Integer>> res, int n, int total) {
for (int i = 0, npow = n * n; i < total; i++)
res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));
}
}
| class TwentyFourGame
EXPRESSIONS = [
'((%dr %s %dr) %s %dr) %s %dr',
'(%dr %s (%dr %s %dr)) %s %dr',
'(%dr %s %dr) %s (%dr %s %dr)',
'%dr %s ((%dr %s %dr) %s %dr)',
'%dr %s (%dr %s (%dr %s %dr))',
]
OPERATORS = [:+, :-, :*, :/].repeated_permutation(3).to_a
def self.solve(digits)
solutions = []
perms = digits.permutation.to_a.uniq
perms.product(OPERATORS, EXPRESSIONS) do |(a,b,c,d), (op1,op2,op3), expr|
text = expr % [a, op1, b, op2, c, op3, d]
value = eval(text) rescue next
solutions << text.delete("r") if value == 24
end
solutions
end
end
digits = ARGV.map do |arg|
begin
Integer(arg)
rescue ArgumentError
raise "error: not an integer: '
end
end
digits.size == 4 or raise "error: need 4 digits, only have
solutions = TwentyFourGame.solve(digits)
if solutions.empty?
puts "no solutions"
else
puts "found
puts solutions.sort
end
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | import java.util.*;
public class Game24Player {
final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo",
"nnnnooo"};
final String ops = "+-*/^";
String solution;
List<Integer> digits;
public static void main(String[] args) {
new Game24Player().play();
}
void play() {
digits = getSolvableDigits();
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("Make 24 using these digits: ");
System.out.println(digits);
System.out.println("(Enter 'q' to quit, 's' for a solution)");
System.out.print("> ");
String line = in.nextLine();
if (line.equalsIgnoreCase("q")) {
System.out.println("\nThanks for playing");
return;
}
if (line.equalsIgnoreCase("s")) {
System.out.println(solution);
digits = getSolvableDigits();
continue;
}
char[] entry = line.replaceAll("[^*+-/)(\\d]", "").toCharArray();
try {
validate(entry);
if (evaluate(infixToPostfix(entry))) {
System.out.println("\nCorrect! Want to try another? ");
digits = getSolvableDigits();
} else {
System.out.println("\nNot correct.");
}
} catch (Exception e) {
System.out.printf("%n%s Try again.%n", e.getMessage());
}
}
}
void validate(char[] input) throws Exception {
int total1 = 0, parens = 0, opsCount = 0;
for (char c : input) {
if (Character.isDigit(c))
total1 += 1 << (c - '0') * 4;
else if (c == '(')
parens++;
else if (c == ')')
parens--;
else if (ops.indexOf(c) != -1)
opsCount++;
if (parens < 0)
throw new Exception("Parentheses mismatch.");
}
if (parens != 0)
throw new Exception("Parentheses mismatch.");
if (opsCount != 3)
throw new Exception("Wrong number of operators.");
int total2 = 0;
for (int d : digits)
total2 += 1 << d * 4;
if (total1 != total2)
throw new Exception("Not the same digits.");
}
boolean evaluate(char[] line) throws Exception {
Stack<Float> s = new Stack<>();
try {
for (char c : line) {
if ('0' <= c && c <= '9')
s.push((float) c - '0');
else
s.push(applyOperator(s.pop(), s.pop(), c));
}
} catch (EmptyStackException e) {
throw new Exception("Invalid entry.");
}
return (Math.abs(24 - s.peek()) < 0.001F);
}
float applyOperator(float a, float b, char c) {
switch (c) {
case '+':
return a + b;
case '-':
return b - a;
case '*':
return a * b;
case '/':
return b / a;
default:
return Float.NaN;
}
}
List<Integer> randomDigits() {
Random r = new Random();
List<Integer> result = new ArrayList<>(4);
for (int i = 0; i < 4; i++)
result.add(r.nextInt(9) + 1);
return result;
}
List<Integer> getSolvableDigits() {
List<Integer> result;
do {
result = randomDigits();
} while (!isSolvable(result));
return result;
}
boolean isSolvable(List<Integer> digits) {
Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);
permute(digits, dPerms, 0);
int total = 4 * 4 * 4;
List<List<Integer>> oPerms = new ArrayList<>(total);
permuteOperators(oPerms, 4, total);
StringBuilder sb = new StringBuilder(4 + 3);
for (String pattern : patterns) {
char[] patternChars = pattern.toCharArray();
for (List<Integer> dig : dPerms) {
for (List<Integer> opr : oPerms) {
int i = 0, j = 0;
for (char c : patternChars) {
if (c == 'n')
sb.append(dig.get(i++));
else
sb.append(ops.charAt(opr.get(j++)));
}
String candidate = sb.toString();
try {
if (evaluate(candidate.toCharArray())) {
solution = postfixToInfix(candidate);
return true;
}
} catch (Exception ignored) {
}
sb.setLength(0);
}
}
}
return false;
}
String postfixToInfix(String postfix) {
class Expression {
String op, ex;
int prec = 3;
Expression(String e) {
ex = e;
}
Expression(String e1, String e2, String o) {
ex = String.format("%s %s %s", e1, o, e2);
op = o;
prec = ops.indexOf(o) / 2;
}
}
Stack<Expression> expr = new Stack<>();
for (char c : postfix.toCharArray()) {
int idx = ops.indexOf(c);
if (idx != -1) {
Expression r = expr.pop();
Expression l = expr.pop();
int opPrec = idx / 2;
if (l.prec < opPrec)
l.ex = '(' + l.ex + ')';
if (r.prec <= opPrec)
r.ex = '(' + r.ex + ')';
expr.push(new Expression(l.ex, r.ex, "" + c));
} else {
expr.push(new Expression("" + c));
}
}
return expr.peek().ex;
}
char[] infixToPostfix(char[] infix) throws Exception {
StringBuilder sb = new StringBuilder();
Stack<Integer> s = new Stack<>();
try {
for (char c : infix) {
int idx = ops.indexOf(c);
if (idx != -1) {
if (s.isEmpty())
s.push(idx);
else {
while (!s.isEmpty()) {
int prec2 = s.peek() / 2;
int prec1 = idx / 2;
if (prec2 >= prec1)
sb.append(ops.charAt(s.pop()));
else
break;
}
s.push(idx);
}
} else if (c == '(') {
s.push(-2);
} else if (c == ')') {
while (s.peek() != -2)
sb.append(ops.charAt(s.pop()));
s.pop();
} else {
sb.append(c);
}
}
while (!s.isEmpty())
sb.append(ops.charAt(s.pop()));
} catch (EmptyStackException e) {
throw new Exception("Invalid entry.");
}
return sb.toString().toCharArray();
}
void permute(List<Integer> lst, Set<List<Integer>> res, int k) {
for (int i = k; i < lst.size(); i++) {
Collections.swap(lst, i, k);
permute(lst, res, k + 1);
Collections.swap(lst, k, i);
}
if (k == lst.size())
res.add(new ArrayList<>(lst));
}
void permuteOperators(List<List<Integer>> res, int n, int total) {
for (int i = 0, npow = n * n; i < total; i++)
res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));
}
}
| class TwentyFourGame
EXPRESSIONS = [
'((%dr %s %dr) %s %dr) %s %dr',
'(%dr %s (%dr %s %dr)) %s %dr',
'(%dr %s %dr) %s (%dr %s %dr)',
'%dr %s ((%dr %s %dr) %s %dr)',
'%dr %s (%dr %s (%dr %s %dr))',
]
OPERATORS = [:+, :-, :*, :/].repeated_permutation(3).to_a
def self.solve(digits)
solutions = []
perms = digits.permutation.to_a.uniq
perms.product(OPERATORS, EXPRESSIONS) do |(a,b,c,d), (op1,op2,op3), expr|
text = expr % [a, op1, b, op2, c, op3, d]
value = eval(text) rescue next
solutions << text.delete("r") if value == 24
end
solutions
end
end
digits = ARGV.map do |arg|
begin
Integer(arg)
rescue ArgumentError
raise "error: not an integer: '
end
end
digits.size == 4 or raise "error: need 4 digits, only have
solutions = TwentyFourGame.solve(digits)
if solutions.empty?
puts "no solutions"
else
puts "found
puts solutions.sort
end
|
Generate an equivalent Ruby version of this Java code. | import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.*;
public class HoughTransform
{
public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast)
{
int width = inputData.width;
int height = inputData.height;
int maxRadius = (int)Math.ceil(Math.hypot(width, height));
int halfRAxisSize = rAxisSize >>> 1;
ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize);
double[] sinTable = new double[thetaAxisSize];
double[] cosTable = new double[thetaAxisSize];
for (int theta = thetaAxisSize - 1; theta >= 0; theta--)
{
double thetaRadians = theta * Math.PI / thetaAxisSize;
sinTable[theta] = Math.sin(thetaRadians);
cosTable[theta] = Math.cos(thetaRadians);
}
for (int y = height - 1; y >= 0; y--)
{
for (int x = width - 1; x >= 0; x--)
{
if (inputData.contrast(x, y, minContrast))
{
for (int theta = thetaAxisSize - 1; theta >= 0; theta--)
{
double r = cosTable[theta] * x + sinTable[theta] * y;
int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize;
outputData.accumulate(theta, rScaled, 1);
}
}
}
}
return outputData;
}
public static class ArrayData
{
public final int[] dataArray;
public final int width;
public final int height;
public ArrayData(int width, int height)
{
this(new int[width * height], width, height);
}
public ArrayData(int[] dataArray, int width, int height)
{
this.dataArray = dataArray;
this.width = width;
this.height = height;
}
public int get(int x, int y)
{ return dataArray[y * width + x]; }
public void set(int x, int y, int value)
{ dataArray[y * width + x] = value; }
public void accumulate(int x, int y, int delta)
{ set(x, y, get(x, y) + delta); }
public boolean contrast(int x, int y, int minContrast)
{
int centerValue = get(x, y);
for (int i = 8; i >= 0; i--)
{
if (i == 4)
continue;
int newx = x + (i % 3) - 1;
int newy = y + (i / 3) - 1;
if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height))
continue;
if (Math.abs(get(newx, newy) - centerValue) >= minContrast)
return true;
}
return false;
}
public int getMax()
{
int max = dataArray[0];
for (int i = width * height - 1; i > 0; i--)
if (dataArray[i] > max)
max = dataArray[i];
return max;
}
}
public static ArrayData getArrayDataFromImage(String filename) throws IOException
{
BufferedImage inputImage = ImageIO.read(new File(filename));
int width = inputImage.getWidth();
int height = inputImage.getHeight();
int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);
ArrayData arrayData = new ArrayData(width, height);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int rgbValue = rgbData[y * width + x];
rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);
arrayData.set(x, height - 1 - y, rgbValue);
}
}
return arrayData;
}
public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException
{
int max = arrayData.getMax();
BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < arrayData.height; y++)
{
for (int x = 0; x < arrayData.width; x++)
{
int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255);
outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000);
}
}
ImageIO.write(outputImage, "PNG", new File(filename));
return;
}
public static void main(String[] args) throws IOException
{
ArrayData inputData = getArrayDataFromImage(args[0]);
int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]);
ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast);
writeOutputImage(args[1], outputData);
return;
}
}
| require 'mathn'
require 'rubygems'
require 'gd2'
include GD2
def hough_transform(img)
mx, my = img.w*0.5, img.h*0.5
max_d = Math.sqrt(mx**2 + my**2)
min_d = max_d * -1
hough = Hash.new(0)
(0..img.w).each do |x|
puts "
(0..img.h).each do |y|
if img.pixel2color(img.get_pixel(x,y)).g > 32
(0...180).each do |a|
rad = a * (Math::PI / 180.0)
d = (x-mx) * Math.cos(rad) + (y-my) * Math.sin(rad)
hough["
end
end
end
end
heat = GD2::Image.import 'heatmap.png'
out = GD2::Image::TrueColor.new(180,max_d*2)
max = hough.values.max
p max
hough.each_pair do |k,v|
a,d = k.split('_').map(&:to_i)
c = (v / max) * 255
c = heat.get_pixel(c,0)
out.set_pixel(a, max_d + d, c)
end
out
end
|
Generate an equivalent Ruby version of this Java code. | import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;
public class TonelliShanks {
private static final BigInteger ZERO = BigInteger.ZERO;
private static final BigInteger ONE = BigInteger.ONE;
private static final BigInteger TEN = BigInteger.TEN;
private static final BigInteger TWO = BigInteger.valueOf(2);
private static final BigInteger FOUR = BigInteger.valueOf(4);
private static class Solution {
private BigInteger root1;
private BigInteger root2;
private boolean exists;
Solution(BigInteger root1, BigInteger root2, boolean exists) {
this.root1 = root1;
this.root2 = root2;
this.exists = exists;
}
}
private static Solution ts(Long n, Long p) {
return ts(BigInteger.valueOf(n), BigInteger.valueOf(p));
}
private static Solution ts(BigInteger n, BigInteger p) {
BiFunction<BigInteger, BigInteger, BigInteger> powModP = (BigInteger a, BigInteger e) -> a.modPow(e, p);
Function<BigInteger, BigInteger> ls = (BigInteger a) -> powModP.apply(a, p.subtract(ONE).divide(TWO));
if (!ls.apply(n).equals(ONE)) return new Solution(ZERO, ZERO, false);
BigInteger q = p.subtract(ONE);
BigInteger ss = ZERO;
while (q.and(ONE).equals(ZERO)) {
ss = ss.add(ONE);
q = q.shiftRight(1);
}
if (ss.equals(ONE)) {
BigInteger r1 = powModP.apply(n, p.add(ONE).divide(FOUR));
return new Solution(r1, p.subtract(r1), true);
}
BigInteger z = TWO;
while (!ls.apply(z).equals(p.subtract(ONE))) z = z.add(ONE);
BigInteger c = powModP.apply(z, q);
BigInteger r = powModP.apply(n, q.add(ONE).divide(TWO));
BigInteger t = powModP.apply(n, q);
BigInteger m = ss;
while (true) {
if (t.equals(ONE)) return new Solution(r, p.subtract(r), true);
BigInteger i = ZERO;
BigInteger zz = t;
while (!zz.equals(BigInteger.ONE) && i.compareTo(m.subtract(ONE)) < 0) {
zz = zz.multiply(zz).mod(p);
i = i.add(ONE);
}
BigInteger b = c;
BigInteger e = m.subtract(i).subtract(ONE);
while (e.compareTo(ZERO) > 0) {
b = b.multiply(b).mod(p);
e = e.subtract(ONE);
}
r = r.multiply(b).mod(p);
c = b.multiply(b).mod(p);
t = t.multiply(c).mod(p);
m = i;
}
}
public static void main(String[] args) {
List<Map.Entry<Long, Long>> pairs = List.of(
Map.entry(10L, 13L),
Map.entry(56L, 101L),
Map.entry(1030L, 10009L),
Map.entry(1032L, 10009L),
Map.entry(44402L, 100049L),
Map.entry(665820697L, 1000000009L),
Map.entry(881398088036L, 1000000000039L)
);
for (Map.Entry<Long, Long> pair : pairs) {
Solution sol = ts(pair.getKey(), pair.getValue());
System.out.printf("n = %s\n", pair.getKey());
System.out.printf("p = %s\n", pair.getValue());
if (sol.exists) {
System.out.printf("root1 = %s\n", sol.root1);
System.out.printf("root2 = %s\n", sol.root2);
} else {
System.out.println("No solution exists");
}
System.out.println();
}
BigInteger bn = new BigInteger("41660815127637347468140745042827704103445750172002");
BigInteger bp = TEN.pow(50).add(BigInteger.valueOf(577));
Solution sol = ts(bn, bp);
System.out.printf("n = %s\n", bn);
System.out.printf("p = %s\n", bp);
if (sol.exists) {
System.out.printf("root1 = %s\n", sol.root1);
System.out.printf("root2 = %s\n", sol.root2);
} else {
System.out.println("No solution exists");
}
}
}
| func tonelli(n, p) {
legendre(n, p) == 1 || die "not a square (mod p)"
var q = p-1
var s = valuation(q, 2)
s == 1 ? return(powmod(n, (p + 1) >> 2, p)) : (q >>= s)
var c = powmod(2 ..^ p -> first {|z| legendre(z, p) == -1}, q, p)
var r = powmod(n, (q + 1) >> 1, p)
var t = powmod(n, q, p)
var m = s
var t2 = 0
while (!p.divides(t - 1)) {
t2 = ((t * t) % p)
var b
for i in (1 ..^ m) {
if (p.divides(t2 - 1)) {
b = powmod(c, 1 << (m - i - 1), p)
m = i
break
}
t2 = ((t2 * t2) % p)
}
r = ((r * b) % p)
c = ((b * b) % p)
t = ((t * c) % p)
}
return r
}
var tests = [
[10, 13], [56, 101], [1030, 10009], [44402, 100049],
[665820697, 1000000009], [881398088036, 1000000000039],
[41660815127637347468140745042827704103445750172002, 10**50 + 577],
]
for n,p in tests {
var r = tonelli(n, p)
assert((r*r - n) % p == 0)
say "Roots of
}
|
Convert this Java block to Ruby, preserving its control flow and logic. | import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
public class TruthTable {
public static void main( final String... args ) {
System.out.println( new TruthTable( args ) );
}
private interface Operator {
boolean evaluate( Stack<Boolean> s );
}
private static final Map<String,Operator> operators = new HashMap<String,Operator>() {{
put( "&", stack -> Boolean.logicalAnd( stack.pop(), stack.pop() ) );
put( "|", stack -> Boolean.logicalOr( stack.pop(), stack.pop() ) );
put( "!", stack -> ! stack.pop() );
put( "^", stack -> ! stack.pop().equals ( stack.pop() ) );
}};
private final List<String> variables;
private final String[] symbols;
public TruthTable( final String... symbols ) {
final Set<String> variables = new LinkedHashSet<>();
for ( final String symbol : symbols ) {
if ( ! operators.containsKey( symbol ) ) {
variables.add( symbol );
}
}
this.variables = new ArrayList<>( variables );
this.symbols = symbols;
}
@Override
public String toString () {
final StringBuilder result = new StringBuilder();
for ( final String variable : variables ) {
result.append( variable ).append( ' ' );
}
result.append( ' ' );
for ( final String symbol : symbols ) {
result.append( symbol ).append ( ' ' );
}
result.append( '\n' );
for ( final List<Boolean> values : enumerate( variables.size () ) ) {
final Iterator<String> i = variables.iterator();
for ( final Boolean value : values ) {
result.append(
String.format(
"%-" + i.next().length() + "c ",
value ? 'T' : 'F'
)
);
}
result.append( ' ' )
.append( evaluate( values ) ? 'T' : 'F' )
.append( '\n' );
}
return result.toString ();
}
private static List<List<Boolean>> enumerate( final int size ) {
if ( 1 == size )
return new ArrayList<List<Boolean>>() {{
add( new ArrayList<Boolean>() {{ add(false); }} );
add( new ArrayList<Boolean>() {{ add(true); }} );
}};
return new ArrayList<List<Boolean>>() {{
for ( final List<Boolean> head : enumerate( size - 1 ) ) {
add( new ArrayList<Boolean>( head ) {{ add(false); }} );
add( new ArrayList<Boolean>( head ) {{ add(true); }} );
}
}};
}
private boolean evaluate( final List<Boolean> enumeration ) {
final Iterator<Boolean> i = enumeration.iterator();
final Map<String,Boolean> values = new HashMap<>();
final Stack<Boolean> stack = new Stack<>();
variables.forEach ( v -> values.put( v, i.next() ) );
for ( final String symbol : symbols ) {
final Operator op = operators.get ( symbol );
stack.push(
null == op
? values.get ( symbol )
: op.evaluate ( stack )
);
}
return stack.pop();
}
}
| loop do
print "\ninput a boolean expression (e.g. 'a & b'): "
expr = gets.strip.downcase
break if expr.empty?
vars = expr.scan(/\p{Alpha}+/)
if vars.empty?
puts "no variables detected in your boolean expression"
next
end
vars.each {|v| print "
puts "|
prefix = []
suffix = []
vars.each do |v|
prefix << "[false, true].each do |
suffix << "end"
end
body = vars.inject("puts ") {|str, v| str + "
body += '"| " + eval(expr).to_s'
eval (prefix + [body] + suffix).join("\n")
end
|
Convert this Java block to Ruby, preserving its control flow and logic. | import java.util.Objects;
import java.util.function.Predicate;
public class RealNumberSet {
public enum RangeType {
CLOSED,
BOTH_OPEN,
LEFT_OPEN,
RIGHT_OPEN,
}
public static class RealSet {
private Double low;
private Double high;
private Predicate<Double> predicate;
private double interval = 0.00001;
public RealSet(Double low, Double high, Predicate<Double> predicate) {
this.low = low;
this.high = high;
this.predicate = predicate;
}
public RealSet(Double start, Double end, RangeType rangeType) {
this(start, end, d -> {
switch (rangeType) {
case CLOSED:
return start <= d && d <= end;
case BOTH_OPEN:
return start < d && d < end;
case LEFT_OPEN:
return start < d && d <= end;
case RIGHT_OPEN:
return start <= d && d < end;
default:
throw new IllegalStateException("Unhandled range type encountered.");
}
});
}
public boolean contains(Double d) {
return predicate.test(d);
}
public RealSet union(RealSet other) {
double low2 = Math.min(low, other.low);
double high2 = Math.max(high, other.high);
return new RealSet(low2, high2, d -> predicate.or(other.predicate).test(d));
}
public RealSet intersect(RealSet other) {
double low2 = Math.min(low, other.low);
double high2 = Math.max(high, other.high);
return new RealSet(low2, high2, d -> predicate.and(other.predicate).test(d));
}
public RealSet subtract(RealSet other) {
return new RealSet(low, high, d -> predicate.and(other.predicate.negate()).test(d));
}
public double length() {
if (low.isInfinite() || high.isInfinite()) return -1.0;
if (high <= low) return 0.0;
Double p = low;
int count = 0;
do {
if (predicate.test(p)) count++;
p += interval;
} while (p < high);
return count * interval;
}
public boolean isEmpty() {
if (Objects.equals(high, low)) {
return predicate.negate().test(low);
}
return length() == 0.0;
}
}
public static void main(String[] args) {
RealSet a = new RealSet(0.0, 1.0, RangeType.LEFT_OPEN);
RealSet b = new RealSet(0.0, 2.0, RangeType.RIGHT_OPEN);
RealSet c = new RealSet(1.0, 2.0, RangeType.LEFT_OPEN);
RealSet d = new RealSet(0.0, 3.0, RangeType.RIGHT_OPEN);
RealSet e = new RealSet(0.0, 1.0, RangeType.BOTH_OPEN);
RealSet f = new RealSet(0.0, 1.0, RangeType.CLOSED);
RealSet g = new RealSet(0.0, 0.0, RangeType.CLOSED);
for (int i = 0; i <= 2; i++) {
Double dd = (double) i;
System.out.printf("(0, 1] ∪ [0, 2) contains %d is %s\n", i, a.union(b).contains(dd));
System.out.printf("[0, 2) ∩ (1, 2] contains %d is %s\n", i, b.intersect(c).contains(dd));
System.out.printf("[0, 3) − (0, 1) contains %d is %s\n", i, d.subtract(e).contains(dd));
System.out.printf("[0, 3) − [0, 1] contains %d is %s\n", i, d.subtract(f).contains(dd));
System.out.println();
}
System.out.printf("[0, 0] is empty is %s\n", g.isEmpty());
System.out.println();
RealSet aa = new RealSet(
0.0, 10.0,
x -> (0.0 < x && x < 10.0) && Math.abs(Math.sin(Math.PI * x * x)) > 0.5
);
RealSet bb = new RealSet(
0.0, 10.0,
x -> (0.0 < x && x < 10.0) && Math.abs(Math.sin(Math.PI * x)) > 0.5
);
RealSet cc = aa.subtract(bb);
System.out.printf("Approx length of A - B is %f\n", cc.length());
}
}
| class Rset
Set = Struct.new(:lo, :hi, :inc_lo, :inc_hi) do
def include?(x)
(inc_lo ? lo<=x : lo<x) and (inc_hi ? x<=hi : x<hi)
end
def length
hi - lo
end
def to_s
"
end
end
def initialize(lo=nil, hi=nil, inc_lo=false, inc_hi=false)
if lo.nil? and hi.nil?
@sets = []
else
raise TypeError unless lo.is_a?(Numeric) and hi.is_a?(Numeric)
raise ArgumentError unless valid?(lo, hi, inc_lo, inc_hi)
@sets = [Set[lo, hi, !!inc_lo, !!inc_hi]]
end
end
def self.[](lo, hi, inc_hi=true)
self.new(lo, hi, true, inc_hi)
end
def self.parse(str)
raise ArgumentError unless str =~ /(\[|\()(.+),(.+)(\]|\))/
b0, lo, hi, b1 = $~.captures
lo = Rational(lo)
lo = lo.numerator if lo.denominator == 1
hi = Rational(hi)
hi = hi.numerator if hi.denominator == 1
self.new(lo, hi, b0=='[', b1==']')
end
def initialize_copy(obj)
super
@sets = @sets.map(&:dup)
end
def include?(x)
@sets.any?{|set| set.include?(x)}
end
def empty?
@sets.empty?
end
def union(other)
sets = (@sets+other.sets).map(&:dup).sort_by{|set| [set.lo, set.hi]}
work = []
pre = sets.shift
sets.each do |post|
if valid?(pre.hi, post.lo, !pre.inc_hi, !post.inc_lo)
work << pre
pre = post
else
pre.inc_lo |= post.inc_lo if pre.lo == post.lo
if pre.hi < post.hi
pre.hi = post.hi
pre.inc_hi = post.inc_hi
elsif pre.hi == post.hi
pre.inc_hi |= post.inc_hi
end
end
end
work << pre if pre
new_Rset(work)
end
alias | union
def intersection(other)
sets = @sets.map(&:dup)
work = []
other.sets.each do |oset|
sets.each do |set|
if set.hi < oset.lo or oset.hi < set.lo
elsif oset.lo < set.lo and set.hi < oset.hi
work << set
else
lo = [set.lo, oset.lo].max
if set.lo == oset.lo
inc_lo = set.inc_lo && oset.inc_lo
else
inc_lo = (set.lo < oset.lo) ? oset.inc_lo : set.inc_lo
end
hi = [set.hi, oset.hi].min
if set.hi == oset.hi
inc_hi = set.inc_hi && oset.inc_hi
else
inc_hi = (set.hi < oset.hi) ? set.inc_hi : oset.inc_hi
end
work << Set[lo, hi, inc_lo, inc_hi] if valid?(lo, hi, inc_lo, inc_hi)
end
end
end
new_Rset(work)
end
alias & intersection
def difference(other)
sets = @sets.map(&:dup)
other.sets.each do |oset|
work = []
sets.each do |set|
if set.hi < oset.lo or oset.hi < set.lo
work << set
elsif oset.lo < set.lo and set.hi < oset.hi
else
if set.lo < oset.lo
inc_hi = (set.hi==oset.lo and !set.inc_hi) ? false : !oset.inc_lo
work << Set[set.lo, oset.lo, set.inc_lo, inc_hi]
elsif valid?(set.lo, oset.lo, set.inc_lo, !oset.inc_lo)
work << Set[set.lo, set.lo, true, true]
end
if oset.hi < set.hi
inc_lo = (oset.hi==set.lo and !set.inc_lo) ? false : !oset.inc_hi
work << Set[oset.hi, set.hi, inc_lo, set.inc_hi]
elsif valid?(oset.hi, set.hi, !oset.inc_hi, set.inc_hi)
work << Set[set.hi, set.hi, true, true]
end
end
end
sets = work
end
new_Rset(sets)
end
alias - difference
def ^(other)
(self - other) | (other - self)
end
def ==(other)
self.class == other.class and @sets == other.sets
end
def length
@sets.inject(0){|len, set| len + set.length}
end
def to_s
"
end
alias inspect to_s
protected
attr_accessor :sets
private
def new_Rset(sets)
rset = self.class.new
rset.sets = sets
rset
end
def valid?(lo, hi, inc_lo, inc_hi)
lo < hi or (lo==hi and inc_lo and inc_hi)
end
end
def Rset(lo, hi, inc_hi=false)
Rset.new(lo, hi, false, inc_hi)
end
|
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version. | import java.util.Objects;
import java.util.function.Predicate;
public class RealNumberSet {
public enum RangeType {
CLOSED,
BOTH_OPEN,
LEFT_OPEN,
RIGHT_OPEN,
}
public static class RealSet {
private Double low;
private Double high;
private Predicate<Double> predicate;
private double interval = 0.00001;
public RealSet(Double low, Double high, Predicate<Double> predicate) {
this.low = low;
this.high = high;
this.predicate = predicate;
}
public RealSet(Double start, Double end, RangeType rangeType) {
this(start, end, d -> {
switch (rangeType) {
case CLOSED:
return start <= d && d <= end;
case BOTH_OPEN:
return start < d && d < end;
case LEFT_OPEN:
return start < d && d <= end;
case RIGHT_OPEN:
return start <= d && d < end;
default:
throw new IllegalStateException("Unhandled range type encountered.");
}
});
}
public boolean contains(Double d) {
return predicate.test(d);
}
public RealSet union(RealSet other) {
double low2 = Math.min(low, other.low);
double high2 = Math.max(high, other.high);
return new RealSet(low2, high2, d -> predicate.or(other.predicate).test(d));
}
public RealSet intersect(RealSet other) {
double low2 = Math.min(low, other.low);
double high2 = Math.max(high, other.high);
return new RealSet(low2, high2, d -> predicate.and(other.predicate).test(d));
}
public RealSet subtract(RealSet other) {
return new RealSet(low, high, d -> predicate.and(other.predicate.negate()).test(d));
}
public double length() {
if (low.isInfinite() || high.isInfinite()) return -1.0;
if (high <= low) return 0.0;
Double p = low;
int count = 0;
do {
if (predicate.test(p)) count++;
p += interval;
} while (p < high);
return count * interval;
}
public boolean isEmpty() {
if (Objects.equals(high, low)) {
return predicate.negate().test(low);
}
return length() == 0.0;
}
}
public static void main(String[] args) {
RealSet a = new RealSet(0.0, 1.0, RangeType.LEFT_OPEN);
RealSet b = new RealSet(0.0, 2.0, RangeType.RIGHT_OPEN);
RealSet c = new RealSet(1.0, 2.0, RangeType.LEFT_OPEN);
RealSet d = new RealSet(0.0, 3.0, RangeType.RIGHT_OPEN);
RealSet e = new RealSet(0.0, 1.0, RangeType.BOTH_OPEN);
RealSet f = new RealSet(0.0, 1.0, RangeType.CLOSED);
RealSet g = new RealSet(0.0, 0.0, RangeType.CLOSED);
for (int i = 0; i <= 2; i++) {
Double dd = (double) i;
System.out.printf("(0, 1] ∪ [0, 2) contains %d is %s\n", i, a.union(b).contains(dd));
System.out.printf("[0, 2) ∩ (1, 2] contains %d is %s\n", i, b.intersect(c).contains(dd));
System.out.printf("[0, 3) − (0, 1) contains %d is %s\n", i, d.subtract(e).contains(dd));
System.out.printf("[0, 3) − [0, 1] contains %d is %s\n", i, d.subtract(f).contains(dd));
System.out.println();
}
System.out.printf("[0, 0] is empty is %s\n", g.isEmpty());
System.out.println();
RealSet aa = new RealSet(
0.0, 10.0,
x -> (0.0 < x && x < 10.0) && Math.abs(Math.sin(Math.PI * x * x)) > 0.5
);
RealSet bb = new RealSet(
0.0, 10.0,
x -> (0.0 < x && x < 10.0) && Math.abs(Math.sin(Math.PI * x)) > 0.5
);
RealSet cc = aa.subtract(bb);
System.out.printf("Approx length of A - B is %f\n", cc.length());
}
}
| class Rset
Set = Struct.new(:lo, :hi, :inc_lo, :inc_hi) do
def include?(x)
(inc_lo ? lo<=x : lo<x) and (inc_hi ? x<=hi : x<hi)
end
def length
hi - lo
end
def to_s
"
end
end
def initialize(lo=nil, hi=nil, inc_lo=false, inc_hi=false)
if lo.nil? and hi.nil?
@sets = []
else
raise TypeError unless lo.is_a?(Numeric) and hi.is_a?(Numeric)
raise ArgumentError unless valid?(lo, hi, inc_lo, inc_hi)
@sets = [Set[lo, hi, !!inc_lo, !!inc_hi]]
end
end
def self.[](lo, hi, inc_hi=true)
self.new(lo, hi, true, inc_hi)
end
def self.parse(str)
raise ArgumentError unless str =~ /(\[|\()(.+),(.+)(\]|\))/
b0, lo, hi, b1 = $~.captures
lo = Rational(lo)
lo = lo.numerator if lo.denominator == 1
hi = Rational(hi)
hi = hi.numerator if hi.denominator == 1
self.new(lo, hi, b0=='[', b1==']')
end
def initialize_copy(obj)
super
@sets = @sets.map(&:dup)
end
def include?(x)
@sets.any?{|set| set.include?(x)}
end
def empty?
@sets.empty?
end
def union(other)
sets = (@sets+other.sets).map(&:dup).sort_by{|set| [set.lo, set.hi]}
work = []
pre = sets.shift
sets.each do |post|
if valid?(pre.hi, post.lo, !pre.inc_hi, !post.inc_lo)
work << pre
pre = post
else
pre.inc_lo |= post.inc_lo if pre.lo == post.lo
if pre.hi < post.hi
pre.hi = post.hi
pre.inc_hi = post.inc_hi
elsif pre.hi == post.hi
pre.inc_hi |= post.inc_hi
end
end
end
work << pre if pre
new_Rset(work)
end
alias | union
def intersection(other)
sets = @sets.map(&:dup)
work = []
other.sets.each do |oset|
sets.each do |set|
if set.hi < oset.lo or oset.hi < set.lo
elsif oset.lo < set.lo and set.hi < oset.hi
work << set
else
lo = [set.lo, oset.lo].max
if set.lo == oset.lo
inc_lo = set.inc_lo && oset.inc_lo
else
inc_lo = (set.lo < oset.lo) ? oset.inc_lo : set.inc_lo
end
hi = [set.hi, oset.hi].min
if set.hi == oset.hi
inc_hi = set.inc_hi && oset.inc_hi
else
inc_hi = (set.hi < oset.hi) ? set.inc_hi : oset.inc_hi
end
work << Set[lo, hi, inc_lo, inc_hi] if valid?(lo, hi, inc_lo, inc_hi)
end
end
end
new_Rset(work)
end
alias & intersection
def difference(other)
sets = @sets.map(&:dup)
other.sets.each do |oset|
work = []
sets.each do |set|
if set.hi < oset.lo or oset.hi < set.lo
work << set
elsif oset.lo < set.lo and set.hi < oset.hi
else
if set.lo < oset.lo
inc_hi = (set.hi==oset.lo and !set.inc_hi) ? false : !oset.inc_lo
work << Set[set.lo, oset.lo, set.inc_lo, inc_hi]
elsif valid?(set.lo, oset.lo, set.inc_lo, !oset.inc_lo)
work << Set[set.lo, set.lo, true, true]
end
if oset.hi < set.hi
inc_lo = (oset.hi==set.lo and !set.inc_lo) ? false : !oset.inc_hi
work << Set[oset.hi, set.hi, inc_lo, set.inc_hi]
elsif valid?(oset.hi, set.hi, !oset.inc_hi, set.inc_hi)
work << Set[set.hi, set.hi, true, true]
end
end
end
sets = work
end
new_Rset(sets)
end
alias - difference
def ^(other)
(self - other) | (other - self)
end
def ==(other)
self.class == other.class and @sets == other.sets
end
def length
@sets.inject(0){|len, set| len + set.length}
end
def to_s
"
end
alias inspect to_s
protected
attr_accessor :sets
private
def new_Rset(sets)
rset = self.class.new
rset.sets = sets
rset
end
def valid?(lo, hi, inc_lo, inc_hi)
lo < hi or (lo==hi and inc_lo and inc_hi)
end
end
def Rset(lo, hi, inc_hi=false)
Rset.new(lo, hi, false, inc_hi)
end
|
Rewrite the snippet below in Ruby so it works the same as the original Java code. | import java.util.*;
import java.util.stream.*;
public class StateNamePuzzle {
static String[] states = {"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware", "Florida",
"Georgia", "hawaii", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa",
"Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts",
"Michigan", "Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico",
"New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma",
"Oregon", "Pennsylvania", "Rhode Island", "South Carolina",
"South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming",
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory",};
public static void main(String[] args) {
solve(Arrays.asList(states));
}
static void solve(List<String> input) {
Map<String, String> orig = input.stream().collect(Collectors.toMap(
s -> s.replaceAll("\\s", "").toLowerCase(), s -> s, (s, a) -> s));
input = new ArrayList<>(orig.keySet());
Map<String, List<String[]>> map = new HashMap<>();
for (int i = 0; i < input.size() - 1; i++) {
String pair0 = input.get(i);
for (int j = i + 1; j < input.size(); j++) {
String[] pair = {pair0, input.get(j)};
String s = pair0 + pair[1];
String key = Arrays.toString(s.chars().sorted().toArray());
List<String[]> val = map.getOrDefault(key, new ArrayList<>());
val.add(pair);
map.put(key, val);
}
}
map.forEach((key, list) -> {
for (int i = 0; i < list.size() - 1; i++) {
String[] a = list.get(i);
for (int j = i + 1; j < list.size(); j++) {
String[] b = list.get(j);
if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4)
continue;
System.out.printf("%s + %s = %s + %s %n", orig.get(a[0]),
orig.get(a[1]), orig.get(b[0]), orig.get(b[1]));
}
}
});
}
}
| require 'set'
Primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
States = [
"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado",
"Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho",
"Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine",
"Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi",
"Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota", "Ohio",
"Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina",
"South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
]
def print_answer(states)
goedel = lambda {|str| str.chars.map {|c| Primes[c.ord - 65]}.reduce(:*)}
pairs = Hash.new {|h,k| h[k] = Array.new}
map = states.uniq.map {|state| [state, goedel[state.upcase.delete("^A-Z")]]}
map.combination(2) {|(s1,g1), (s2,g2)| pairs[g1 * g2] << [s1, s2]}
result = []
pairs.values.select {|val| val.length > 1}.each do |list_of_pairs|
list_of_pairs.combination(2) do |pair1, pair2|
if Set[*pair1, *pair2].length == 4
result << [pair1, pair2]
end
end
end
result.each_with_index do |(pair1, pair2), i|
puts "%d\t%s\t%s" % [i+1, pair1.join(', '), pair2.join(', ')]
end
end
puts "real states only"
print_answer(States)
puts ""
puts "with fictional states"
print_answer(States + ["New Kory", "Wen Kory", "York New", "Kory New", "New Kory"])
|
Convert this Java block to Ruby, preserving its control flow and logic. | import java.math.BigInteger;
public class SuperDNumbers {
public static void main(String[] args) {
for ( int i = 2 ; i <= 9 ; i++ ) {
superD(i, 10);
}
}
private static final void superD(int d, int max) {
long start = System.currentTimeMillis();
String test = "";
for ( int i = 0 ; i < d ; i++ ) {
test += (""+d);
}
int n = 0;
int i = 0;
System.out.printf("First %d super-%d numbers: %n", max, d);
while ( n < max ) {
i++;
BigInteger val = BigInteger.valueOf(d).multiply(BigInteger.valueOf(i).pow(d));
if ( val.toString().contains(test) ) {
n++;
System.out.printf("%d ", i);
}
}
long end = System.currentTimeMillis();
System.out.printf("%nRun time %d ms%n%n", end-start);
}
}
| (2..8).each do |d|
rep = d.to_s * d
print "
puts (2..).lazy.select{|n| (d * n**d).to_s.include?(rep) }.first(10).join(", ")
end
|
Produce a language-to-language conversion: from Java to Ruby, same semantics. | import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Vector;
public class RTextonyms {
private static final Map<Character, Character> mapping;
private int total, elements, textonyms, max_found;
private String filename, mappingResult;
private Vector<String> max_strings;
private Map<String, Vector<String>> values;
static {
mapping = new HashMap<Character, Character>();
mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2');
mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3');
mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4');
mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5');
mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6');
mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7');
mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8');
mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9');
}
public RTextonyms(String filename) {
this.filename = filename;
this.total = this.elements = this.textonyms = this.max_found = 0;
this.values = new HashMap<String, Vector<String>>();
this.max_strings = new Vector<String>();
return;
}
public void add(String line) {
String mapping = "";
total++;
if (!get_mapping(line)) {
return;
}
mapping = mappingResult;
if (values.get(mapping) == null) {
values.put(mapping, new Vector<String>());
}
int num_strings;
num_strings = values.get(mapping).size();
textonyms += num_strings == 1 ? 1 : 0;
elements++;
if (num_strings > max_found) {
max_strings.clear();
max_strings.add(mapping);
max_found = num_strings;
}
else if (num_strings == max_found) {
max_strings.add(mapping);
}
values.get(mapping).add(line);
return;
}
public void results() {
System.out.printf("Read %,d words from %s%n%n", total, filename);
System.out.printf("There are %,d words in %s which can be represented by the digit key mapping.%n", elements,
filename);
System.out.printf("They require %,d digit combinations to represent them.%n", values.size());
System.out.printf("%,d digit combinations represent Textonyms.%n", textonyms);
System.out.printf("The numbers mapping to the most words map to %,d words each:%n", max_found + 1);
for (String key : max_strings) {
System.out.printf("%16s maps to: %s%n", key, values.get(key).toString());
}
System.out.println();
return;
}
public void match(String key) {
Vector<String> match;
match = values.get(key);
if (match == null) {
System.out.printf("Key %s not found%n", key);
}
else {
System.out.printf("Key %s matches: %s%n", key, match.toString());
}
return;
}
private boolean get_mapping(String line) {
mappingResult = line;
StringBuilder mappingBuilder = new StringBuilder();
for (char cc : line.toCharArray()) {
if (Character.isAlphabetic(cc)) {
mappingBuilder.append(mapping.get(Character.toUpperCase(cc)));
}
else if (Character.isDigit(cc)) {
mappingBuilder.append(cc);
}
else {
return false;
}
}
mappingResult = mappingBuilder.toString();
return true;
}
public static void main(String[] args) {
String filename;
if (args.length > 0) {
filename = args[0];
}
else {
filename = "./unixdict.txt";
}
RTextonyms tc;
tc = new RTextonyms(filename);
Path fp = Paths.get(filename);
try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) {
while (fs.hasNextLine()) {
tc.add(fs.nextLine());
}
}
catch (IOException ex) {
ex.printStackTrace();
}
List<String> numbers = Arrays.asList(
"001", "228", "27484247", "7244967473642",
"."
);
tc.results();
for (String number : numbers) {
if (number.equals(".")) {
System.out.println();
}
else {
tc.match(number);
}
}
return;
}
}
| CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
NUMS = "22233344455566677778889999" * 2
dict = "unixdict.txt"
textonyms = File.open(dict){|f| f.map(&:chomp).group_by {|word| word.tr(CHARS, NUMS) } }
puts "There are
They require
puts "\n25287876746242:
|
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version. | package lvijay;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
public class Church {
public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {
}
public static ChurchNum zero() {
return f -> x -> x;
}
public static ChurchNum next(ChurchNum n) {
return f -> x -> f.apply(n.apply(f).apply(x));
}
public static ChurchNum plus(ChurchNum a) {
return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));
}
public static ChurchNum pow(ChurchNum m) {
return n -> m.apply(n);
}
public static ChurchNum mult(ChurchNum a) {
return b -> f -> x -> b.apply(a.apply(f)).apply(x);
}
public static ChurchNum toChurchNum(int n) {
if (n <= 0) {
return zero();
}
return next(toChurchNum(n - 1));
}
public static int toInt(ChurchNum c) {
AtomicInteger counter = new AtomicInteger(0);
ChurchNum funCounter = f -> {
counter.incrementAndGet();
return f;
};
plus(zero()).apply(c).apply(funCounter).apply(x -> x);
return counter.get();
}
public static void main(String[] args) {
ChurchNum zero = zero();
ChurchNum three = next(next(next(zero)));
ChurchNum four = next(next(next(next(zero))));
System.out.println("3+4=" + toInt(plus(three).apply(four)));
System.out.println("4+3=" + toInt(plus(four).apply(three)));
System.out.println("3*4=" + toInt(mult(three).apply(four)));
System.out.println("4*3=" + toInt(mult(four).apply(three)));
System.out.println("3^4=" + toInt(pow(four).apply(three)));
System.out.println("4^3=" + toInt(pow(three).apply(four)));
System.out.println(" 8=" + toInt(toChurchNum(8)));
}
}
| def zero(f)
return lambda {|x| x}
end
Zero = lambda { |f| zero(f) }
def succ(n)
return lambda { |f| lambda { |x| f.(n.(f).(x)) } }
end
Three = succ(succ(succ(Zero)))
def add(n, m)
return lambda { |f| lambda { |x| m.(f).(n.(f).(x)) } }
end
def mult(n, m)
return lambda { |f| lambda { |x| m.(n.(f)).(x) } }
end
def power(b, e)
return e.(b)
end
def int_from_couch(f)
countup = lambda { |i| i+1 }
f.(countup).(0)
end
def couch_from_int(x)
countdown = lambda { |i|
case i
when 0 then Zero
else succ(countdown.(i-1))
end
}
countdown.(x)
end
Four = couch_from_int(4)
puts [ add(Three, Four),
mult(Three, Four),
power(Three, Four),
power(Four, Three) ].map {|f| int_from_couch(f) }
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | package lvijay;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
public class Church {
public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {
}
public static ChurchNum zero() {
return f -> x -> x;
}
public static ChurchNum next(ChurchNum n) {
return f -> x -> f.apply(n.apply(f).apply(x));
}
public static ChurchNum plus(ChurchNum a) {
return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));
}
public static ChurchNum pow(ChurchNum m) {
return n -> m.apply(n);
}
public static ChurchNum mult(ChurchNum a) {
return b -> f -> x -> b.apply(a.apply(f)).apply(x);
}
public static ChurchNum toChurchNum(int n) {
if (n <= 0) {
return zero();
}
return next(toChurchNum(n - 1));
}
public static int toInt(ChurchNum c) {
AtomicInteger counter = new AtomicInteger(0);
ChurchNum funCounter = f -> {
counter.incrementAndGet();
return f;
};
plus(zero()).apply(c).apply(funCounter).apply(x -> x);
return counter.get();
}
public static void main(String[] args) {
ChurchNum zero = zero();
ChurchNum three = next(next(next(zero)));
ChurchNum four = next(next(next(next(zero))));
System.out.println("3+4=" + toInt(plus(three).apply(four)));
System.out.println("4+3=" + toInt(plus(four).apply(three)));
System.out.println("3*4=" + toInt(mult(three).apply(four)));
System.out.println("4*3=" + toInt(mult(four).apply(three)));
System.out.println("3^4=" + toInt(pow(four).apply(three)));
System.out.println("4^3=" + toInt(pow(three).apply(four)));
System.out.println(" 8=" + toInt(toChurchNum(8)));
}
}
| def zero(f)
return lambda {|x| x}
end
Zero = lambda { |f| zero(f) }
def succ(n)
return lambda { |f| lambda { |x| f.(n.(f).(x)) } }
end
Three = succ(succ(succ(Zero)))
def add(n, m)
return lambda { |f| lambda { |x| m.(f).(n.(f).(x)) } }
end
def mult(n, m)
return lambda { |f| lambda { |x| m.(n.(f)).(x) } }
end
def power(b, e)
return e.(b)
end
def int_from_couch(f)
countup = lambda { |i| i+1 }
f.(countup).(0)
end
def couch_from_int(x)
countdown = lambda { |i|
case i
when 0 then Zero
else succ(countdown.(i-1))
end
}
countdown.(x)
end
Four = couch_from_int(4)
puts [ add(Three, Four),
mult(Three, Four),
power(Three, Four),
power(Four, Three) ].map {|f| int_from_couch(f) }
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | import java.lang.reflect.Method;
public class ListMethods {
public int examplePublicInstanceMethod(char c, double d) {
return 42;
}
private boolean examplePrivateInstanceMethod(String s) {
return true;
}
public static void main(String[] args) {
Class clazz = ListMethods.class;
System.out.println("All public methods (including inherited):");
for (Method m : clazz.getMethods()) {
System.out.println(m);
}
System.out.println();
System.out.println("All declared methods (excluding inherited):");
for (Method m : clazz.getDeclaredMethods()) {
System.out.println(m);
}
}
}
|
class Super
CLASSNAME = 'super'
def initialize(name)
@name = name
def self.superOwn
'super owned'
end
end
def to_s
"Super(
end
def doSup
'did super stuff'
end
def self.superClassStuff
'did super class stuff'
end
protected
def protSup
"Super's protected"
end
private
def privSup
"Super's private"
end
end
module Other
def otherStuff
'did other stuff'
end
end
class Sub < Super
CLASSNAME = 'sub'
attr_reader :dynamic
include Other
def initialize(name, *args)
super(name)
@rest = args;
@dynamic = {}
def self.subOwn
'sub owned'
end
end
def methods(regular=true)
super + @dynamic.keys
end
def method_missing(name, *args, &block)
return super unless @dynamic.member?(name)
method = @dynamic[name]
if method.arity > 0
if method.parameters[0][1] == :self
args.unshift(self)
end
if method.lambda?
args += args + [nil] * [method.arity - args.length, 0].max
if method.parameters[-1][0] != :rest
args = args[0,method.arity]
end
end
method.call(*args)
else
method.call
end
end
def public_methods(all=true)
super + @dynamic.keys
end
def respond_to?(symbol, include_all=false)
@dynamic.member?(symbol) || super
end
def to_s
"Sub(
end
def doSub
'did sub stuff'
end
def self.subClassStuff
'did sub class stuff'
end
protected
def protSub
"Sub's protected"
end
private
def privSub
"Sub's private"
end
end
sup = Super.new('sup')
sub = Sub.new('sub', 0, 'I', 'two')
sub.dynamic[:incr] = proc {|i| i+1}
p sub.public_methods(false)
p sub.methods - Object.methods
p sub.public_methods - Object.public_methods
p sub.methods - sup.methods
p sub.methods(false)
p sub.singleton_methods
|
Translate this program into Ruby but keep the logic exactly as in Java. | import java.lang.reflect.Method;
class Example {
public int foo(int x) {
return 42 + x;
}
}
public class Main {
public static void main(String[] args) throws Exception {
Object example = new Example();
String name = "foo";
Class<?> clazz = example.getClass();
Method meth = clazz.getMethod(name, int.class);
Object result = meth.invoke(example, 5);
System.out.println(result);
}
}
| class Example
def foo
42
end
def bar(arg1, arg2, &block)
block.call arg1, arg2
end
end
symbol = :foo
Example.new.send symbol
Example.new.send( :bar, 1, 2 ) { |x,y| x+y }
args = [1, 2]
Example.new.send( "bar", *args ) { |x,y| x+y }
|
Write the same algorithm in Ruby as shown in this Java implementation. | import java.text.MessageFormat;
import java.text.ParseException;
public class CanonicalizeCIDR {
public static void main(String[] args) {
for (String test : TESTS) {
try {
CIDR cidr = new CIDR(test);
System.out.printf("%-18s -> %s\n", test, cidr.toString());
} catch (Exception ex) {
System.err.printf("Error parsing '%s': %s\n", test, ex.getLocalizedMessage());
}
}
}
private static class CIDR {
private CIDR(int address, int maskLength) {
this.address = address;
this.maskLength = maskLength;
}
private CIDR(String str) throws Exception {
Object[] args = new MessageFormat(FORMAT).parse(str);
int address = 0;
for (int i = 0; i < 4; ++i) {
int a = ((Number)args[i]).intValue();
if (a < 0 || a > 255)
throw new Exception("Invalid IP address");
address <<= 8;
address += a;
}
int maskLength = ((Number)args[4]).intValue();
if (maskLength < 1 || maskLength > 32)
throw new Exception("Invalid mask length");
int mask = ~((1 << (32 - maskLength)) - 1);
this.address = address & mask;
this.maskLength = maskLength;
}
public String toString() {
int address = this.address;
int d = address & 0xFF;
address >>= 8;
int c = address & 0xFF;
address >>= 8;
int b = address & 0xFF;
address >>= 8;
int a = address & 0xFF;
Object[] args = { a, b, c, d, maskLength };
return new MessageFormat(FORMAT).format(args);
}
private int address;
private int maskLength;
private static final String FORMAT = "{0,number,integer}.{1,number,integer}.{2,number,integer}.{3,number,integer}/{4,number,integer}";
};
private static final String[] TESTS = {
"87.70.141.1/22",
"36.18.154.103/12",
"62.62.197.11/29",
"67.137.119.181/4",
"161.214.74.21/24",
"184.232.176.184/18"
};
}
|
if ARGV.length == 0 then
ARGV = $stdin.readlines.map(&:chomp)
end
ARGV.each do |cidr|
dotted, size_str = cidr.split('/')
size = size_str.to_i
binary = dotted.split('.').map { |o| "%08b" % o }.join
binary[size .. -1] = '0' * (32 - size)
canon = binary.chars.each_slice(8).map { |a| a.join.to_i(2) }.join('.')
puts "
end
|
Convert this Java block to Ruby, preserving its control flow and logic. | import java.text.MessageFormat;
import java.text.ParseException;
public class CanonicalizeCIDR {
public static void main(String[] args) {
for (String test : TESTS) {
try {
CIDR cidr = new CIDR(test);
System.out.printf("%-18s -> %s\n", test, cidr.toString());
} catch (Exception ex) {
System.err.printf("Error parsing '%s': %s\n", test, ex.getLocalizedMessage());
}
}
}
private static class CIDR {
private CIDR(int address, int maskLength) {
this.address = address;
this.maskLength = maskLength;
}
private CIDR(String str) throws Exception {
Object[] args = new MessageFormat(FORMAT).parse(str);
int address = 0;
for (int i = 0; i < 4; ++i) {
int a = ((Number)args[i]).intValue();
if (a < 0 || a > 255)
throw new Exception("Invalid IP address");
address <<= 8;
address += a;
}
int maskLength = ((Number)args[4]).intValue();
if (maskLength < 1 || maskLength > 32)
throw new Exception("Invalid mask length");
int mask = ~((1 << (32 - maskLength)) - 1);
this.address = address & mask;
this.maskLength = maskLength;
}
public String toString() {
int address = this.address;
int d = address & 0xFF;
address >>= 8;
int c = address & 0xFF;
address >>= 8;
int b = address & 0xFF;
address >>= 8;
int a = address & 0xFF;
Object[] args = { a, b, c, d, maskLength };
return new MessageFormat(FORMAT).format(args);
}
private int address;
private int maskLength;
private static final String FORMAT = "{0,number,integer}.{1,number,integer}.{2,number,integer}.{3,number,integer}/{4,number,integer}";
};
private static final String[] TESTS = {
"87.70.141.1/22",
"36.18.154.103/12",
"62.62.197.11/29",
"67.137.119.181/4",
"161.214.74.21/24",
"184.232.176.184/18"
};
}
|
if ARGV.length == 0 then
ARGV = $stdin.readlines.map(&:chomp)
end
ARGV.each do |cidr|
dotted, size_str = cidr.split('/')
size = size_str.to_i
binary = dotted.split('.').map { |o| "%08b" % o }.join
binary[size .. -1] = '0' * (32 - size)
canon = binary.chars.each_slice(8).map { |a| a.join.to_i(2) }.join('.')
puts "
end
|
Produce a language-to-language conversion: from Java to Ruby, same semantics. | import java.math.BigInteger;
public class PrimorialPrimes {
final static int sieveLimit = 1550_000;
static boolean[] notPrime = sieve(sieveLimit);
public static void main(String[] args) {
int count = 0;
for (int i = 1; i < 1000_000 && count < 20; i++) {
BigInteger b = primorial(i);
if (b.add(BigInteger.ONE).isProbablePrime(1)
|| b.subtract(BigInteger.ONE).isProbablePrime(1)) {
System.out.printf("%d ", i);
count++;
}
}
}
static BigInteger primorial(int n) {
if (n == 0)
return BigInteger.ONE;
BigInteger result = BigInteger.ONE;
for (int i = 0; i < sieveLimit && n > 0; i++) {
if (notPrime[i])
continue;
result = result.multiply(BigInteger.valueOf(i));
n--;
}
return result;
}
public static boolean[] sieve(int limit) {
boolean[] composite = new boolean[limit];
composite[0] = composite[1] = true;
int max = (int) Math.sqrt(limit);
for (int n = 2; n <= max; n++) {
if (!composite[n]) {
for (int k = n * n; k < limit; k += n) {
composite[k] = true;
}
}
}
return composite;
}
}
|
require 'prime'
require 'openssl'
i, urutan, primorial_number = 1, 1, OpenSSL::BN.new(1)
start = Time.now
prime_array = Prime.first (500)
until urutan > 20
primorial_number *= prime_array[i-1]
if (primorial_number - 1).prime_fasttest? || (primorial_number + 1).prime_fasttest?
puts "
urutan += 1
end
i += 1
end
|
Keep all operations the same but rewrite the snippet in Ruby. | import java.math.BigInteger;
public class CombinationsAndPermutations {
public static void main(String[] args) {
System.out.println(Double.MAX_VALUE);
System.out.println("A sample of permutations from 1 to 12 with exact Integer arithmetic:");
for ( int n = 1 ; n <= 12 ; n++ ) {
int k = n / 2;
System.out.printf("%d P %d = %s%n", n, k, permutation(n, k));
}
System.out.println();
System.out.println("A sample of combinations from 10 to 60 with exact Integer arithmetic:");
for ( int n = 10 ; n <= 60 ; n += 5 ) {
int k = n / 2;
System.out.printf("%d C %d = %s%n", n, k, combination(n, k));
}
System.out.println();
System.out.println("A sample of permutations from 5 to 15000 displayed in floating point arithmetic:");
System.out.printf("%d P %d = %s%n", 5, 2, display(permutation(5, 2), 50));
for ( int n = 1000 ; n <= 15000 ; n += 1000 ) {
int k = n / 2;
System.out.printf("%d P %d = %s%n", n, k, display(permutation(n, k), 50));
}
System.out.println();
System.out.println("A sample of combinations from 100 to 1000 displayed in floating point arithmetic:");
for ( int n = 100 ; n <= 1000 ; n += 100 ) {
int k = n / 2;
System.out.printf("%d C %d = %s%n", n, k, display(combination(n, k), 50));
}
}
private static String display(BigInteger val, int precision) {
String s = val.toString();
precision = Math.min(precision, s.length());
StringBuilder sb = new StringBuilder();
sb.append(s.substring(0, 1));
sb.append(".");
sb.append(s.substring(1, precision));
sb.append(" * 10^");
sb.append(s.length()-1);
return sb.toString();
}
public static BigInteger combination(int n, int k) {
if ( n-k < k ) {
k = n-k;
}
BigInteger result = permutation(n, k);
while ( k > 0 ) {
result = result.divide(BigInteger.valueOf(k));
k--;
}
return result;
}
public static BigInteger permutation(int n, int k) {
BigInteger result = BigInteger.ONE;
for ( int i = n ; i >= n-k+1 ; i-- ) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
}
| require "big"
include Math
struct Int
def permutation(k)
(self-k+1..self).product(1.to_big_i)
end
def combination(k)
self.permutation(k) // (1..k).product(1.to_big_i)
end
def big_permutation(k)
exp(lgamma_plus(self) - lgamma_plus(self-k))
end
def big_combination(k)
exp( lgamma_plus(self) - lgamma_plus(self - k) - lgamma_plus(k))
end
private def lgamma_plus(n)
lgamma(n+1)
end
end
p 12.permutation(9)
p 12.big_permutation(9)
p 60.combination(53)
p 145.big_permutation(133)
p 900.big_combination(450)
p 1000.big_combination(969)
p 15000.big_permutation(73)
p 15000.big_permutation(74)
p 15000.permutation(74)
|
Maintain the same structure and functionality when rewriting this code in Ruby. | import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Objects;
public class Calculate_Pi {
private static final MathContext con1024 = new MathContext(1024);
private static final BigDecimal bigTwo = new BigDecimal(2);
private static final BigDecimal bigFour = new BigDecimal(4);
private static BigDecimal bigSqrt(BigDecimal bd, MathContext con) {
BigDecimal x0 = BigDecimal.ZERO;
BigDecimal x1 = BigDecimal.valueOf(Math.sqrt(bd.doubleValue()));
while (!Objects.equals(x0, x1)) {
x0 = x1;
x1 = bd.divide(x0, con).add(x0).divide(bigTwo, con);
}
return x1;
}
public static void main(String[] args) {
BigDecimal a = BigDecimal.ONE;
BigDecimal g = a.divide(bigSqrt(bigTwo, con1024), con1024);
BigDecimal t;
BigDecimal sum = BigDecimal.ZERO;
BigDecimal pow = bigTwo;
while (!Objects.equals(a, g)) {
t = a.add(g).divide(bigTwo, con1024);
g = bigSqrt(a.multiply(g), con1024);
a = t;
pow = pow.multiply(bigTwo);
sum = sum.add(a.multiply(a).subtract(g.multiply(g)).multiply(pow));
}
BigDecimal pi = bigFour.multiply(a.multiply(a)).divide(BigDecimal.ONE.subtract(sum), con1024);
System.out.println(pi);
}
}
|
require 'flt'
Flt::BinNum.Context.precision = 8192
a = n = 1
g = 1 / Flt::BinNum(2).sqrt
z = 0.25
(0..17).each{
x = [(a + g) * 0.5, (a * g).sqrt]
var = x[0] - a
z -= var * var * n
n += n
a = x[0]
g = x[1]
}
puts a * a / z
|
Generate a Ruby translation of this Java snippet without changing its computational steps. | import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Objects;
public class Calculate_Pi {
private static final MathContext con1024 = new MathContext(1024);
private static final BigDecimal bigTwo = new BigDecimal(2);
private static final BigDecimal bigFour = new BigDecimal(4);
private static BigDecimal bigSqrt(BigDecimal bd, MathContext con) {
BigDecimal x0 = BigDecimal.ZERO;
BigDecimal x1 = BigDecimal.valueOf(Math.sqrt(bd.doubleValue()));
while (!Objects.equals(x0, x1)) {
x0 = x1;
x1 = bd.divide(x0, con).add(x0).divide(bigTwo, con);
}
return x1;
}
public static void main(String[] args) {
BigDecimal a = BigDecimal.ONE;
BigDecimal g = a.divide(bigSqrt(bigTwo, con1024), con1024);
BigDecimal t;
BigDecimal sum = BigDecimal.ZERO;
BigDecimal pow = bigTwo;
while (!Objects.equals(a, g)) {
t = a.add(g).divide(bigTwo, con1024);
g = bigSqrt(a.multiply(g), con1024);
a = t;
pow = pow.multiply(bigTwo);
sum = sum.add(a.multiply(a).subtract(g.multiply(g)).multiply(pow));
}
BigDecimal pi = bigFour.multiply(a.multiply(a)).divide(BigDecimal.ONE.subtract(sum), con1024);
System.out.println(pi);
}
}
|
require 'flt'
Flt::BinNum.Context.precision = 8192
a = n = 1
g = 1 / Flt::BinNum(2).sqrt
z = 0.25
(0..17).each{
x = [(a + g) * 0.5, (a * g).sqrt]
var = x[0] - a
z -= var * var * n
n += n
a = x[0]
g = x[1]
}
puts a * a / z
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | import java.util.LinkedList;
import java.util.List;
public class LongPrimes
{
private static void sieve(int limit, List<Integer> primes)
{
boolean[] c = new boolean[limit];
for (int i = 0; i < limit; i++)
c[i] = false;
int p = 3, n = 0;
int p2 = p * p;
while (p2 <= limit)
{
for (int i = p2; i <= limit; i += 2 * p)
c[i] = true;
do
p += 2;
while (c[p]);
p2 = p * p;
}
for (int i = 3; i <= limit; i += 2)
if (!c[i])
primes.add(i);
}
private static int findPeriod(int n)
{
int r = 1, period = 0;
for (int i = 1; i < n; i++)
r = (10 * r) % n;
int rr = r;
do
{
r = (10 * r) % n;
++period;
}
while (r != rr);
return period;
}
public static void main(String[] args)
{
int[] numbers = new int[]{500, 1000, 2000, 4000, 8000, 16000, 32000, 64000};
int[] totals = new int[numbers.length];
List<Integer> primes = new LinkedList<Integer>();
List<Integer> longPrimes = new LinkedList<Integer>();
sieve(64000, primes);
for (int prime : primes)
if (findPeriod(prime) == prime - 1)
longPrimes.add(prime);
int count = 0, index = 0;
for (int longPrime : longPrimes)
{
if (longPrime > numbers[index])
totals[index++] = count;
++count;
}
totals[numbers.length - 1] = count;
System.out.println("The long primes up to " + numbers[0] + " are:");
System.out.println(longPrimes.subList(0, totals[0]));
System.out.println();
System.out.println("The number of long primes up to:");
for (int i = 0; i <= 7; i++)
System.out.printf(" %5d is %d\n", numbers[i], totals[i]);
}
}
| require "big"
def prime?(n)
return n | 1 == 3 if n < 5
return false if n.gcd(6) != 1
pc = typeof(n).new(5)
until pc*pc > n
return false if n % pc == 0 || n % (pc + 2) == 0
pc += 6
end
true
end
def long_prime?(p)
return false unless prime? p
(2...p).each do |d|
return d == (p - 1) if (p - 1) % d == 0 && (10.to_big_i ** d) % p == 1
end
false
end
start = Time.monotonic
puts "Long primes ≤ 500:"
(2..500).each { |pc| print "
puts
[500, 1000, 2000, 4000, 8000, 16000, 32000, 64000].each do |n|
puts "Number of long primes ≤
end
puts "\nTime:
|
Change the following Java code into Ruby without altering its purpose. | import java.math.BigInteger;
public class PrimorialNumbers {
final static int sieveLimit = 1300_000;
static boolean[] notPrime = sieve(sieveLimit);
public static void main(String[] args) {
for (int i = 0; i < 10; i++)
System.out.printf("primorial(%d): %d%n", i, primorial(i));
for (int i = 1; i < 6; i++) {
int len = primorial((int) Math.pow(10, i)).toString().length();
System.out.printf("primorial(10^%d) has length %d%n", i, len);
}
}
static BigInteger primorial(int n) {
if (n == 0)
return BigInteger.ONE;
BigInteger result = BigInteger.ONE;
for (int i = 0; i < sieveLimit && n > 0; i++) {
if (notPrime[i])
continue;
result = result.multiply(BigInteger.valueOf(i));
n--;
}
return result;
}
public static boolean[] sieve(int limit) {
boolean[] composite = new boolean[limit];
composite[0] = composite[1] = true;
int max = (int) Math.sqrt(limit);
for (int n = 2; n <= max; n++) {
if (!composite[n]) {
for (int k = n * n; k < limit; k += n) {
composite[k] = true;
}
}
}
return composite;
}
}
| require 'prime'
def primorial_number(n)
pgen = Prime.each
(1..n).inject(1){|p,_| p*pgen.next}
end
puts "First ten primorials:
(1..5).each do |n|
puts "primorial(10**
end
|
Write the same code in Ruby as shown below in Java. | import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class EgyptianFractions {
private static BigInteger gcd(BigInteger a, BigInteger b) {
if (b.equals(BigInteger.ZERO)) {
return a;
}
return gcd(b, a.mod(b));
}
private static class Frac implements Comparable<Frac> {
private BigInteger num, denom;
public Frac(BigInteger n, BigInteger d) {
if (d.equals(BigInteger.ZERO)) {
throw new IllegalArgumentException("Parameter d may not be zero.");
}
BigInteger nn = n;
BigInteger dd = d;
if (nn.equals(BigInteger.ZERO)) {
dd = BigInteger.ONE;
} else if (dd.compareTo(BigInteger.ZERO) < 0) {
nn = nn.negate();
dd = dd.negate();
}
BigInteger g = gcd(nn, dd).abs();
if (g.compareTo(BigInteger.ZERO) > 0) {
nn = nn.divide(g);
dd = dd.divide(g);
}
num = nn;
denom = dd;
}
public Frac(int n, int d) {
this(BigInteger.valueOf(n), BigInteger.valueOf(d));
}
public Frac plus(Frac rhs) {
return new Frac(
num.multiply(rhs.denom).add(denom.multiply(rhs.num)),
rhs.denom.multiply(denom)
);
}
public Frac unaryMinus() {
return new Frac(num.negate(), denom);
}
public Frac minus(Frac rhs) {
return plus(rhs.unaryMinus());
}
@Override
public int compareTo(Frac rhs) {
BigDecimal diff = this.toBigDecimal().subtract(rhs.toBigDecimal());
if (diff.compareTo(BigDecimal.ZERO) < 0) {
return -1;
}
if (BigDecimal.ZERO.compareTo(diff) < 0) {
return 1;
}
return 0;
}
@Override
public boolean equals(Object obj) {
if (null == obj || !(obj instanceof Frac)) {
return false;
}
Frac rhs = (Frac) obj;
return compareTo(rhs) == 0;
}
@Override
public String toString() {
if (denom.equals(BigInteger.ONE)) {
return num.toString();
}
return String.format("%s/%s", num, denom);
}
public BigDecimal toBigDecimal() {
BigDecimal bdn = new BigDecimal(num);
BigDecimal bdd = new BigDecimal(denom);
return bdn.divide(bdd, MathContext.DECIMAL128);
}
public List<Frac> toEgyptian() {
if (num.equals(BigInteger.ZERO)) {
return Collections.singletonList(this);
}
List<Frac> fracs = new ArrayList<>();
if (num.abs().compareTo(denom.abs()) >= 0) {
Frac div = new Frac(num.divide(denom), BigInteger.ONE);
Frac rem = this.minus(div);
fracs.add(div);
toEgyptian(rem.num, rem.denom, fracs);
} else {
toEgyptian(num, denom, fracs);
}
return fracs;
}
public void toEgyptian(BigInteger n, BigInteger d, List<Frac> fracs) {
if (n.equals(BigInteger.ZERO)) {
return;
}
BigDecimal n2 = new BigDecimal(n);
BigDecimal d2 = new BigDecimal(d);
BigDecimal[] divRem = d2.divideAndRemainder(n2, MathContext.UNLIMITED);
BigInteger div = divRem[0].toBigInteger();
if (divRem[1].compareTo(BigDecimal.ZERO) > 0) {
div = div.add(BigInteger.ONE);
}
fracs.add(new Frac(BigInteger.ONE, div));
BigInteger n3 = d.negate().mod(n);
if (n3.compareTo(BigInteger.ZERO) < 0) {
n3 = n3.add(n);
}
BigInteger d3 = d.multiply(div);
Frac f = new Frac(n3, d3);
if (f.num.equals(BigInteger.ONE)) {
fracs.add(f);
return;
}
toEgyptian(f.num, f.denom, fracs);
}
}
public static void main(String[] args) {
List<Frac> fracs = List.of(
new Frac(43, 48),
new Frac(5, 121),
new Frac(2014, 59)
);
for (Frac frac : fracs) {
List<Frac> list = frac.toEgyptian();
Frac first = list.get(0);
if (first.denom.equals(BigInteger.ONE)) {
System.out.printf("%s -> [%s] + ", frac, first);
} else {
System.out.printf("%s -> %s", frac, first);
}
for (int i = 1; i < list.size(); ++i) {
System.out.printf(" + %s", list.get(i));
}
System.out.println();
}
for (Integer r : List.of(98, 998)) {
if (r == 98) {
System.out.println("\nFor proper fractions with 1 or 2 digits:");
} else {
System.out.println("\nFor proper fractions with 1, 2 or 3 digits:");
}
int maxSize = 0;
List<Frac> maxSizeFracs = new ArrayList<>();
BigInteger maxDen = BigInteger.ZERO;
List<Frac> maxDenFracs = new ArrayList<>();
boolean[][] sieve = new boolean[r + 1][];
for (int i = 0; i < r + 1; ++i) {
sieve[i] = new boolean[r + 2];
}
for (int i = 1; i < r; ++i) {
for (int j = i + 1; j < r + 1; ++j) {
if (sieve[i][j]) continue;
Frac f = new Frac(i, j);
List<Frac> list = f.toEgyptian();
int listSize = list.size();
if (listSize > maxSize) {
maxSize = listSize;
maxSizeFracs.clear();
maxSizeFracs.add(f);
} else if (listSize == maxSize) {
maxSizeFracs.add(f);
}
BigInteger listDen = list.get(list.size() - 1).denom;
if (listDen.compareTo(maxDen) > 0) {
maxDen = listDen;
maxDenFracs.clear();
maxDenFracs.add(f);
} else if (listDen.equals(maxDen)) {
maxDenFracs.add(f);
}
if (i < r / 2) {
int k = 2;
while (true) {
if (j * k > r + 1) break;
sieve[i * k][j * k] = true;
k++;
}
}
}
}
System.out.printf(" largest number of items = %s\n", maxSize);
System.out.printf("fraction(s) with this number : %s\n", maxSizeFracs);
String md = maxDen.toString();
System.out.printf(" largest denominator = %s digits, ", md.length());
System.out.printf("%s...%s\n", md.substring(0, 20), md.substring(md.length() - 20, md.length()));
System.out.printf("fraction(s) with this denominator : %s\n", maxDenFracs);
}
}
}
| def ef(fr)
ans = []
if fr >= 1
return [[fr.to_i], Rational(0, 1)] if fr.denominator == 1
intfr = fr.to_i
ans, fr = [intfr], fr - intfr
end
x, y = fr.numerator, fr.denominator
while x != 1
ans << Rational(1, (1/fr).ceil)
fr = Rational(-y % x, y * (1/fr).ceil)
x, y = fr.numerator, fr.denominator
end
ans << fr
end
for fr in [Rational(43, 48), Rational(5, 121), Rational(2014, 59)]
puts '%s => %s' % [fr, ef(fr).join(' + ')]
end
lenmax = denommax = [0]
for b in 2..99
for a in 1...b
fr = Rational(a,b)
e = ef(fr)
elen, edenom = e.length, e[-1].denominator
lenmax = [elen, fr] if elen > lenmax[0]
denommax = [edenom, fr] if edenom > denommax[0]
end
end
puts 'Term max is %s with %i terms' % [lenmax[1], lenmax[0]]
dstr = denommax[0].to_s
puts 'Denominator max is %s with %i digits' % [denommax[1], dstr.size], dstr
|
Produce a functionally identical Ruby code for the snippet given in Java. | import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class EgyptianFractions {
private static BigInteger gcd(BigInteger a, BigInteger b) {
if (b.equals(BigInteger.ZERO)) {
return a;
}
return gcd(b, a.mod(b));
}
private static class Frac implements Comparable<Frac> {
private BigInteger num, denom;
public Frac(BigInteger n, BigInteger d) {
if (d.equals(BigInteger.ZERO)) {
throw new IllegalArgumentException("Parameter d may not be zero.");
}
BigInteger nn = n;
BigInteger dd = d;
if (nn.equals(BigInteger.ZERO)) {
dd = BigInteger.ONE;
} else if (dd.compareTo(BigInteger.ZERO) < 0) {
nn = nn.negate();
dd = dd.negate();
}
BigInteger g = gcd(nn, dd).abs();
if (g.compareTo(BigInteger.ZERO) > 0) {
nn = nn.divide(g);
dd = dd.divide(g);
}
num = nn;
denom = dd;
}
public Frac(int n, int d) {
this(BigInteger.valueOf(n), BigInteger.valueOf(d));
}
public Frac plus(Frac rhs) {
return new Frac(
num.multiply(rhs.denom).add(denom.multiply(rhs.num)),
rhs.denom.multiply(denom)
);
}
public Frac unaryMinus() {
return new Frac(num.negate(), denom);
}
public Frac minus(Frac rhs) {
return plus(rhs.unaryMinus());
}
@Override
public int compareTo(Frac rhs) {
BigDecimal diff = this.toBigDecimal().subtract(rhs.toBigDecimal());
if (diff.compareTo(BigDecimal.ZERO) < 0) {
return -1;
}
if (BigDecimal.ZERO.compareTo(diff) < 0) {
return 1;
}
return 0;
}
@Override
public boolean equals(Object obj) {
if (null == obj || !(obj instanceof Frac)) {
return false;
}
Frac rhs = (Frac) obj;
return compareTo(rhs) == 0;
}
@Override
public String toString() {
if (denom.equals(BigInteger.ONE)) {
return num.toString();
}
return String.format("%s/%s", num, denom);
}
public BigDecimal toBigDecimal() {
BigDecimal bdn = new BigDecimal(num);
BigDecimal bdd = new BigDecimal(denom);
return bdn.divide(bdd, MathContext.DECIMAL128);
}
public List<Frac> toEgyptian() {
if (num.equals(BigInteger.ZERO)) {
return Collections.singletonList(this);
}
List<Frac> fracs = new ArrayList<>();
if (num.abs().compareTo(denom.abs()) >= 0) {
Frac div = new Frac(num.divide(denom), BigInteger.ONE);
Frac rem = this.minus(div);
fracs.add(div);
toEgyptian(rem.num, rem.denom, fracs);
} else {
toEgyptian(num, denom, fracs);
}
return fracs;
}
public void toEgyptian(BigInteger n, BigInteger d, List<Frac> fracs) {
if (n.equals(BigInteger.ZERO)) {
return;
}
BigDecimal n2 = new BigDecimal(n);
BigDecimal d2 = new BigDecimal(d);
BigDecimal[] divRem = d2.divideAndRemainder(n2, MathContext.UNLIMITED);
BigInteger div = divRem[0].toBigInteger();
if (divRem[1].compareTo(BigDecimal.ZERO) > 0) {
div = div.add(BigInteger.ONE);
}
fracs.add(new Frac(BigInteger.ONE, div));
BigInteger n3 = d.negate().mod(n);
if (n3.compareTo(BigInteger.ZERO) < 0) {
n3 = n3.add(n);
}
BigInteger d3 = d.multiply(div);
Frac f = new Frac(n3, d3);
if (f.num.equals(BigInteger.ONE)) {
fracs.add(f);
return;
}
toEgyptian(f.num, f.denom, fracs);
}
}
public static void main(String[] args) {
List<Frac> fracs = List.of(
new Frac(43, 48),
new Frac(5, 121),
new Frac(2014, 59)
);
for (Frac frac : fracs) {
List<Frac> list = frac.toEgyptian();
Frac first = list.get(0);
if (first.denom.equals(BigInteger.ONE)) {
System.out.printf("%s -> [%s] + ", frac, first);
} else {
System.out.printf("%s -> %s", frac, first);
}
for (int i = 1; i < list.size(); ++i) {
System.out.printf(" + %s", list.get(i));
}
System.out.println();
}
for (Integer r : List.of(98, 998)) {
if (r == 98) {
System.out.println("\nFor proper fractions with 1 or 2 digits:");
} else {
System.out.println("\nFor proper fractions with 1, 2 or 3 digits:");
}
int maxSize = 0;
List<Frac> maxSizeFracs = new ArrayList<>();
BigInteger maxDen = BigInteger.ZERO;
List<Frac> maxDenFracs = new ArrayList<>();
boolean[][] sieve = new boolean[r + 1][];
for (int i = 0; i < r + 1; ++i) {
sieve[i] = new boolean[r + 2];
}
for (int i = 1; i < r; ++i) {
for (int j = i + 1; j < r + 1; ++j) {
if (sieve[i][j]) continue;
Frac f = new Frac(i, j);
List<Frac> list = f.toEgyptian();
int listSize = list.size();
if (listSize > maxSize) {
maxSize = listSize;
maxSizeFracs.clear();
maxSizeFracs.add(f);
} else if (listSize == maxSize) {
maxSizeFracs.add(f);
}
BigInteger listDen = list.get(list.size() - 1).denom;
if (listDen.compareTo(maxDen) > 0) {
maxDen = listDen;
maxDenFracs.clear();
maxDenFracs.add(f);
} else if (listDen.equals(maxDen)) {
maxDenFracs.add(f);
}
if (i < r / 2) {
int k = 2;
while (true) {
if (j * k > r + 1) break;
sieve[i * k][j * k] = true;
k++;
}
}
}
}
System.out.printf(" largest number of items = %s\n", maxSize);
System.out.printf("fraction(s) with this number : %s\n", maxSizeFracs);
String md = maxDen.toString();
System.out.printf(" largest denominator = %s digits, ", md.length());
System.out.printf("%s...%s\n", md.substring(0, 20), md.substring(md.length() - 20, md.length()));
System.out.printf("fraction(s) with this denominator : %s\n", maxDenFracs);
}
}
}
| def ef(fr)
ans = []
if fr >= 1
return [[fr.to_i], Rational(0, 1)] if fr.denominator == 1
intfr = fr.to_i
ans, fr = [intfr], fr - intfr
end
x, y = fr.numerator, fr.denominator
while x != 1
ans << Rational(1, (1/fr).ceil)
fr = Rational(-y % x, y * (1/fr).ceil)
x, y = fr.numerator, fr.denominator
end
ans << fr
end
for fr in [Rational(43, 48), Rational(5, 121), Rational(2014, 59)]
puts '%s => %s' % [fr, ef(fr).join(' + ')]
end
lenmax = denommax = [0]
for b in 2..99
for a in 1...b
fr = Rational(a,b)
e = ef(fr)
elen, edenom = e.length, e[-1].denominator
lenmax = [elen, fr] if elen > lenmax[0]
denommax = [edenom, fr] if edenom > denommax[0]
end
end
puts 'Term max is %s with %i terms' % [lenmax[1], lenmax[0]]
dstr = denommax[0].to_s
puts 'Denominator max is %s with %i digits' % [denommax[1], dstr.size], dstr
|
Port the provided Java code into Ruby while preserving the original functionality. | import static java.lang.Math.*;
import java.util.function.Function;
public class Test {
final static int N = 5;
static double[] lroots = new double[N];
static double[] weight = new double[N];
static double[][] lcoef = new double[N + 1][N + 1];
static void legeCoef() {
lcoef[0][0] = lcoef[1][1] = 1;
for (int n = 2; n <= N; n++) {
lcoef[n][0] = -(n - 1) * lcoef[n - 2][0] / n;
for (int i = 1; i <= n; i++) {
lcoef[n][i] = ((2 * n - 1) * lcoef[n - 1][i - 1]
- (n - 1) * lcoef[n - 2][i]) / n;
}
}
}
static double legeEval(int n, double x) {
double s = lcoef[n][n];
for (int i = n; i > 0; i--)
s = s * x + lcoef[n][i - 1];
return s;
}
static double legeDiff(int n, double x) {
return n * (x * legeEval(n, x) - legeEval(n - 1, x)) / (x * x - 1);
}
static void legeRoots() {
double x, x1;
for (int i = 1; i <= N; i++) {
x = cos(PI * (i - 0.25) / (N + 0.5));
do {
x1 = x;
x -= legeEval(N, x) / legeDiff(N, x);
} while (x != x1);
lroots[i - 1] = x;
x1 = legeDiff(N, x);
weight[i - 1] = 2 / ((1 - x * x) * x1 * x1);
}
}
static double legeInte(Function<Double, Double> f, double a, double b) {
double c1 = (b - a) / 2, c2 = (b + a) / 2, sum = 0;
for (int i = 0; i < N; i++)
sum += weight[i] * f.apply(c1 * lroots[i] + c2);
return c1 * sum;
}
public static void main(String[] args) {
legeCoef();
legeRoots();
System.out.print("Roots: ");
for (int i = 0; i < N; i++)
System.out.printf(" %f", lroots[i]);
System.out.print("\nWeight:");
for (int i = 0; i < N; i++)
System.out.printf(" %f", weight[i]);
System.out.printf("%nintegrating Exp(x) over [-3, 3]:%n\t%10.8f,%n"
+ "compared to actual%n\t%10.8f%n",
legeInte(x -> exp(x), -3, 3), exp(3) - exp(-3));
}
}
| func legendre_pair((1), x) { (x, 1) }
func legendre_pair( n, x) {
var (m1, m2) = legendre_pair(n - 1, x)
var u = (1 - 1/n)
((1 + u)*x*m1 - u*m2, m1)
}
func legendre((0), _) { 1 }
func legendre( n, x) { [legendre_pair(n, x)][0] }
func legendre_prime({ .is_zero }, _) { 0 }
func legendre_prime({ .is_one }, _) { 1 }
func legendre_prime(n, x) {
var (m0, m1) = legendre_pair(n, x)
(m1 - x*m0) * n / (1 - x**2)
}
func approximate_legendre_root(n, k) {
var t = ((4*k - 1) / (4*n + 2))
(1 - ((n - 1)/(8 * n**3))) * cos(Num.pi * t)
}
func newton_raphson(f, f_prime, r, eps = 2e-16) {
loop {
var dr = (-f(r) / f_prime(r))
dr.abs >= eps || break
r += dr
}
return r
}
func legendre_root(n, k) {
newton_raphson(legendre.method(:call, n), legendre_prime.method(:call, n),
approximate_legendre_root(n, k))
}
func weight(n, r) { 2 / ((1 - r**2) * legendre_prime(n, r)**2) }
func nodes(n) {
gather {
take(Pair(0, weight(n, 0))) if n.is_odd
{ |i|
var r = legendre_root(n, i)
var w = weight(n, r)
take(Pair(r, w), Pair(-r, w))
}.each(1 .. (n >> 1))
}
}
func quadrature(n, f, a, b, nds = nodes(n)) {
func scale(x) { (x*(b - a) + a + b) / 2 }
(b - a) / 2 * nds.sum { .second * f(scale(.first)) }
}
[(5..10)..., 20].each { |i|
printf("Gauss-Legendre %2d-point quadrature ∫₋₃⁺³ exp(x) dx ≈ %.15f\n",
i, quadrature(i, {.exp}, -3, +3))
}
|
Translate this program into Ruby but keep the logic exactly as in Java. | import java.util.*;
public class KdTree {
private int dimensions_;
private Node root_ = null;
private Node best_ = null;
private double bestDistance_ = 0;
private int visited_ = 0;
public KdTree(int dimensions, List<Node> nodes) {
dimensions_ = dimensions;
root_ = makeTree(nodes, 0, nodes.size(), 0);
}
public Node findNearest(Node target) {
if (root_ == null)
throw new IllegalStateException("Tree is empty!");
best_ = null;
visited_ = 0;
bestDistance_ = 0;
nearest(root_, target, 0);
return best_;
}
public int visited() {
return visited_;
}
public double distance() {
return Math.sqrt(bestDistance_);
}
private void nearest(Node root, Node target, int index) {
if (root == null)
return;
++visited_;
double d = root.distance(target);
if (best_ == null || d < bestDistance_) {
bestDistance_ = d;
best_ = root;
}
if (bestDistance_ == 0)
return;
double dx = root.get(index) - target.get(index);
index = (index + 1) % dimensions_;
nearest(dx > 0 ? root.left_ : root.right_, target, index);
if (dx * dx >= bestDistance_)
return;
nearest(dx > 0 ? root.right_ : root.left_, target, index);
}
private Node makeTree(List<Node> nodes, int begin, int end, int index) {
if (end <= begin)
return null;
int n = begin + (end - begin)/2;
Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));
index = (index + 1) % dimensions_;
node.left_ = makeTree(nodes, begin, n, index);
node.right_ = makeTree(nodes, n + 1, end, index);
return node;
}
private static class NodeComparator implements Comparator<Node> {
private int index_;
private NodeComparator(int index) {
index_ = index;
}
public int compare(Node n1, Node n2) {
return Double.compare(n1.get(index_), n2.get(index_));
}
}
public static class Node {
private double[] coords_;
private Node left_ = null;
private Node right_ = null;
public Node(double[] coords) {
coords_ = coords;
}
public Node(double x, double y) {
this(new double[]{x, y});
}
public Node(double x, double y, double z) {
this(new double[]{x, y, z});
}
double get(int index) {
return coords_[index];
}
double distance(Node node) {
double dist = 0;
for (int i = 0; i < coords_.length; ++i) {
double d = coords_[i] - node.coords_[i];
dist += d * d;
}
return dist;
}
public String toString() {
StringBuilder s = new StringBuilder("(");
for (int i = 0; i < coords_.length; ++i) {
if (i > 0)
s.append(", ");
s.append(coords_[i]);
}
s.append(')');
return s.toString();
}
}
}
| struct Kd_node {
d,
split,
left,
right,
}
struct Orthotope {
min,
max,
}
class Kd_tree(n, bounds) {
method init {
n = self.nk2(0, n);
}
method nk2(split, e) {
return(nil) if (e.len <= 0);
var exset = e.sort_by { _[split] }
var m = (exset.len // 2);
var d = exset[m];
while ((m+1 < exset.len) && (exset[m+1][split] == d[split])) {
++m;
}
var s2 = ((split + 1) % d.len);
Kd_node(d: d, split: split,
left: self.nk2(s2, exset.first(m)),
right: self.nk2(s2, exset.last(m-1)));
}
}
struct T3 {
nearest,
dist_sqd = Inf,
nodes_visited = 0,
}
func find_nearest(k, t, p) {
func nn(kd, target, hr, max_dist_sqd) {
kd || return T3(nearest: [0]*k);
var nodes_visited = 1;
var s = kd.split;
var pivot = kd.d;
var left_hr = Orthotope(hr.min, hr.max);
var right_hr = Orthotope(hr.min, hr.max);
left_hr.max[s] = pivot[s];
right_hr.min[s] = pivot[s];
var nearer_kd;
var further_kd;
var nearer_hr;
var further_hr;
if (target[s] <= pivot[s]) {
(nearer_kd, nearer_hr) = (kd.left, left_hr);
(further_kd, further_hr) = (kd.right, right_hr);
}
else {
(nearer_kd, nearer_hr) = (kd.right, right_hr);
(further_kd, further_hr) = (kd.left, left_hr);
}
var n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd);
var nearest = n1.nearest;
var dist_sqd = n1.dist_sqd;
nodes_visited += n1.nodes_visited;
if (dist_sqd < max_dist_sqd) {
max_dist_sqd = dist_sqd;
}
var d = (pivot[s] - target[s] -> sqr);
if (d > max_dist_sqd) {
return T3(nearest: nearest, dist_sqd: dist_sqd, nodes_visited: nodes_visited);
}
d = (pivot ~Z- target »sqr»() «+»);
if (d < dist_sqd) {
nearest = pivot;
dist_sqd = d;
max_dist_sqd = dist_sqd;
}
var n2 = nn(further_kd, target, further_hr, max_dist_sqd);
nodes_visited += n2.nodes_visited;
if (n2.dist_sqd < dist_sqd) {
nearest = n2.nearest;
dist_sqd = n2.dist_sqd;
}
T3(nearest: nearest, dist_sqd: dist_sqd, nodes_visited: nodes_visited);
}
return nn(t.n, p, t.bounds, Inf);
}
func show_nearest(k, heading, kd, p) {
print <<-"END"
Point: [
END
var n = find_nearest(k, kd, p);
print <<-"END"
Nearest neighbor: [
Distance:
Nodes visited:
END
}
func random_point(k) { k.of { 1.rand } }
func random_points(k, n) { n.of { random_point(k) } }
var kd1 = Kd_tree([[2, 3],[5, 4],[9, 6],[4, 7],[8, 1],[7, 2]],
Orthotope(min: [0, 0], max: [10, 10]));
show_nearest(2, "Wikipedia example data", kd1, [9, 2]);
var N = 1000
var t0 = Time.micro
var kd2 = Kd_tree(random_points(3, N), Orthotope(min: [0,0,0], max: [1,1,1]))
var t1 = Time.micro
show_nearest(2,
"k-d tree with
kd2, random_point(3))
|
Translate this program into Ruby but keep the logic exactly as in Java. | import java.util.*;
public class CutRectangle {
private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
public static void main(String[] args) {
cutRectangle(2, 2);
cutRectangle(4, 3);
}
static void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1)
return;
int[][] grid = new int[h][w];
Stack<Integer> stack = new Stack<>();
int half = (w * h) / 2;
long bits = (long) Math.pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.pop();
int r = pos / w;
int c = pos % w;
for (int[] dir : dirs) {
int nextR = r + dir[0];
int nextC = c + dir[1];
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
}
}
}
static void printResult(int[][] arr) {
for (int[] a : arr)
System.out.println(Arrays.toString(a));
System.out.println();
}
}
| def cut_it(h, w)
if h.odd?
return 0 if w.odd?
h, w = w, h
end
return 1 if w == 1
nxt = [[w+1, 1, 0], [-w-1, -1, 0], [-1, 0, -1], [1, 0, 1]]
blen = (h + 1) * (w + 1) - 1
grid = [false] * (blen + 1)
walk = lambda do |y, x, count=0|
return count+1 if y==0 or y==h or x==0 or x==w
t = y * (w + 1) + x
grid[t] = grid[blen - t] = true
nxt.each do |nt, dy, dx|
count += walk[y + dy, x + dx] unless grid[t + nt]
end
grid[t] = grid[blen - t] = false
count
end
t = h / 2 * (w + 1) + w / 2
if w.odd?
grid[t] = grid[t + 1] = true
count = walk[h / 2, w / 2 - 1]
count + walk[h / 2 - 1, w / 2] * 2
else
grid[t] = true
count = walk[h / 2, w / 2 - 1]
return count * 2 if h == w
count + walk[h / 2 - 1, w / 2]
end
end
for w in 1..9
for h in 1..w
puts "%d x %d: %d" % [w, h, cut_it(w, h)] if (w * h).even?
end
end
|
Translate the given Java code snippet into Ruby without altering its behavior. | import java.util.*;
public class CutRectangle {
private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
public static void main(String[] args) {
cutRectangle(2, 2);
cutRectangle(4, 3);
}
static void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1)
return;
int[][] grid = new int[h][w];
Stack<Integer> stack = new Stack<>();
int half = (w * h) / 2;
long bits = (long) Math.pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.pop();
int r = pos / w;
int c = pos % w;
for (int[] dir : dirs) {
int nextR = r + dir[0];
int nextC = c + dir[1];
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
}
}
}
static void printResult(int[][] arr) {
for (int[] a : arr)
System.out.println(Arrays.toString(a));
System.out.println();
}
}
| def cut_it(h, w)
if h.odd?
return 0 if w.odd?
h, w = w, h
end
return 1 if w == 1
nxt = [[w+1, 1, 0], [-w-1, -1, 0], [-1, 0, -1], [1, 0, 1]]
blen = (h + 1) * (w + 1) - 1
grid = [false] * (blen + 1)
walk = lambda do |y, x, count=0|
return count+1 if y==0 or y==h or x==0 or x==w
t = y * (w + 1) + x
grid[t] = grid[blen - t] = true
nxt.each do |nt, dy, dx|
count += walk[y + dy, x + dx] unless grid[t + nt]
end
grid[t] = grid[blen - t] = false
count
end
t = h / 2 * (w + 1) + w / 2
if w.odd?
grid[t] = grid[t + 1] = true
count = walk[h / 2, w / 2 - 1]
count + walk[h / 2 - 1, w / 2] * 2
else
grid[t] = true
count = walk[h / 2, w / 2 - 1]
return count * 2 if h == w
count + walk[h / 2 - 1, w / 2]
end
end
for w in 1..9
for h in 1..w
puts "%d x %d: %d" % [w, h, cut_it(w, h)] if (w * h).even?
end
end
|
Please provide an equivalent version of this Java code in Ruby. | import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class ChaosGame extends JPanel {
static class ColoredPoint extends Point {
int colorIndex;
ColoredPoint(int x, int y, int idx) {
super(x, y);
colorIndex = idx;
}
}
Stack<ColoredPoint> stack = new Stack<>();
Point[] points = new Point[3];
Color[] colors = {Color.red, Color.green, Color.blue};
Random r = new Random();
public ChaosGame() {
Dimension dim = new Dimension(640, 640);
setPreferredSize(dim);
setBackground(Color.white);
int margin = 60;
int size = dim.width - 2 * margin;
points[0] = new Point(dim.width / 2, margin);
points[1] = new Point(margin, size);
points[2] = new Point(margin + size, size);
stack.push(new ColoredPoint(-1, -1, 0));
new Timer(10, (ActionEvent e) -> {
if (stack.size() < 50_000) {
for (int i = 0; i < 1000; i++)
addPoint();
repaint();
}
}).start();
}
private void addPoint() {
try {
int colorIndex = r.nextInt(3);
Point p1 = stack.peek();
Point p2 = points[colorIndex];
stack.add(halfwayPoint(p1, p2, colorIndex));
} catch (EmptyStackException e) {
e.printStackTrace();
}
}
void drawPoints(Graphics2D g) {
for (ColoredPoint p : stack) {
g.setColor(colors[p.colorIndex]);
g.fillOval(p.x, p.y, 1, 1);
}
}
ColoredPoint halfwayPoint(Point a, Point b, int idx) {
return new ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawPoints(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Chaos Game");
f.setResizable(false);
f.add(new ChaosGame(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
| require('Imager')
var width = 600
var height = 600
var points = [
[width//2, 0],
[ 0, height-1],
[height-1, height-1],
]
var img = %O|Imager|.new(
xsize => width,
ysize => height,
)
var color = %O|Imager::Color|.new('
var r = [(width-1).irand, (height-1).irand]
30000.times {
var p = points.rand
r[] = (
(p[0] + r[0]) // 2,
(p[1] + r[1]) // 2,
)
img.setpixel(
x => r[0],
y => r[1],
color => color,
)
}
img.write(file => 'chaos_game.png')
|
Ensure the translated Ruby code behaves exactly like the original Java snippet. | import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class ChaosGame extends JPanel {
static class ColoredPoint extends Point {
int colorIndex;
ColoredPoint(int x, int y, int idx) {
super(x, y);
colorIndex = idx;
}
}
Stack<ColoredPoint> stack = new Stack<>();
Point[] points = new Point[3];
Color[] colors = {Color.red, Color.green, Color.blue};
Random r = new Random();
public ChaosGame() {
Dimension dim = new Dimension(640, 640);
setPreferredSize(dim);
setBackground(Color.white);
int margin = 60;
int size = dim.width - 2 * margin;
points[0] = new Point(dim.width / 2, margin);
points[1] = new Point(margin, size);
points[2] = new Point(margin + size, size);
stack.push(new ColoredPoint(-1, -1, 0));
new Timer(10, (ActionEvent e) -> {
if (stack.size() < 50_000) {
for (int i = 0; i < 1000; i++)
addPoint();
repaint();
}
}).start();
}
private void addPoint() {
try {
int colorIndex = r.nextInt(3);
Point p1 = stack.peek();
Point p2 = points[colorIndex];
stack.add(halfwayPoint(p1, p2, colorIndex));
} catch (EmptyStackException e) {
e.printStackTrace();
}
}
void drawPoints(Graphics2D g) {
for (ColoredPoint p : stack) {
g.setColor(colors[p.colorIndex]);
g.fillOval(p.x, p.y, 1, 1);
}
}
ColoredPoint halfwayPoint(Point a, Point b, int idx) {
return new ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawPoints(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Chaos Game");
f.setResizable(false);
f.add(new ChaosGame(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
| require('Imager')
var width = 600
var height = 600
var points = [
[width//2, 0],
[ 0, height-1],
[height-1, height-1],
]
var img = %O|Imager|.new(
xsize => width,
ysize => height,
)
var color = %O|Imager::Color|.new('
var r = [(width-1).irand, (height-1).irand]
30000.times {
var p = points.rand
r[] = (
(p[0] + r[0]) // 2,
(p[1] + r[1]) // 2,
)
img.setpixel(
x => r[0],
y => r[1],
color => color,
)
}
img.write(file => 'chaos_game.png')
|
Preserve the algorithm and functionality while converting the code from Java to Ruby. | import java.util.Arrays;
public class GroupStage{
static String[] games = {"12", "13", "14", "23", "24", "34"};
static String results = "000000";
private static boolean nextResult(){
if(results.equals("222222")) return false;
int res = Integer.parseInt(results, 3) + 1;
results = Integer.toString(res, 3);
while(results.length() < 6) results = "0" + results;
return true;
}
public static void main(String[] args){
int[][] points = new int[4][10];
do{
int[] records = {0,0,0,0};
for(int i = 0; i < 6; i++){
switch(results.charAt(i)){
case '2': records[games[i].charAt(0) - '1'] += 3; break;
case '1':
records[games[i].charAt(0) - '1']++;
records[games[i].charAt(1) - '1']++;
break;
case '0': records[games[i].charAt(1) - '1'] += 3; break;
}
}
Arrays.sort(records);
points[0][records[0]]++;
points[1][records[1]]++;
points[2][records[2]]++;
points[3][records[3]]++;
}while(nextResult());
System.out.println("First place: " + Arrays.toString(points[3]));
System.out.println("Second place: " + Arrays.toString(points[2]));
System.out.println("Third place: " + Arrays.toString(points[1]));
System.out.println("Fourth place: " + Arrays.toString(points[0]));
}
}
| teams = [:a, :b, :c, :d]
matches = teams.combination(2).to_a
outcomes = [:win, :draw, :loss]
gains = {win:[3,0], draw:[1,1], loss:[0,3]}
places_histogram = Array.new(4) {Array.new(10,0)}
outcomes.repeated_permutation(6).each do |outcome|
results = Hash.new(0)
outcome.zip(matches).each do |decision, (team1, team2)|
results[team1] += gains[decision][0]
results[team2] += gains[decision][1]
end
results.values.sort.reverse.each_with_index do |points, place|
places_histogram[place][points] += 1
end
end
fmt = "%s :" + "%4s"*10
puts fmt % [" ", *0..9]
puts fmt % ["-", *["---"]*10]
places_histogram.each.with_index(1) {|hist,place| puts fmt % [place, *hist]}
|
Transform the following Java implementation into Ruby, maintaining the same output and logic. | import java.util.Stack;
public class ShuntingYard {
public static void main(String[] args) {
String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
System.out.printf("infix: %s%n", infix);
System.out.printf("postfix: %s%n", infixToPostfix(infix));
}
static String infixToPostfix(String infix) {
final String ops = "-+/*^";
StringBuilder sb = new StringBuilder();
Stack<Integer> s = new Stack<>();
for (String token : infix.split("\\s")) {
if (token.isEmpty())
continue;
char c = token.charAt(0);
int idx = ops.indexOf(c);
if (idx != -1) {
if (s.isEmpty())
s.push(idx);
else {
while (!s.isEmpty()) {
int prec2 = s.peek() / 2;
int prec1 = idx / 2;
if (prec2 > prec1 || (prec2 == prec1 && c != '^'))
sb.append(ops.charAt(s.pop())).append(' ');
else break;
}
s.push(idx);
}
}
else if (c == '(') {
s.push(-2);
}
else if (c == ')') {
while (s.peek() != -2)
sb.append(ops.charAt(s.pop())).append(' ');
s.pop();
}
else {
sb.append(token).append(' ');
}
}
while (!s.isEmpty())
sb.append(ops.charAt(s.pop())).append(' ');
return sb.toString();
}
}
| rpn = RPNExpression.from_infix("3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3")
|
Port the provided Java code into Ruby while preserving the original functionality. |
public final class ImprovedNoise {
static public double noise(double x, double y, double z) {
int X = (int)Math.floor(x) & 255,
Y = (int)Math.floor(y) & 255,
Z = (int)Math.floor(z) & 255;
x -= Math.floor(x);
y -= Math.floor(y);
z -= Math.floor(z);
double u = fade(x),
v = fade(y),
w = fade(z);
int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,
B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;
return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ),
grad(p[BA ], x-1, y , z )),
lerp(u, grad(p[AB ], x , y-1, z ),
grad(p[BB ], x-1, y-1, z ))),
lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ),
grad(p[BA+1], x-1, y , z-1 )),
lerp(u, grad(p[AB+1], x , y-1, z-1 ),
grad(p[BB+1], x-1, y-1, z-1 ))));
}
static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }
static double lerp(double t, double a, double b) { return a + t * (b - a); }
static double grad(int hash, double x, double y, double z) {
int h = hash & 15;
double u = h<8 ? x : y,
v = h<4 ? y : h==12||h==14 ? x : z;
return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);
}
static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15,
131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180
};
static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; }
}
| const p = (%w'47 4G 3T 2J 2I F 3N D 5L 2N 2O 1H 5E 6H 7 69 3W 10 2V U 1X 3Y 8
2R 11 6O L A N 5A 6 44 6V 3C 6I 23 0 Q 5H 1Q 2M 70 63 5N 39 Z B W 1L 4X X 2G
6L 45 1K 2F 4U K 3H 3S 4R 4O 1W 4V 22 4L 1Z 3Q 3V 1C R 4M 25 42 4E 6F 2B 33 6D
3E 1O 5V 3P 6E 64 2X 2K 15 1J 1A 6T 14 6S 2U 3Z 1I 1T P 1R 4H 1 60 28 21 5T 24
3O 57 5S 2H I 4P 5K 5G 3R 3M 38 58 4F 2E 4K 2S 31 5I 4T 56 3 1S 1G 61 6A 6Y 3G
3F 5 5M 12 43 3A 3I 73 2A 2D 5W 5R 5Q 1N 6B 1B G 1M H 52 59 S 16 67 53 4Q 5X
3B 6W 48 2 18 4A 4J 1Y 65 49 2T 4B 4N 17 4S 9 3L M 13 71 J 2Q 30 32 27 35 68
6G 4Y 55 34 2W 62 6U 2P 6C 6Z Y 6Q 5D 6M 5U 40 C 5B 4Z 4I 6P 29 1F 41 6J 6X E
6N 2Z 1D 5C 5Y V 51 5J 2Y 4D 54 2C 5O 4W 37 3D 1E 19 3J 4 46 72 3U 6K 5P 2L 66
36 1V T O 20 6R 3X 3K 5F 26 1U 5Z 1P 4C 50' * 2 -> map {|n| Num(n, 36) })
func fade(n) { n * n * n * (n * (n * 6 - 15) + 10) }
func lerp(t, a, b) { a + t*(b-a) }
func grad(h, x, y, z) {
h &= 15
var u = (h < 8 ? x : y)
var v = (h < 4 ? y : (h ~~ [12,14] ? x : z))
(h&1 ? -u : u) + (h&2 ? -v : v)
}
func noise(x, y, z) {
var(X, Y, Z) = [x, y, z].map { .floor & 255 }...
var (u, v, w) = [x-=X, y-=Y, z-=Z].map { fade(_) }...
var (AA, AB) = with(p[X] + Y) {|i| (p[i] + Z, p[i+1] + Z) }
var (BA, BB) = with(p[X+1] + Y) {|i| (p[i] + Z, p[i+1] + Z) }
lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ),
grad(p[BA ], x-1, y , z )),
lerp(u, grad(p[AB ], x , y-1, z ),
grad(p[BB ], x-1, y-1, z ))),
lerp(v, lerp(u, grad(p[AA+1], x , y , z-1),
grad(p[BA+1], x-1, y , z-1)),
lerp(u, grad(p[AB+1], x , y-1, z-1),
grad(p[BB+1], x-1, y-1, z-1))))
}
say noise(3.14, 42, 7)
|
Convert the following code from Java to Ruby, ensuring the logic remains intact. | package astar;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;
class AStar {
private final List<Node> open;
private final List<Node> closed;
private final List<Node> path;
private final int[][] maze;
private Node now;
private final int xstart;
private final int ystart;
private int xend, yend;
private final boolean diag;
static class Node implements Comparable {
public Node parent;
public int x, y;
public double g;
public double h;
Node(Node parent, int xpos, int ypos, double g, double h) {
this.parent = parent;
this.x = xpos;
this.y = ypos;
this.g = g;
this.h = h;
}
@Override
public int compareTo(Object o) {
Node that = (Node) o;
return (int)((this.g + this.h) - (that.g + that.h));
}
}
AStar(int[][] maze, int xstart, int ystart, boolean diag) {
this.open = new ArrayList<>();
this.closed = new ArrayList<>();
this.path = new ArrayList<>();
this.maze = maze;
this.now = new Node(null, xstart, ystart, 0, 0);
this.xstart = xstart;
this.ystart = ystart;
this.diag = diag;
}
public List<Node> findPathTo(int xend, int yend) {
this.xend = xend;
this.yend = yend;
this.closed.add(this.now);
addNeigborsToOpenList();
while (this.now.x != this.xend || this.now.y != this.yend) {
if (this.open.isEmpty()) {
return null;
}
this.now = this.open.get(0);
this.open.remove(0);
this.closed.add(this.now);
addNeigborsToOpenList();
}
this.path.add(0, this.now);
while (this.now.x != this.xstart || this.now.y != this.ystart) {
this.now = this.now.parent;
this.path.add(0, this.now);
}
return this.path;
}
public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){
Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();
if(maze[stateNode.getR()][stateNode.getC()] == 2){
if(isNodeILegal(stateNode, stateNode.expandDirection())){
exploreNodes.add(stateNode.expandDirection());
}
}
public void AStarSearch(){
this.start.setCostToGoal(this.start.calculateCost(this.goal));
this.start.setPathCost(0);
this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());
Mazecoord intialNode = this.start;
Mazecoord stateNode = intialNode;
frontier.add(intialNode);
while (true){
if(frontier.isEmpty()){
System.out.println("fail");
System.out.println(explored.size());
System.exit(-1);
}
}
public int calculateCost(Mazecoord goal){
int rState = this.getR();
int rGoal = goal.getR();
int diffR = rState - rGoal;
int diffC = this.getC() - goal.getC();
if(diffR * diffC > 0) {
return Math.abs(diffR) + Math.abs(diffC);
} else {
return Math.max(Math.abs(diffR), Math.abs(diffC));
}
}
public Coord getFather(){
return this.father;
}
public void setFather(Mazecoord node){
this.father = node;
}
public int getAStartCost() {
return AStartCost;
}
public void setAStartCost(int aStartCost) {
AStartCost = aStartCost;
}
public int getCostToGoal() {
return costToGoal;
}
public void setCostToGoal(int costToGoal) {
this.costToGoal = costToGoal;
}
private double distance(int dx, int dy) {
if (this.diag) {
return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend);
} else {
return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend);
}
}
private void addNeigborsToOpenList() {
Node node;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
if (!this.diag && x != 0 && y != 0) {
continue;
}
node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));
if ((x != 0 || y != 0)
&& this.now.x + x >= 0 && this.now.x + x < this.maze[0].length
&& this.now.y + y >= 0 && this.now.y + y < this.maze.length
&& this.maze[this.now.y + y][this.now.x + x] != -1
&& !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) {
node.g = node.parent.g + 1.;
node.g += maze[this.now.y + y][this.now.x + x];
this.open.add(node);
}
}
}
Collections.sort(this.open);
}
public static void main(String[] args) {
int[][] maze = {
{ 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0,100,100,100, 0, 0},
{ 0, 0, 0, 0, 0,100, 0, 0},
{ 0, 0,100, 0, 0,100, 0, 0},
{ 0, 0,100, 0, 0,100, 0, 0},
{ 0, 0,100,100,100,100, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0},
};
AStar as = new AStar(maze, 0, 0, true);
List<Node> path = as.findPathTo(7, 7);
if (path != null) {
path.forEach((n) -> {
System.out.print("[" + n.x + ", " + n.y + "] ");
maze[n.y][n.x] = -1;
});
System.out.printf("\nTotal cost: %.02f\n", path.get(path.size() - 1).g);
for (int[] maze_row : maze) {
for (int maze_entry : maze_row) {
switch (maze_entry) {
case 0:
System.out.print("_");
break;
case -1:
System.out.print("*");
break;
default:
System.out.print("#");
}
}
System.out.println();
}
}
}
}
| class AStarGraph {
has barriers = [
[2,4],[2,5],[2,6],[3,6],[4,6],[5,6],[5,5],[5,4],[5,3],[5,2],[4,2],[3,2]
]
method heuristic(start, goal) {
var (D1 = 1, D2 = 1)
var dx = abs(start[0] - goal[0])
var dy = abs(start[1] - goal[1])
(D1 * (dx + dy)) + ((D2 - 2*D1) * Math.min(dx, dy))
}
method get_vertex_neighbours(pos) {
gather {
for dx, dy in [[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]] {
var x2 = (pos[0] + dx)
var y2 = (pos[1] + dy)
(x2<0 || x2>7 || y2<0 || y2>7) && next
take([x2, y2])
}
}
}
method move_cost(_a, b) {
barriers.contains(b) ? 100 : 1
}
}
func AStarSearch(start, end, graph) {
var G = Hash()
var F = Hash()
G{start} = 0
F{start} = graph.heuristic(start, end)
var closedVertices = []
var openVertices = [start]
var cameFrom = Hash()
while (openVertices) {
var current = nil
var currentFscore = Inf
for pos in openVertices {
if (F{pos} < currentFscore) {
currentFscore = F{pos}
current = pos
}
}
if (current == end) {
var path = [current]
while (cameFrom.contains(current)) {
current = cameFrom{current}
path << current
}
path.flip!
return (path, F{end})
}
openVertices.remove(current)
closedVertices.append(current)
for neighbour in (graph.get_vertex_neighbours(current)) {
if (closedVertices.contains(neighbour)) {
next
}
var candidateG = (G{current} + graph.move_cost(current, neighbour))
if (!openVertices.contains(neighbour)) {
openVertices.append(neighbour)
}
elsif (candidateG >= G{neighbour}) {
next
}
cameFrom{neighbour} = current
G{neighbour} = candidateG
var H = graph.heuristic(neighbour, end)
F{neighbour} = (G{neighbour} + H)
}
}
die "A* failed to find a solution"
}
var graph = AStarGraph()
var (route, cost) = AStarSearch([0,0], [7,7], graph)
var w = 10
var h = 10
var grid = h.of { w.of { "." } }
for y in (^h) { grid[y][0] = "█"; grid[y][-1] = "█" }
for x in (^w) { grid[0][x] = "█"; grid[-1][x] = "█" }
for x,y in (graph.barriers) { grid[x+1][y+1] = "█" }
for x,y in (route) { grid[x+1][y+1] = "x" }
grid.each { .join.say }
say "Path cost
|
Ensure the translated Ruby code behaves exactly like the original Java snippet. | package astar;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;
class AStar {
private final List<Node> open;
private final List<Node> closed;
private final List<Node> path;
private final int[][] maze;
private Node now;
private final int xstart;
private final int ystart;
private int xend, yend;
private final boolean diag;
static class Node implements Comparable {
public Node parent;
public int x, y;
public double g;
public double h;
Node(Node parent, int xpos, int ypos, double g, double h) {
this.parent = parent;
this.x = xpos;
this.y = ypos;
this.g = g;
this.h = h;
}
@Override
public int compareTo(Object o) {
Node that = (Node) o;
return (int)((this.g + this.h) - (that.g + that.h));
}
}
AStar(int[][] maze, int xstart, int ystart, boolean diag) {
this.open = new ArrayList<>();
this.closed = new ArrayList<>();
this.path = new ArrayList<>();
this.maze = maze;
this.now = new Node(null, xstart, ystart, 0, 0);
this.xstart = xstart;
this.ystart = ystart;
this.diag = diag;
}
public List<Node> findPathTo(int xend, int yend) {
this.xend = xend;
this.yend = yend;
this.closed.add(this.now);
addNeigborsToOpenList();
while (this.now.x != this.xend || this.now.y != this.yend) {
if (this.open.isEmpty()) {
return null;
}
this.now = this.open.get(0);
this.open.remove(0);
this.closed.add(this.now);
addNeigborsToOpenList();
}
this.path.add(0, this.now);
while (this.now.x != this.xstart || this.now.y != this.ystart) {
this.now = this.now.parent;
this.path.add(0, this.now);
}
return this.path;
}
public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){
Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();
if(maze[stateNode.getR()][stateNode.getC()] == 2){
if(isNodeILegal(stateNode, stateNode.expandDirection())){
exploreNodes.add(stateNode.expandDirection());
}
}
public void AStarSearch(){
this.start.setCostToGoal(this.start.calculateCost(this.goal));
this.start.setPathCost(0);
this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());
Mazecoord intialNode = this.start;
Mazecoord stateNode = intialNode;
frontier.add(intialNode);
while (true){
if(frontier.isEmpty()){
System.out.println("fail");
System.out.println(explored.size());
System.exit(-1);
}
}
public int calculateCost(Mazecoord goal){
int rState = this.getR();
int rGoal = goal.getR();
int diffR = rState - rGoal;
int diffC = this.getC() - goal.getC();
if(diffR * diffC > 0) {
return Math.abs(diffR) + Math.abs(diffC);
} else {
return Math.max(Math.abs(diffR), Math.abs(diffC));
}
}
public Coord getFather(){
return this.father;
}
public void setFather(Mazecoord node){
this.father = node;
}
public int getAStartCost() {
return AStartCost;
}
public void setAStartCost(int aStartCost) {
AStartCost = aStartCost;
}
public int getCostToGoal() {
return costToGoal;
}
public void setCostToGoal(int costToGoal) {
this.costToGoal = costToGoal;
}
private double distance(int dx, int dy) {
if (this.diag) {
return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend);
} else {
return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend);
}
}
private void addNeigborsToOpenList() {
Node node;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
if (!this.diag && x != 0 && y != 0) {
continue;
}
node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));
if ((x != 0 || y != 0)
&& this.now.x + x >= 0 && this.now.x + x < this.maze[0].length
&& this.now.y + y >= 0 && this.now.y + y < this.maze.length
&& this.maze[this.now.y + y][this.now.x + x] != -1
&& !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) {
node.g = node.parent.g + 1.;
node.g += maze[this.now.y + y][this.now.x + x];
this.open.add(node);
}
}
}
Collections.sort(this.open);
}
public static void main(String[] args) {
int[][] maze = {
{ 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0,100,100,100, 0, 0},
{ 0, 0, 0, 0, 0,100, 0, 0},
{ 0, 0,100, 0, 0,100, 0, 0},
{ 0, 0,100, 0, 0,100, 0, 0},
{ 0, 0,100,100,100,100, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0},
};
AStar as = new AStar(maze, 0, 0, true);
List<Node> path = as.findPathTo(7, 7);
if (path != null) {
path.forEach((n) -> {
System.out.print("[" + n.x + ", " + n.y + "] ");
maze[n.y][n.x] = -1;
});
System.out.printf("\nTotal cost: %.02f\n", path.get(path.size() - 1).g);
for (int[] maze_row : maze) {
for (int maze_entry : maze_row) {
switch (maze_entry) {
case 0:
System.out.print("_");
break;
case -1:
System.out.print("*");
break;
default:
System.out.print("#");
}
}
System.out.println();
}
}
}
}
| class AStarGraph {
has barriers = [
[2,4],[2,5],[2,6],[3,6],[4,6],[5,6],[5,5],[5,4],[5,3],[5,2],[4,2],[3,2]
]
method heuristic(start, goal) {
var (D1 = 1, D2 = 1)
var dx = abs(start[0] - goal[0])
var dy = abs(start[1] - goal[1])
(D1 * (dx + dy)) + ((D2 - 2*D1) * Math.min(dx, dy))
}
method get_vertex_neighbours(pos) {
gather {
for dx, dy in [[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]] {
var x2 = (pos[0] + dx)
var y2 = (pos[1] + dy)
(x2<0 || x2>7 || y2<0 || y2>7) && next
take([x2, y2])
}
}
}
method move_cost(_a, b) {
barriers.contains(b) ? 100 : 1
}
}
func AStarSearch(start, end, graph) {
var G = Hash()
var F = Hash()
G{start} = 0
F{start} = graph.heuristic(start, end)
var closedVertices = []
var openVertices = [start]
var cameFrom = Hash()
while (openVertices) {
var current = nil
var currentFscore = Inf
for pos in openVertices {
if (F{pos} < currentFscore) {
currentFscore = F{pos}
current = pos
}
}
if (current == end) {
var path = [current]
while (cameFrom.contains(current)) {
current = cameFrom{current}
path << current
}
path.flip!
return (path, F{end})
}
openVertices.remove(current)
closedVertices.append(current)
for neighbour in (graph.get_vertex_neighbours(current)) {
if (closedVertices.contains(neighbour)) {
next
}
var candidateG = (G{current} + graph.move_cost(current, neighbour))
if (!openVertices.contains(neighbour)) {
openVertices.append(neighbour)
}
elsif (candidateG >= G{neighbour}) {
next
}
cameFrom{neighbour} = current
G{neighbour} = candidateG
var H = graph.heuristic(neighbour, end)
F{neighbour} = (G{neighbour} + H)
}
}
die "A* failed to find a solution"
}
var graph = AStarGraph()
var (route, cost) = AStarSearch([0,0], [7,7], graph)
var w = 10
var h = 10
var grid = h.of { w.of { "." } }
for y in (^h) { grid[y][0] = "█"; grid[y][-1] = "█" }
for x in (^w) { grid[0][x] = "█"; grid[-1][x] = "█" }
for x,y in (graph.barriers) { grid[x+1][y+1] = "█" }
for x,y in (route) { grid[x+1][y+1] = "x" }
grid.each { .join.say }
say "Path cost
|
Translate the given Java code snippet into Ruby without altering its behavior. | import java.math.BigInteger;
import java.util.*;
public class Lychrel {
static Map<BigInteger, Tuple> cache = new HashMap<>();
static class Tuple {
final Boolean flag;
final BigInteger bi;
Tuple(boolean f, BigInteger b) {
flag = f;
bi = b;
}
}
static BigInteger rev(BigInteger bi) {
String s = new StringBuilder(bi.toString()).reverse().toString();
return new BigInteger(s);
}
static Tuple lychrel(BigInteger n) {
Tuple res;
if ((res = cache.get(n)) != null)
return res;
BigInteger r = rev(n);
res = new Tuple(true, n);
List<BigInteger> seen = new ArrayList<>();
for (int i = 0; i < 500; i++) {
n = n.add(r);
r = rev(n);
if (n.equals(r)) {
res = new Tuple(false, BigInteger.ZERO);
break;
}
if (cache.containsKey(n)) {
res = cache.get(n);
break;
}
seen.add(n);
}
for (BigInteger bi : seen)
cache.put(bi, res);
return res;
}
public static void main(String[] args) {
List<BigInteger> seeds = new ArrayList<>();
List<BigInteger> related = new ArrayList<>();
List<BigInteger> palin = new ArrayList<>();
for (int i = 1; i <= 10_000; i++) {
BigInteger n = BigInteger.valueOf(i);
Tuple t = lychrel(n);
if (!t.flag)
continue;
if (n.equals(t.bi))
seeds.add(t.bi);
else
related.add(t.bi);
if (n.equals(t.bi))
palin.add(t.bi);
}
System.out.printf("%d Lychrel seeds: %s%n", seeds.size(), seeds);
System.out.printf("%d Lychrel related%n", related.size());
System.out.printf("%d Lychrel palindromes: %s%n", palin.size(), palin);
}
}
| require "set"
require "big"
def add_reverse(num, max_iter=1000)
num = num.to_big_i
nums = [] of BigInt
(1..max_iter).each_with_object(Set.new([num])) do |_, nums|
num += reverse_int(num)
nums << num
return nums if palindrome?(num)
end
end
def palindrome?(num)
num == reverse_int(num)
end
def reverse_int(num)
num.to_s.reverse.to_big_i
end
def split_roots_from_relateds(roots_and_relateds)
roots = roots_and_relateds.dup
i = 1
while i < roots.size
this = roots[i]
if roots[0...i].any?{ |prev| this.intersects?(prev) }
roots.delete_at(i)
else
i += 1
end
end
root = roots.map{ |each_set| each_set.min }
related = roots_and_relateds.map{ |each_set| each_set.min }
related = related.reject{ |n| root.includes?(n) }
return root, related
end
def find_lychrel(maxn, max_reversions)
series = (1..maxn).map{ |n| add_reverse(n, max_reversions*2) }
roots_and_relateds = series.select{ |s| s.size > max_reversions }
split_roots_from_relateds(roots_and_relateds)
end
maxn, reversion_limit = 10000, 500
puts "Calculations using n = 1..
lychrel, l_related = find_lychrel(maxn, reversion_limit)
puts " Number of Lychrel numbers:
puts " Lychrel numbers:
puts " Number of Lychrel related:
pals = (lychrel + l_related).select{|x| palindrome?(x)}.sort
puts " Number of Lychrel palindromes:
puts " Lychrel palindromes:
|
Convert this Java snippet to Ruby and keep its semantics consistent. | import java.math.BigInteger;
import java.util.*;
public class Lychrel {
static Map<BigInteger, Tuple> cache = new HashMap<>();
static class Tuple {
final Boolean flag;
final BigInteger bi;
Tuple(boolean f, BigInteger b) {
flag = f;
bi = b;
}
}
static BigInteger rev(BigInteger bi) {
String s = new StringBuilder(bi.toString()).reverse().toString();
return new BigInteger(s);
}
static Tuple lychrel(BigInteger n) {
Tuple res;
if ((res = cache.get(n)) != null)
return res;
BigInteger r = rev(n);
res = new Tuple(true, n);
List<BigInteger> seen = new ArrayList<>();
for (int i = 0; i < 500; i++) {
n = n.add(r);
r = rev(n);
if (n.equals(r)) {
res = new Tuple(false, BigInteger.ZERO);
break;
}
if (cache.containsKey(n)) {
res = cache.get(n);
break;
}
seen.add(n);
}
for (BigInteger bi : seen)
cache.put(bi, res);
return res;
}
public static void main(String[] args) {
List<BigInteger> seeds = new ArrayList<>();
List<BigInteger> related = new ArrayList<>();
List<BigInteger> palin = new ArrayList<>();
for (int i = 1; i <= 10_000; i++) {
BigInteger n = BigInteger.valueOf(i);
Tuple t = lychrel(n);
if (!t.flag)
continue;
if (n.equals(t.bi))
seeds.add(t.bi);
else
related.add(t.bi);
if (n.equals(t.bi))
palin.add(t.bi);
}
System.out.printf("%d Lychrel seeds: %s%n", seeds.size(), seeds);
System.out.printf("%d Lychrel related%n", related.size());
System.out.printf("%d Lychrel palindromes: %s%n", palin.size(), palin);
}
}
| require "set"
require "big"
def add_reverse(num, max_iter=1000)
num = num.to_big_i
nums = [] of BigInt
(1..max_iter).each_with_object(Set.new([num])) do |_, nums|
num += reverse_int(num)
nums << num
return nums if palindrome?(num)
end
end
def palindrome?(num)
num == reverse_int(num)
end
def reverse_int(num)
num.to_s.reverse.to_big_i
end
def split_roots_from_relateds(roots_and_relateds)
roots = roots_and_relateds.dup
i = 1
while i < roots.size
this = roots[i]
if roots[0...i].any?{ |prev| this.intersects?(prev) }
roots.delete_at(i)
else
i += 1
end
end
root = roots.map{ |each_set| each_set.min }
related = roots_and_relateds.map{ |each_set| each_set.min }
related = related.reject{ |n| root.includes?(n) }
return root, related
end
def find_lychrel(maxn, max_reversions)
series = (1..maxn).map{ |n| add_reverse(n, max_reversions*2) }
roots_and_relateds = series.select{ |s| s.size > max_reversions }
split_roots_from_relateds(roots_and_relateds)
end
maxn, reversion_limit = 10000, 500
puts "Calculations using n = 1..
lychrel, l_related = find_lychrel(maxn, reversion_limit)
puts " Number of Lychrel numbers:
puts " Lychrel numbers:
puts " Number of Lychrel related:
pals = (lychrel + l_related).select{|x| palindrome?(x)}.sort
puts " Number of Lychrel palindromes:
puts " Lychrel palindromes:
|
Translate the given Java code snippet into Ruby without altering its behavior. | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CheckMachinFormula {
private static String FILE_NAME = "MachinFormula.txt";
public static void main(String[] args) {
try {
runPrivate();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void runPrivate() throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {
String inLine = null;
while ( (inLine = reader.readLine()) != null ) {
String[] split = inLine.split("=");
System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim()));
}
}
}
private static String tanLeft(String formula) {
if ( formula.compareTo("pi/4") == 0 ) {
return "1";
}
throw new RuntimeException("ERROR 104: Unknown left side: " + formula);
}
private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)");
private static Fraction tanRight(String formula) {
Matcher matcher = ARCTAN_PATTERN.matcher(formula);
List<Term> terms = new ArrayList<>();
while ( matcher.find() ) {
terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));
}
return evaluateArctan(terms);
}
private static Fraction evaluateArctan(List<Term> terms) {
if ( terms.size() == 1 ) {
Term term = terms.get(0);
return evaluateArctan(term.coefficient, term.fraction);
}
int size = terms.size();
List<Term> left = terms.subList(0, (size+1) / 2);
List<Term> right = terms.subList((size+1) / 2, size);
return arctanFormula(evaluateArctan(left), evaluateArctan(right));
}
private static Fraction evaluateArctan(int coefficient, Fraction fraction) {
if ( coefficient == 1 ) {
return fraction;
}
else if ( coefficient < 0 ) {
return evaluateArctan(-coefficient, fraction).negate();
}
if ( coefficient % 2 == 0 ) {
Fraction f = evaluateArctan(coefficient/2, fraction);
return arctanFormula(f, f);
}
Fraction a = evaluateArctan(coefficient/2, fraction);
Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);
return arctanFormula(a, b);
}
private static Fraction arctanFormula(Fraction f1, Fraction f2) {
return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));
}
private static class Fraction {
public static final Fraction ONE = new Fraction("1", "1");
private BigInteger numerator;
private BigInteger denominator;
public Fraction(String num, String den) {
numerator = new BigInteger(num);
denominator = new BigInteger(den);
}
public Fraction(BigInteger num, BigInteger den) {
numerator = num;
denominator = den;
}
public Fraction negate() {
return new Fraction(numerator.negate(), denominator);
}
public Fraction add(Fraction f) {
BigInteger gcd = denominator.gcd(f.denominator);
BigInteger first = numerator.multiply(f.denominator.divide(gcd));
BigInteger second = f.numerator.multiply(denominator.divide(gcd));
return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));
}
public Fraction subtract(Fraction f) {
return add(f.negate());
}
public Fraction multiply(Fraction f) {
BigInteger num = numerator.multiply(f.numerator);
BigInteger den = denominator.multiply(f.denominator);
BigInteger gcd = num.gcd(den);
return new Fraction(num.divide(gcd), den.divide(gcd));
}
public Fraction divide(Fraction f) {
return multiply(new Fraction(f.denominator, f.numerator));
}
@Override
public String toString() {
if ( denominator.compareTo(BigInteger.ONE) == 0 ) {
return numerator.toString();
}
return numerator + " / " + denominator;
}
}
private static class Term {
private int coefficient;
private Fraction fraction;
public Term(int c, Fraction f) {
coefficient = c;
fraction = f;
}
}
}
| var equationtext = <<'EOT'
pi/4 = arctan(1/2) + arctan(1/3)
pi/4 = 2*arctan(1/3) + arctan(1/7)
pi/4 = 4*arctan(1/5) - arctan(1/239)
pi/4 = 5*arctan(1/7) + 2*arctan(3/79)
pi/4 = 5*arctan(29/278) + 7*arctan(3/79)
pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)
pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)
pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)
pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)
pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)
pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)
pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)
pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)
pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)
pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)
pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)
pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)
EOT
func parse_eqn(equation) {
static eqn_re = %r{
(^ \s* pi/4 \s* = \s* )?
(?:
\s* ( [-+] )? \s*
(?: ( \d+ ) \s* \*)?
\s* arctan\((.*?)\)
)}x
gather {
for lhs,sign,mult,rat in (equation.findall(eqn_re)) {
take([
[+1, -1][sign == '-'] * (mult ? Num(mult) : 1),
Num(rat)
])
}
}
}
func tanEval(coef, f) {
return f if (coef == 1)
return -tanEval(-coef, f) if (coef < 0)
var ca = coef>>1
var cb = (coef - ca)
var (a, b) = (tanEval(ca, f), tanEval(cb, f))
(a + b) / (1 - a*b)
}
func tans(xs) {
var xslen = xs.len
return tanEval(xs[0]...) if (xslen == 1)
var (aa, bb) = xs.part(xslen>>1)
var (a, b) = (tans(aa), tans(bb))
(a + b) / (1 - a*b)
}
var machins = equationtext.lines.map(parse_eqn)
for machin,eqn in (machins ~Z equationtext.lines) {
var ans = tans(machin)
printf("%5s: %s\n", (ans == 1 ? 'OK' : 'ERROR'), eqn)
}
|
Change the following Java code into Ruby without altering its purpose. | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CheckMachinFormula {
private static String FILE_NAME = "MachinFormula.txt";
public static void main(String[] args) {
try {
runPrivate();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void runPrivate() throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {
String inLine = null;
while ( (inLine = reader.readLine()) != null ) {
String[] split = inLine.split("=");
System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim()));
}
}
}
private static String tanLeft(String formula) {
if ( formula.compareTo("pi/4") == 0 ) {
return "1";
}
throw new RuntimeException("ERROR 104: Unknown left side: " + formula);
}
private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)");
private static Fraction tanRight(String formula) {
Matcher matcher = ARCTAN_PATTERN.matcher(formula);
List<Term> terms = new ArrayList<>();
while ( matcher.find() ) {
terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));
}
return evaluateArctan(terms);
}
private static Fraction evaluateArctan(List<Term> terms) {
if ( terms.size() == 1 ) {
Term term = terms.get(0);
return evaluateArctan(term.coefficient, term.fraction);
}
int size = terms.size();
List<Term> left = terms.subList(0, (size+1) / 2);
List<Term> right = terms.subList((size+1) / 2, size);
return arctanFormula(evaluateArctan(left), evaluateArctan(right));
}
private static Fraction evaluateArctan(int coefficient, Fraction fraction) {
if ( coefficient == 1 ) {
return fraction;
}
else if ( coefficient < 0 ) {
return evaluateArctan(-coefficient, fraction).negate();
}
if ( coefficient % 2 == 0 ) {
Fraction f = evaluateArctan(coefficient/2, fraction);
return arctanFormula(f, f);
}
Fraction a = evaluateArctan(coefficient/2, fraction);
Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);
return arctanFormula(a, b);
}
private static Fraction arctanFormula(Fraction f1, Fraction f2) {
return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));
}
private static class Fraction {
public static final Fraction ONE = new Fraction("1", "1");
private BigInteger numerator;
private BigInteger denominator;
public Fraction(String num, String den) {
numerator = new BigInteger(num);
denominator = new BigInteger(den);
}
public Fraction(BigInteger num, BigInteger den) {
numerator = num;
denominator = den;
}
public Fraction negate() {
return new Fraction(numerator.negate(), denominator);
}
public Fraction add(Fraction f) {
BigInteger gcd = denominator.gcd(f.denominator);
BigInteger first = numerator.multiply(f.denominator.divide(gcd));
BigInteger second = f.numerator.multiply(denominator.divide(gcd));
return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));
}
public Fraction subtract(Fraction f) {
return add(f.negate());
}
public Fraction multiply(Fraction f) {
BigInteger num = numerator.multiply(f.numerator);
BigInteger den = denominator.multiply(f.denominator);
BigInteger gcd = num.gcd(den);
return new Fraction(num.divide(gcd), den.divide(gcd));
}
public Fraction divide(Fraction f) {
return multiply(new Fraction(f.denominator, f.numerator));
}
@Override
public String toString() {
if ( denominator.compareTo(BigInteger.ONE) == 0 ) {
return numerator.toString();
}
return numerator + " / " + denominator;
}
}
private static class Term {
private int coefficient;
private Fraction fraction;
public Term(int c, Fraction f) {
coefficient = c;
fraction = f;
}
}
}
| var equationtext = <<'EOT'
pi/4 = arctan(1/2) + arctan(1/3)
pi/4 = 2*arctan(1/3) + arctan(1/7)
pi/4 = 4*arctan(1/5) - arctan(1/239)
pi/4 = 5*arctan(1/7) + 2*arctan(3/79)
pi/4 = 5*arctan(29/278) + 7*arctan(3/79)
pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)
pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)
pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)
pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)
pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)
pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)
pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)
pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)
pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)
pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)
pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)
pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)
EOT
func parse_eqn(equation) {
static eqn_re = %r{
(^ \s* pi/4 \s* = \s* )?
(?:
\s* ( [-+] )? \s*
(?: ( \d+ ) \s* \*)?
\s* arctan\((.*?)\)
)}x
gather {
for lhs,sign,mult,rat in (equation.findall(eqn_re)) {
take([
[+1, -1][sign == '-'] * (mult ? Num(mult) : 1),
Num(rat)
])
}
}
}
func tanEval(coef, f) {
return f if (coef == 1)
return -tanEval(-coef, f) if (coef < 0)
var ca = coef>>1
var cb = (coef - ca)
var (a, b) = (tanEval(ca, f), tanEval(cb, f))
(a + b) / (1 - a*b)
}
func tans(xs) {
var xslen = xs.len
return tanEval(xs[0]...) if (xslen == 1)
var (aa, bb) = xs.part(xslen>>1)
var (a, b) = (tans(aa), tans(bb))
(a + b) / (1 - a*b)
}
var machins = equationtext.lines.map(parse_eqn)
for machin,eqn in (machins ~Z equationtext.lines) {
var ans = tans(machin)
printf("%5s: %s\n", (ans == 1 ? 'OK' : 'ERROR'), eqn)
}
|
Preserve the algorithm and functionality while converting the code from Java to Ruby. | import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Random;
public class IsaacRandom extends Random {
private static final long serialVersionUID = 1L;
private final int[] randResult = new int[256];
private int valuesUsed;
private final int[] mm = new int[256];
private int aa, bb, cc;
public IsaacRandom() {
super(0);
init(null);
}
public IsaacRandom(int[] seed) {
super(0);
setSeed(seed);
}
public IsaacRandom(String seed) {
super(0);
setSeed(seed);
}
private void generateMoreResults() {
cc++;
bb += cc;
for (int i=0; i<256; i++) {
int x = mm[i];
switch (i&3) {
case 0:
aa = aa^(aa<<13);
break;
case 1:
aa = aa^(aa>>>6);
break;
case 2:
aa = aa^(aa<<2);
break;
case 3:
aa = aa^(aa>>>16);
break;
}
aa = mm[i^128] + aa;
int y = mm[i] = mm[(x>>>2) & 0xFF] + aa + bb;
randResult[i] = bb = mm[(y>>>10) & 0xFF] + x;
}
valuesUsed = 0;
}
private static void mix(int[] s) {
s[0]^=s[1]<<11; s[3]+=s[0]; s[1]+=s[2];
s[1]^=s[2]>>>2; s[4]+=s[1]; s[2]+=s[3];
s[2]^=s[3]<<8; s[5]+=s[2]; s[3]+=s[4];
s[3]^=s[4]>>>16; s[6]+=s[3]; s[4]+=s[5];
s[4]^=s[5]<<10; s[7]+=s[4]; s[5]+=s[6];
s[5]^=s[6]>>>4; s[0]+=s[5]; s[6]+=s[7];
s[6]^=s[7]<<8; s[1]+=s[6]; s[7]+=s[0];
s[7]^=s[0]>>>9; s[2]+=s[7]; s[0]+=s[1];
}
private void init(int[] seed) {
if (seed != null && seed.length != 256) {
seed = Arrays.copyOf(seed, 256);
}
aa = bb = cc = 0;
int[] initState = new int[8];
Arrays.fill(initState, 0x9e3779b9);
for (int i=0; i<4; i++) {
mix(initState);
}
for (int i=0; i<256; i+=8) {
if (seed != null) {
for (int j=0; j<8; j++) {
initState[j] += seed[i+j];
}
}
mix(initState);
for (int j=0; j<8; j++) {
mm[i+j] = initState[j];
}
}
if (seed != null) {
for (int i=0; i<256; i+=8) {
for (int j=0; j<8; j++) {
initState[j] += mm[i+j];
}
mix(initState);
for (int j=0; j<8; j++) {
mm[i+j] = initState[j];
}
}
}
valuesUsed = 256;
}
@Override
protected int next(int bits) {
if (valuesUsed == 256) {
generateMoreResults();
assert(valuesUsed == 0);
}
int value = randResult[valuesUsed];
valuesUsed++;
return value >>> (32-bits);
}
@Override
public synchronized void setSeed(long seed) {
super.setSeed(0);
if (mm == null) {
return;
}
int[] arraySeed = new int[256];
arraySeed[0] = (int) (seed & 0xFFFFFFFF);
arraySeed[1] = (int) (seed >>> 32);
init(arraySeed);
}
public synchronized void setSeed(int[] seed) {
super.setSeed(0);
init(seed);
}
public synchronized void setSeed(String seed) {
super.setSeed(0);
char[] charSeed = seed.toCharArray();
int[] intSeed = new int[charSeed.length];
for (int i=0; i<charSeed.length; i++) {
intSeed[i] = charSeed[i];
}
init(intSeed);
}
public int randomChar() {
long unsignedNext = nextInt() & 0xFFFFFFFFL;
return (int) (unsignedNext % 95 + 32);
}
public enum CipherMode { ENCIPHER, DECIPHER, NONE };
public byte[] vernamCipher(byte[] input) {
byte[] result = new byte[input.length];
for (int i=0; i<input.length; i++) {
result[i] = (byte) (randomChar() ^ input[i]);
}
return result;
}
private static byte caesarShift(CipherMode mode, byte ch, int shift, byte modulo, byte start) {
if (mode == CipherMode.DECIPHER) {
shift = -shift;
}
int n = (ch-start) + shift;
n %= modulo;
if (n<0) {
n += modulo;
}
return (byte) (start + n);
}
public byte[] caesarCipher(CipherMode mode, byte[] input, byte modulo, byte start) {
byte[] result = new byte[input.length];
for (int i=0; i<input.length; i++) {
result[i] = caesarShift(mode, input[i], randomChar(), modulo, start);
}
return result;
}
private static String toHexString(byte[] input) {
StringBuilder sb = new StringBuilder(input.length*2);
for (byte b : input) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
public static void main(String[] args) {
final byte MOD = 95;
final byte START = 32;
String secret = "a Top Secret secret";
String key = "this is my secret key";
IsaacRandom random = new IsaacRandom(key);
byte[] vernamResult;
byte[] caesarResult;
String vernamDecrypted;
String caesarDecrypted;
try {
vernamResult = random.vernamCipher(secret.getBytes("ASCII"));
caesarResult = random.caesarCipher(CipherMode.ENCIPHER, secret.getBytes("ASCII"), MOD, START);
random.setSeed(key);
vernamDecrypted = new String(random.vernamCipher(vernamResult), "ASCII");
caesarDecrypted = new String(random.caesarCipher(CipherMode.DECIPHER, caesarResult, MOD, START), "ASCII");
} catch (UnsupportedEncodingException e) {
throw new InternalError("JVM isn't conforming - ASCII encoding isn't available");
}
System.out.printf("Message: %s\n", secret);
System.out.printf("Key : %s\n", key);
System.out.printf("XOR : %s\n", toHexString(vernamResult));
System.out.printf("XOR dcr: %s\n", vernamDecrypted);
System.out.printf("MOD : %s\n", toHexString(caesarResult));
System.out.printf("MOD dcr: %s\n", caesarDecrypted);
}
}
| require('Math::Random::ISAAC')
func xor_isaac(key, msg) {
var rng = %O<Math::Random::ISAAC>.new(unpack('C*', key))
msg.chars»ord()» \
-> »^« 256.of{ rng.irand % 95 + 32 }.last(msg.len).flip \
-> «%« '%02X' -> join
}
var msg = 'a Top Secret secret'
var key = 'this is my secret key'
var enc = xor_isaac(key, msg)
var dec = xor_isaac(key, pack('H*', enc))
say "Message:
say "Key :
say "XOR :
say "XOR dcr:
|
Convert the following code from Java to Ruby, ensuring the logic remains intact. | import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Random;
public class IsaacRandom extends Random {
private static final long serialVersionUID = 1L;
private final int[] randResult = new int[256];
private int valuesUsed;
private final int[] mm = new int[256];
private int aa, bb, cc;
public IsaacRandom() {
super(0);
init(null);
}
public IsaacRandom(int[] seed) {
super(0);
setSeed(seed);
}
public IsaacRandom(String seed) {
super(0);
setSeed(seed);
}
private void generateMoreResults() {
cc++;
bb += cc;
for (int i=0; i<256; i++) {
int x = mm[i];
switch (i&3) {
case 0:
aa = aa^(aa<<13);
break;
case 1:
aa = aa^(aa>>>6);
break;
case 2:
aa = aa^(aa<<2);
break;
case 3:
aa = aa^(aa>>>16);
break;
}
aa = mm[i^128] + aa;
int y = mm[i] = mm[(x>>>2) & 0xFF] + aa + bb;
randResult[i] = bb = mm[(y>>>10) & 0xFF] + x;
}
valuesUsed = 0;
}
private static void mix(int[] s) {
s[0]^=s[1]<<11; s[3]+=s[0]; s[1]+=s[2];
s[1]^=s[2]>>>2; s[4]+=s[1]; s[2]+=s[3];
s[2]^=s[3]<<8; s[5]+=s[2]; s[3]+=s[4];
s[3]^=s[4]>>>16; s[6]+=s[3]; s[4]+=s[5];
s[4]^=s[5]<<10; s[7]+=s[4]; s[5]+=s[6];
s[5]^=s[6]>>>4; s[0]+=s[5]; s[6]+=s[7];
s[6]^=s[7]<<8; s[1]+=s[6]; s[7]+=s[0];
s[7]^=s[0]>>>9; s[2]+=s[7]; s[0]+=s[1];
}
private void init(int[] seed) {
if (seed != null && seed.length != 256) {
seed = Arrays.copyOf(seed, 256);
}
aa = bb = cc = 0;
int[] initState = new int[8];
Arrays.fill(initState, 0x9e3779b9);
for (int i=0; i<4; i++) {
mix(initState);
}
for (int i=0; i<256; i+=8) {
if (seed != null) {
for (int j=0; j<8; j++) {
initState[j] += seed[i+j];
}
}
mix(initState);
for (int j=0; j<8; j++) {
mm[i+j] = initState[j];
}
}
if (seed != null) {
for (int i=0; i<256; i+=8) {
for (int j=0; j<8; j++) {
initState[j] += mm[i+j];
}
mix(initState);
for (int j=0; j<8; j++) {
mm[i+j] = initState[j];
}
}
}
valuesUsed = 256;
}
@Override
protected int next(int bits) {
if (valuesUsed == 256) {
generateMoreResults();
assert(valuesUsed == 0);
}
int value = randResult[valuesUsed];
valuesUsed++;
return value >>> (32-bits);
}
@Override
public synchronized void setSeed(long seed) {
super.setSeed(0);
if (mm == null) {
return;
}
int[] arraySeed = new int[256];
arraySeed[0] = (int) (seed & 0xFFFFFFFF);
arraySeed[1] = (int) (seed >>> 32);
init(arraySeed);
}
public synchronized void setSeed(int[] seed) {
super.setSeed(0);
init(seed);
}
public synchronized void setSeed(String seed) {
super.setSeed(0);
char[] charSeed = seed.toCharArray();
int[] intSeed = new int[charSeed.length];
for (int i=0; i<charSeed.length; i++) {
intSeed[i] = charSeed[i];
}
init(intSeed);
}
public int randomChar() {
long unsignedNext = nextInt() & 0xFFFFFFFFL;
return (int) (unsignedNext % 95 + 32);
}
public enum CipherMode { ENCIPHER, DECIPHER, NONE };
public byte[] vernamCipher(byte[] input) {
byte[] result = new byte[input.length];
for (int i=0; i<input.length; i++) {
result[i] = (byte) (randomChar() ^ input[i]);
}
return result;
}
private static byte caesarShift(CipherMode mode, byte ch, int shift, byte modulo, byte start) {
if (mode == CipherMode.DECIPHER) {
shift = -shift;
}
int n = (ch-start) + shift;
n %= modulo;
if (n<0) {
n += modulo;
}
return (byte) (start + n);
}
public byte[] caesarCipher(CipherMode mode, byte[] input, byte modulo, byte start) {
byte[] result = new byte[input.length];
for (int i=0; i<input.length; i++) {
result[i] = caesarShift(mode, input[i], randomChar(), modulo, start);
}
return result;
}
private static String toHexString(byte[] input) {
StringBuilder sb = new StringBuilder(input.length*2);
for (byte b : input) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
public static void main(String[] args) {
final byte MOD = 95;
final byte START = 32;
String secret = "a Top Secret secret";
String key = "this is my secret key";
IsaacRandom random = new IsaacRandom(key);
byte[] vernamResult;
byte[] caesarResult;
String vernamDecrypted;
String caesarDecrypted;
try {
vernamResult = random.vernamCipher(secret.getBytes("ASCII"));
caesarResult = random.caesarCipher(CipherMode.ENCIPHER, secret.getBytes("ASCII"), MOD, START);
random.setSeed(key);
vernamDecrypted = new String(random.vernamCipher(vernamResult), "ASCII");
caesarDecrypted = new String(random.caesarCipher(CipherMode.DECIPHER, caesarResult, MOD, START), "ASCII");
} catch (UnsupportedEncodingException e) {
throw new InternalError("JVM isn't conforming - ASCII encoding isn't available");
}
System.out.printf("Message: %s\n", secret);
System.out.printf("Key : %s\n", key);
System.out.printf("XOR : %s\n", toHexString(vernamResult));
System.out.printf("XOR dcr: %s\n", vernamDecrypted);
System.out.printf("MOD : %s\n", toHexString(caesarResult));
System.out.printf("MOD dcr: %s\n", caesarDecrypted);
}
}
| require('Math::Random::ISAAC')
func xor_isaac(key, msg) {
var rng = %O<Math::Random::ISAAC>.new(unpack('C*', key))
msg.chars»ord()» \
-> »^« 256.of{ rng.irand % 95 + 32 }.last(msg.len).flip \
-> «%« '%02X' -> join
}
var msg = 'a Top Secret secret'
var key = 'this is my secret key'
var enc = xor_isaac(key, msg)
var dec = xor_isaac(key, pack('H*', enc))
say "Message:
say "Key :
say "XOR :
say "XOR dcr:
|
Write the same algorithm in Ruby as shown in this Java implementation. | import java.math.BigInteger;
import java.util.*;
class RankPermutation
{
public static BigInteger getRank(int[] permutation)
{
int n = permutation.length;
BitSet usedDigits = new BitSet();
BigInteger rank = BigInteger.ZERO;
for (int i = 0; i < n; i++)
{
rank = rank.multiply(BigInteger.valueOf(n - i));
int digit = 0;
int v = -1;
while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])
digit++;
usedDigits.set(v);
rank = rank.add(BigInteger.valueOf(digit));
}
return rank;
}
public static int[] getPermutation(int n, BigInteger rank)
{
int[] digits = new int[n];
for (int digit = 2; digit <= n; digit++)
{
BigInteger divisor = BigInteger.valueOf(digit);
digits[n - digit] = rank.mod(divisor).intValue();
if (digit < n)
rank = rank.divide(divisor);
}
BitSet usedDigits = new BitSet();
int[] permutation = new int[n];
for (int i = 0; i < n; i++)
{
int v = usedDigits.nextClearBit(0);
for (int j = 0; j < digits[i]; j++)
v = usedDigits.nextClearBit(v + 1);
permutation[i] = v;
usedDigits.set(v);
}
return permutation;
}
public static void main(String[] args)
{
for (int i = 0; i < 6; i++)
{
int[] permutation = getPermutation(3, BigInteger.valueOf(i));
System.out.println(String.valueOf(i) + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation));
}
Random rnd = new Random();
for (int n : new int[] { 12, 144 })
{
BigInteger factorial = BigInteger.ONE;
for (int i = 2; i <= n; i++)
factorial = factorial.multiply(BigInteger.valueOf(i));
System.out.println("n = " + n);
for (int i = 0; i < 5; i++)
{
BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);
rank = rank.mod(factorial);
int[] permutation = getPermutation(n, rank);
System.out.println(" " + rank + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation));
}
}
}
}
| class Permutation
include Enumerable
attr_reader :num_elements, :size
def initialize(num_elements)
@num_elements = num_elements
@size = fact(num_elements)
end
def each
return self.to_enum unless block_given?
(0...@size).each{|i| yield unrank(i)}
end
def unrank(r)
pi = (0...num_elements).to_a
(@num_elements-1).downto(1) do |n|
s, r = r.divmod(fact(n))
pi[n], pi[s] = pi[s], pi[n]
end
pi
end
def rank(pi)
pi = pi.dup
pi1 = pi.zip(0...pi.size).sort.map(&:last)
(pi.size-1).downto(0).inject(0) do |memo,i|
pi[i], pi[pi1[i]] = pi[pi1[i]], (s = pi[i])
pi1[s], pi1[i] = pi1[i], pi1[s]
memo += s * fact(i)
end
end
private
def fact(n)
n.zero? ? 1 : n.downto(1).inject(:*)
end
end
|
Generate an equivalent Ruby version of this Java code. | import java.math.BigInteger;
import java.util.*;
class RankPermutation
{
public static BigInteger getRank(int[] permutation)
{
int n = permutation.length;
BitSet usedDigits = new BitSet();
BigInteger rank = BigInteger.ZERO;
for (int i = 0; i < n; i++)
{
rank = rank.multiply(BigInteger.valueOf(n - i));
int digit = 0;
int v = -1;
while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])
digit++;
usedDigits.set(v);
rank = rank.add(BigInteger.valueOf(digit));
}
return rank;
}
public static int[] getPermutation(int n, BigInteger rank)
{
int[] digits = new int[n];
for (int digit = 2; digit <= n; digit++)
{
BigInteger divisor = BigInteger.valueOf(digit);
digits[n - digit] = rank.mod(divisor).intValue();
if (digit < n)
rank = rank.divide(divisor);
}
BitSet usedDigits = new BitSet();
int[] permutation = new int[n];
for (int i = 0; i < n; i++)
{
int v = usedDigits.nextClearBit(0);
for (int j = 0; j < digits[i]; j++)
v = usedDigits.nextClearBit(v + 1);
permutation[i] = v;
usedDigits.set(v);
}
return permutation;
}
public static void main(String[] args)
{
for (int i = 0; i < 6; i++)
{
int[] permutation = getPermutation(3, BigInteger.valueOf(i));
System.out.println(String.valueOf(i) + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation));
}
Random rnd = new Random();
for (int n : new int[] { 12, 144 })
{
BigInteger factorial = BigInteger.ONE;
for (int i = 2; i <= n; i++)
factorial = factorial.multiply(BigInteger.valueOf(i));
System.out.println("n = " + n);
for (int i = 0; i < 5; i++)
{
BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);
rank = rank.mod(factorial);
int[] permutation = getPermutation(n, rank);
System.out.println(" " + rank + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation));
}
}
}
}
| class Permutation
include Enumerable
attr_reader :num_elements, :size
def initialize(num_elements)
@num_elements = num_elements
@size = fact(num_elements)
end
def each
return self.to_enum unless block_given?
(0...@size).each{|i| yield unrank(i)}
end
def unrank(r)
pi = (0...num_elements).to_a
(@num_elements-1).downto(1) do |n|
s, r = r.divmod(fact(n))
pi[n], pi[s] = pi[s], pi[n]
end
pi
end
def rank(pi)
pi = pi.dup
pi1 = pi.zip(0...pi.size).sort.map(&:last)
(pi.size-1).downto(0).inject(0) do |memo,i|
pi[i], pi[pi1[i]] = pi[pi1[i]], (s = pi[i])
pi1[s], pi1[i] = pi1[i], pi1[s]
memo += s * fact(i)
end
end
private
def fact(n)
n.zero? ? 1 : n.downto(1).inject(:*)
end
end
|
Preserve the algorithm and functionality while converting the code from Java to Ruby. | public class FirstPowerOfTwo {
public static void main(String[] args) {
runTest(12, 1);
runTest(12, 2);
runTest(123, 45);
runTest(123, 12345);
runTest(123, 678910);
}
private static void runTest(int l, int n) {
System.out.printf("p(%d, %d) = %,d%n", l, n, p(l, n));
}
public static int p(int l, int n) {
int test = 0;
double log = Math.log(2) / Math.log(10);
int factor = 1;
int loop = l;
while ( loop > 10 ) {
factor *= 10;
loop /= 10;
}
while ( n > 0) {
test++;
int val = (int) (factor * Math.pow(10, test * log % 1));
if ( val == l ) {
n--;
}
}
return test;
}
}
| def p(l, n)
test = 0
logv = Math.log(2.0) / Math.log(10.0)
factor = 1
loopv = l
while loopv > 10 do
factor = factor * 10
loopv = loopv / 10
end
while n > 0 do
test = test + 1
val = (factor * (10.0 ** ((test * logv).modulo(1.0)))).floor
if val == l then
n = n - 1
end
end
return test
end
def runTest(l, n)
print "P(%d, %d) = %d\n" % [l, n, p(l, n)]
end
runTest(12, 1)
runTest(12, 2)
runTest(123, 45)
runTest(123, 12345)
runTest(123, 678910)
|
Transform the following Java implementation into Ruby, maintaining the same output and logic. | public class FirstPowerOfTwo {
public static void main(String[] args) {
runTest(12, 1);
runTest(12, 2);
runTest(123, 45);
runTest(123, 12345);
runTest(123, 678910);
}
private static void runTest(int l, int n) {
System.out.printf("p(%d, %d) = %,d%n", l, n, p(l, n));
}
public static int p(int l, int n) {
int test = 0;
double log = Math.log(2) / Math.log(10);
int factor = 1;
int loop = l;
while ( loop > 10 ) {
factor *= 10;
loop /= 10;
}
while ( n > 0) {
test++;
int val = (int) (factor * Math.pow(10, test * log % 1));
if ( val == l ) {
n--;
}
}
return test;
}
}
| def p(l, n)
test = 0
logv = Math.log(2.0) / Math.log(10.0)
factor = 1
loopv = l
while loopv > 10 do
factor = factor * 10
loopv = loopv / 10
end
while n > 0 do
test = test + 1
val = (factor * (10.0 ** ((test * logv).modulo(1.0)))).floor
if val == l then
n = n - 1
end
end
return test
end
def runTest(l, n)
print "P(%d, %d) = %d\n" % [l, n, p(l, n)]
end
runTest(12, 1)
runTest(12, 2)
runTest(123, 45)
runTest(123, 12345)
runTest(123, 678910)
|
Write the same code in Ruby as shown below in Java. | import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class SterlingNumbersSecondKind {
public static void main(String[] args) {
System.out.println("Stirling numbers of the second kind:");
int max = 12;
System.out.printf("n/k");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%10d", n);
}
System.out.printf("%n");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%-3d", n);
for ( int k = 0 ; k <= n ; k++ ) {
System.out.printf("%10s", sterling2(n, k));
}
System.out.printf("%n");
}
System.out.println("The maximum value of S2(100, k) = ");
BigInteger previous = BigInteger.ZERO;
for ( int k = 1 ; k <= 100 ; k++ ) {
BigInteger current = sterling2(100, k);
if ( current.compareTo(previous) > 0 ) {
previous = current;
}
else {
System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1);
break;
}
}
}
private static Map<String,BigInteger> COMPUTED = new HashMap<>();
private static final BigInteger sterling2(int n, int k) {
String key = n + "," + k;
if ( COMPUTED.containsKey(key) ) {
return COMPUTED.get(key);
}
if ( n == 0 && k == 0 ) {
return BigInteger.valueOf(1);
}
if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {
return BigInteger.ZERO;
}
if ( n == k ) {
return BigInteger.valueOf(1);
}
if ( k > n ) {
return BigInteger.ZERO;
}
BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));
COMPUTED.put(key, result);
return result;
}
}
| @memo = {}
def sterling2(n, k)
key = [n,k]
return @memo[key] if @memo.key?(key)
return 1 if n.zero? and k.zero?
return 0 if n.zero? or k.zero?
return 1 if n == k
return 0 if k > n
res = k * sterling2(n-1, k) + sterling2(n - 1, k-1)
@memo[key] = res
end
r = (0..12)
puts "Sterling2 numbers:"
puts "n/k
r.each do |row|
print "%-4s" % row
puts "
end
puts "\nMaximum value from the sterling2(100, k)";
puts (1..100).map{|a| sterling2(100,a)}.max
|
Convert this Java snippet to Ruby and keep its semantics consistent. | import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class SterlingNumbersSecondKind {
public static void main(String[] args) {
System.out.println("Stirling numbers of the second kind:");
int max = 12;
System.out.printf("n/k");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%10d", n);
}
System.out.printf("%n");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%-3d", n);
for ( int k = 0 ; k <= n ; k++ ) {
System.out.printf("%10s", sterling2(n, k));
}
System.out.printf("%n");
}
System.out.println("The maximum value of S2(100, k) = ");
BigInteger previous = BigInteger.ZERO;
for ( int k = 1 ; k <= 100 ; k++ ) {
BigInteger current = sterling2(100, k);
if ( current.compareTo(previous) > 0 ) {
previous = current;
}
else {
System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1);
break;
}
}
}
private static Map<String,BigInteger> COMPUTED = new HashMap<>();
private static final BigInteger sterling2(int n, int k) {
String key = n + "," + k;
if ( COMPUTED.containsKey(key) ) {
return COMPUTED.get(key);
}
if ( n == 0 && k == 0 ) {
return BigInteger.valueOf(1);
}
if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {
return BigInteger.ZERO;
}
if ( n == k ) {
return BigInteger.valueOf(1);
}
if ( k > n ) {
return BigInteger.ZERO;
}
BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));
COMPUTED.put(key, result);
return result;
}
}
| @memo = {}
def sterling2(n, k)
key = [n,k]
return @memo[key] if @memo.key?(key)
return 1 if n.zero? and k.zero?
return 0 if n.zero? or k.zero?
return 1 if n == k
return 0 if k > n
res = k * sterling2(n-1, k) + sterling2(n - 1, k-1)
@memo[key] = res
end
r = (0..12)
puts "Sterling2 numbers:"
puts "n/k
r.each do |row|
print "%-4s" % row
puts "
end
puts "\nMaximum value from the sterling2(100, k)";
puts (1..100).map{|a| sterling2(100,a)}.max
|
Convert this Java block to Ruby, preserving its control flow and logic. | import java.math.BigInteger;
import java.util.function.BiFunction;
import java.util.function.Function;
public class CipollasAlgorithm {
private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));
private static final BigInteger BIG_TWO = BigInteger.valueOf(2);
private static class Point {
BigInteger x;
BigInteger y;
Point(BigInteger x, BigInteger y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("(%s, %s)", this.x, this.y);
}
}
private static class Triple {
BigInteger x;
BigInteger y;
boolean b;
Triple(BigInteger x, BigInteger y, boolean b) {
this.x = x;
this.y = y;
this.b = b;
}
@Override
public String toString() {
return String.format("(%s, %s, %s)", this.x, this.y, this.b);
}
}
private static Triple c(String ns, String ps) {
BigInteger n = new BigInteger(ns);
BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;
Function<BigInteger, BigInteger> ls = (BigInteger a)
-> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);
if (!ls.apply(n).equals(BigInteger.ONE)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
BigInteger a = BigInteger.ZERO;
BigInteger omega2;
while (true) {
omega2 = a.multiply(a).add(p).subtract(n).mod(p);
if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {
break;
}
a = a.add(BigInteger.ONE);
}
BigInteger finalOmega = omega2;
BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(
aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),
aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)
);
Point r = new Point(BigInteger.ONE, BigInteger.ZERO);
Point s = new Point(a, BigInteger.ONE);
BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);
while (nn.compareTo(BigInteger.ZERO) > 0) {
if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {
r = mul.apply(r, s);
}
s = mul.apply(s, s);
nn = nn.shiftRight(1);
}
if (!r.y.equals(BigInteger.ZERO)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
if (!r.x.multiply(r.x).mod(p).equals(n)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
return new Triple(r.x, p.subtract(r.x), true);
}
public static void main(String[] args) {
System.out.println(c("10", "13"));
System.out.println(c("56", "101"));
System.out.println(c("8218", "10007"));
System.out.println(c("8219", "10007"));
System.out.println(c("331575", "1000003"));
System.out.println(c("665165880", "1000000007"));
System.out.println(c("881398088036", "1000000000039"));
System.out.println(c("34035243914635549601583369544560650254325084643201", ""));
}
}
| func cipolla(n, p) {
legendre(n, p) == 1 || return nil
var (a = 0, ω2 = 0)
loop {
ω2 = ((a*a - n) % p)
if (legendre(ω2, p) == -1) {
break
}
++a
}
struct point { x, y }
func mul(a, b) {
point((a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p)
}
var r = point(1, 0)
var s = point(a, 1)
for (var n = ((p+1) >> 1); n > 0; n >>= 1) {
r = mul(r, s) if n.is_odd
s = mul(s, s)
}
r.y == 0 ? r.x : nil
}
var tests = [
[10, 13],
[56, 101],
[8218, 10007],
[8219, 10007],
[331575, 1000003],
[665165880, 1000000007],
[881398088036 1000000000039],
[34035243914635549601583369544560650254325084643201, 10**50 + 151],
]
for n,p in tests {
var r = cipolla(n, p)
if (defined(r)) {
say "Roots of
} else {
say "No solution for (
}
}
|
Write the same code in Ruby as shown below in Java. | import java.math.BigInteger;
import java.util.function.BiFunction;
import java.util.function.Function;
public class CipollasAlgorithm {
private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));
private static final BigInteger BIG_TWO = BigInteger.valueOf(2);
private static class Point {
BigInteger x;
BigInteger y;
Point(BigInteger x, BigInteger y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("(%s, %s)", this.x, this.y);
}
}
private static class Triple {
BigInteger x;
BigInteger y;
boolean b;
Triple(BigInteger x, BigInteger y, boolean b) {
this.x = x;
this.y = y;
this.b = b;
}
@Override
public String toString() {
return String.format("(%s, %s, %s)", this.x, this.y, this.b);
}
}
private static Triple c(String ns, String ps) {
BigInteger n = new BigInteger(ns);
BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;
Function<BigInteger, BigInteger> ls = (BigInteger a)
-> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);
if (!ls.apply(n).equals(BigInteger.ONE)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
BigInteger a = BigInteger.ZERO;
BigInteger omega2;
while (true) {
omega2 = a.multiply(a).add(p).subtract(n).mod(p);
if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {
break;
}
a = a.add(BigInteger.ONE);
}
BigInteger finalOmega = omega2;
BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(
aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p),
aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p)
);
Point r = new Point(BigInteger.ONE, BigInteger.ZERO);
Point s = new Point(a, BigInteger.ONE);
BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);
while (nn.compareTo(BigInteger.ZERO) > 0) {
if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {
r = mul.apply(r, s);
}
s = mul.apply(s, s);
nn = nn.shiftRight(1);
}
if (!r.y.equals(BigInteger.ZERO)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
if (!r.x.multiply(r.x).mod(p).equals(n)) {
return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
}
return new Triple(r.x, p.subtract(r.x), true);
}
public static void main(String[] args) {
System.out.println(c("10", "13"));
System.out.println(c("56", "101"));
System.out.println(c("8218", "10007"));
System.out.println(c("8219", "10007"));
System.out.println(c("331575", "1000003"));
System.out.println(c("665165880", "1000000007"));
System.out.println(c("881398088036", "1000000000039"));
System.out.println(c("34035243914635549601583369544560650254325084643201", ""));
}
}
| func cipolla(n, p) {
legendre(n, p) == 1 || return nil
var (a = 0, ω2 = 0)
loop {
ω2 = ((a*a - n) % p)
if (legendre(ω2, p) == -1) {
break
}
++a
}
struct point { x, y }
func mul(a, b) {
point((a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p)
}
var r = point(1, 0)
var s = point(a, 1)
for (var n = ((p+1) >> 1); n > 0; n >>= 1) {
r = mul(r, s) if n.is_odd
s = mul(s, s)
}
r.y == 0 ? r.x : nil
}
var tests = [
[10, 13],
[56, 101],
[8218, 10007],
[8219, 10007],
[331575, 1000003],
[665165880, 1000000007],
[881398088036 1000000000039],
[34035243914635549601583369544560650254325084643201, 10**50 + 151],
]
for n,p in tests {
var r = cipolla(n, p)
if (defined(r)) {
say "Roots of
} else {
say "No solution for (
}
}
|
Port the following code from Java to Ruby with equivalent syntax and logic. | import java.math.BigInteger;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
public class PierpontPrimes {
public static void main(String[] args) {
NumberFormat nf = NumberFormat.getNumberInstance();
display("First 50 Pierpont primes of the first kind:", pierpontPrimes(50, true));
display("First 50 Pierpont primes of the second kind:", pierpontPrimes(50, false));
System.out.printf("250th Pierpont prime of the first kind: %s%n%n", nf.format(pierpontPrimes(250, true).get(249)));
System.out.printf("250th Pierpont prime of the second kind: %s%n%n", nf.format(pierpontPrimes(250, false).get(249)));
}
private static void display(String message, List<BigInteger> primes) {
NumberFormat nf = NumberFormat.getNumberInstance();
System.out.printf("%s%n", message);
for ( int i = 1 ; i <= primes.size() ; i++ ) {
System.out.printf("%10s ", nf.format(primes.get(i-1)));
if ( i % 10 == 0 ) {
System.out.printf("%n");
}
}
System.out.printf("%n");
}
public static List<BigInteger> pierpontPrimes(int n, boolean first) {
List<BigInteger> primes = new ArrayList<BigInteger>();
if ( first ) {
primes.add(BigInteger.valueOf(2));
n -= 1;
}
BigInteger two = BigInteger.valueOf(2);
BigInteger twoTest = two;
BigInteger three = BigInteger.valueOf(3);
BigInteger threeTest = three;
int twoIndex = 0, threeIndex = 0;
List<BigInteger> twoSmooth = new ArrayList<BigInteger>();
BigInteger one = BigInteger.ONE;
BigInteger mOne = BigInteger.valueOf(-1);
int count = 0;
while ( count < n ) {
BigInteger min = twoTest.min(threeTest);
twoSmooth.add(min);
if ( min.compareTo(twoTest) == 0 ) {
twoTest = two.multiply(twoSmooth.get(twoIndex));
twoIndex++;
}
if ( min.compareTo(threeTest) == 0 ) {
threeTest = three.multiply(twoSmooth.get(threeIndex));
threeIndex++;
}
BigInteger test = min.add(first ? one : mOne);
if ( test.isProbablePrime(10) ) {
primes.add(test);
count++;
}
}
return primes;
}
}
| require 'gmp'
def smooth_generator(ar)
return to_enum(__method__, ar) unless block_given?
next_smooth = 1
queues = ar.map{|num| [num, []] }
loop do
yield next_smooth
queues.each {|m, queue| queue << next_smooth * m}
next_smooth = queues.collect{|m, queue| queue.first}.min
queues.each{|m, queue| queue.shift if queue.first == next_smooth }
end
end
def pierpont(num = 1)
return to_enum(__method__, num) unless block_given?
smooth_generator([2,3]).each{|smooth| yield smooth+num if GMP::Z(smooth + num).probab_prime? > 0}
end
def puts_cols(ar, n=10)
ar.each_slice(n).map{|slice|puts slice.map{|n| n.to_s.rjust(10)}.join }
end
n, m = 50, 250
puts "First
puts_cols(pierpont.take(n))
puts "
puts "First
puts_cols(pierpont(-1).take(n))
puts "
|
Write a version of this Java function in Ruby with identical behavior. | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class NSmoothNumbers {
public static void main(String[] args) {
System.out.printf("show the first 25 n-smooth numbers for n = 2 through n = 29%n");
int max = 25;
List<BigInteger> primes = new ArrayList<>();
for ( int n = 2 ; n <= 29 ; n++ ) {
if ( isPrime(n) ) {
primes.add(BigInteger.valueOf(n));
System.out.printf("The first %d %d-smooth numbers:%n", max, n);
BigInteger[] humble = nSmooth(max, primes.toArray(new BigInteger[0]));
for ( int i = 0 ; i < max ; i++ ) {
System.out.printf("%s ", humble[i]);
}
System.out.printf("%n%n");
}
}
System.out.printf("show three numbers starting with 3,000 for n-smooth numbers for n = 3 through n = 29%n");
int count = 3;
max = 3000 + count - 1;
primes = new ArrayList<>();
primes.add(BigInteger.valueOf(2));
for ( int n = 3 ; n <= 29 ; n++ ) {
if ( isPrime(n) ) {
primes.add(BigInteger.valueOf(n));
System.out.printf("The %d through %d %d-smooth numbers:%n", max-count+1, max, n);
BigInteger[] nSmooth = nSmooth(max, primes.toArray(new BigInteger[0]));
for ( int i = max-count ; i < max ; i++ ) {
System.out.printf("%s ", nSmooth[i]);
}
System.out.printf("%n%n");
}
}
System.out.printf("Show twenty numbers starting with 30,000 n-smooth numbers for n=503 through n=521%n");
count = 20;
max = 30000 + count - 1;
primes = new ArrayList<>();
for ( int n = 2 ; n <= 521 ; n++ ) {
if ( isPrime(n) ) {
primes.add(BigInteger.valueOf(n));
if ( n >= 503 && n <= 521 ) {
System.out.printf("The %d through %d %d-smooth numbers:%n", max-count+1, max, n);
BigInteger[] nSmooth = nSmooth(max, primes.toArray(new BigInteger[0]));
for ( int i = max-count ; i < max ; i++ ) {
System.out.printf("%s ", nSmooth[i]);
}
System.out.printf("%n%n");
}
}
}
}
private static final boolean isPrime(long test) {
if ( test == 2 ) {
return true;
}
if ( test % 2 == 0 ) return false;
for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {
if ( test % i == 0 ) {
return false;
}
}
return true;
}
private static BigInteger[] nSmooth(int n, BigInteger[] primes) {
int size = primes.length;
BigInteger[] test = new BigInteger[size];
for ( int i = 0 ; i < size ; i++ ) {
test[i] = primes[i];
}
BigInteger[] results = new BigInteger[n];
results[0] = BigInteger.ONE;
int[] indexes = new int[size];
for ( int i = 0 ; i < size ; i++ ) {
indexes[i] = 0;
}
for ( int index = 1 ; index < n ; index++ ) {
BigInteger min = test[0];
for ( int i = 1 ; i < size ; i++ ) {
min = min.min(test[i]);
}
results[index] = min;
for ( int i = 0 ; i < size ; i++ ) {
if ( results[index].compareTo(test[i]) == 0 ) {
indexes[i] = indexes[i] + 1;
test[i] = primes[i].multiply(results[indexes[i]]);
}
}
}
return results;
}
}
| require "big"
def prime?(n)
return false unless (n | 1 == 3 if n < 5) || (n % 6) | 4 == 5
sqrt_n = Math.isqrt(n)
pc = typeof(n).new(5)
while pc <= sqrt_n
return false if n % pc == 0 || n % (pc + 2) == 0
pc += 6
end
true
end
def gen_primes(a, b)
(a..b).select { |pc| pc if prime? pc }
end
def nsmooth(n, limit)
raise "Exception(n or limit)" if n < 2 || n > 521 || limit < 1
raise "Exception(must be a prime number: n)" unless prime? n
primes = gen_primes(2, n)
ns = [0.to_big_i] * limit
ns[0] = 1.to_big_i
nextp = primes[0..primes.index(n)].map { |prm| prm.to_big_i }
indices = [0] * nextp.size
(1...limit).each do |m|
ns[m] = nextp.min
(0...indices.size).each do |i|
if ns[m] == nextp[i]
indices[i] += 1
nextp[i] = primes[i] * ns[indices[i]]
end
end
end
ns
end
gen_primes(2, 29).each do |prime|
print "The first 25
print nsmooth(prime, 25)
puts
end
puts
gen_primes(3, 29).each do |prime|
print "The 3000 to 3202
print nsmooth(prime, 3002)[2999..]
puts
end
puts
gen_primes(503, 521).each do |prime|
print "The 30,000 to 30,019
print nsmooth(prime, 30019)[29999..]
puts
end
|
Maintain the same structure and functionality when rewriting this code in Ruby. | import java.util.Arrays;
import java.util.stream.IntStream;
public class PartitionInteger {
private static final int[] primes = IntStream.concat(IntStream.of(2), IntStream.iterate(3, n -> n + 2))
.filter(PartitionInteger::isPrime)
.limit(50_000)
.toArray();
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;
}
private static boolean findCombo(int k, int x, int m, int n, int[] combo) {
boolean foundCombo = false;
if (k >= m) {
if (Arrays.stream(combo).map(i -> primes[i]).sum() == x) {
String s = m > 1 ? "s" : "";
System.out.printf("Partitioned %5d with %2d prime%s: ", x, m, s);
for (int i = 0; i < m; ++i) {
System.out.print(primes[combo[i]]);
if (i < m - 1) System.out.print('+');
else System.out.println();
}
foundCombo = true;
}
} else {
for (int j = 0; j < n; ++j) {
if (k == 0 || j > combo[k - 1]) {
combo[k] = j;
if (!foundCombo) {
foundCombo = findCombo(k + 1, x, m, n, combo);
}
}
}
}
return foundCombo;
}
private static void partition(int x, int m) {
if (x < 2 || m < 1 || m >= x) {
throw new IllegalArgumentException();
}
int[] filteredPrimes = Arrays.stream(primes).filter(it -> it <= x).toArray();
int n = filteredPrimes.length;
if (n < m) throw new IllegalArgumentException("Not enough primes");
int[] combo = new int[m];
boolean foundCombo = findCombo(0, x, m, n, combo);
if (!foundCombo) {
String s = m > 1 ? "s" : " ";
System.out.printf("Partitioned %5d with %2d prime%s: (not possible)\n", x, m, s);
}
}
public static void main(String[] args) {
partition(99809, 1);
partition(18, 2);
partition(19, 3);
partition(20, 4);
partition(2017, 24);
partition(22699, 1);
partition(22699, 2);
partition(22699, 3);
partition(22699, 4);
partition(40355, 3);
}
}
| require "prime"
def prime_partition(x, n)
Prime.each(x).to_a.combination(n).detect{|primes| primes.sum == x}
end
TESTCASES = [[99809, 1], [18, 2], [19, 3], [20, 4], [2017, 24],
[22699, 1], [22699, 2], [22699, 3], [22699, 4], [40355, 3]]
TESTCASES.each do |prime, num|
res = prime_partition(prime, num)
str = res.nil? ? "no solution" : res.join(" + ")
puts "Partitioned
end
|
Please provide an equivalent version of this Java code in Ruby. | import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class SterlingNumbersFirstKind {
public static void main(String[] args) {
System.out.println("Unsigned Stirling numbers of the first kind:");
int max = 12;
System.out.printf("n/k");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%10d", n);
}
System.out.printf("%n");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%-3d", n);
for ( int k = 0 ; k <= n ; k++ ) {
System.out.printf("%10s", sterling1(n, k));
}
System.out.printf("%n");
}
System.out.println("The maximum value of S1(100, k) = ");
BigInteger previous = BigInteger.ZERO;
for ( int k = 1 ; k <= 100 ; k++ ) {
BigInteger current = sterling1(100, k);
if ( current.compareTo(previous) > 0 ) {
previous = current;
}
else {
System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1);
break;
}
}
}
private static Map<String,BigInteger> COMPUTED = new HashMap<>();
private static final BigInteger sterling1(int n, int k) {
String key = n + "," + k;
if ( COMPUTED.containsKey(key) ) {
return COMPUTED.get(key);
}
if ( n == 0 && k == 0 ) {
return BigInteger.valueOf(1);
}
if ( n > 0 && k == 0 ) {
return BigInteger.ZERO;
}
if ( k > n ) {
return BigInteger.ZERO;
}
BigInteger result = sterling1(n-1, k-1).add(BigInteger.valueOf(n-1).multiply(sterling1(n-1, k)));
COMPUTED.put(key, result);
return result;
}
}
| $cache = {}
def sterling1(n, k)
if n == 0 and k == 0 then
return 1
end
if n > 0 and k == 0 then
return 0
end
if k > n then
return 0
end
key = [n, k]
if $cache[key] then
return $cache[key]
end
value = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k)
$cache[key] = value
return value
end
MAX = 12
def main
print "Unsigned Stirling numbers of the first kind:\n"
print "n/k"
for n in 0 .. MAX
print "%10d" % [n]
end
print "\n"
for n in 0 .. MAX
print "%-3d" % [n]
for k in 0 .. n
print "%10d" % [sterling1(n, k)]
end
print "\n"
end
print "The maximum value of S1(100, k) =\n"
previous = 0
for k in 1 .. 100
current = sterling1(100, k)
if previous < current then
previous = current
else
print previous, "\n"
print "(%d digits, k = %d)\n" % [previous.to_s.length, k - 1]
break
end
end
end
main()
|
Produce a functionally identical Ruby code for the snippet given in Java. | import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class SterlingNumbersFirstKind {
public static void main(String[] args) {
System.out.println("Unsigned Stirling numbers of the first kind:");
int max = 12;
System.out.printf("n/k");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%10d", n);
}
System.out.printf("%n");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%-3d", n);
for ( int k = 0 ; k <= n ; k++ ) {
System.out.printf("%10s", sterling1(n, k));
}
System.out.printf("%n");
}
System.out.println("The maximum value of S1(100, k) = ");
BigInteger previous = BigInteger.ZERO;
for ( int k = 1 ; k <= 100 ; k++ ) {
BigInteger current = sterling1(100, k);
if ( current.compareTo(previous) > 0 ) {
previous = current;
}
else {
System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1);
break;
}
}
}
private static Map<String,BigInteger> COMPUTED = new HashMap<>();
private static final BigInteger sterling1(int n, int k) {
String key = n + "," + k;
if ( COMPUTED.containsKey(key) ) {
return COMPUTED.get(key);
}
if ( n == 0 && k == 0 ) {
return BigInteger.valueOf(1);
}
if ( n > 0 && k == 0 ) {
return BigInteger.ZERO;
}
if ( k > n ) {
return BigInteger.ZERO;
}
BigInteger result = sterling1(n-1, k-1).add(BigInteger.valueOf(n-1).multiply(sterling1(n-1, k)));
COMPUTED.put(key, result);
return result;
}
}
| $cache = {}
def sterling1(n, k)
if n == 0 and k == 0 then
return 1
end
if n > 0 and k == 0 then
return 0
end
if k > n then
return 0
end
key = [n, k]
if $cache[key] then
return $cache[key]
end
value = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k)
$cache[key] = value
return value
end
MAX = 12
def main
print "Unsigned Stirling numbers of the first kind:\n"
print "n/k"
for n in 0 .. MAX
print "%10d" % [n]
end
print "\n"
for n in 0 .. MAX
print "%-3d" % [n]
for k in 0 .. n
print "%10d" % [sterling1(n, k)]
end
print "\n"
end
print "The maximum value of S1(100, k) =\n"
previous = 0
for k in 1 .. 100
current = sterling1(100, k)
if previous < current then
previous = current
else
print previous, "\n"
print "(%d digits, k = %d)\n" % [previous.to_s.length, k - 1]
break
end
end
end
main()
|
Maintain the same structure and functionality when rewriting this code in Ruby. | import javafx.util.Pair;
import java.util.ArrayList;
import java.util.List;
public class LineSimplification {
private static class Point extends Pair<Double, Double> {
Point(Double key, Double value) {
super(key, value);
}
@Override
public String toString() {
return String.format("(%f, %f)", getKey(), getValue());
}
}
private static double perpendicularDistance(Point pt, Point lineStart, Point lineEnd) {
double dx = lineEnd.getKey() - lineStart.getKey();
double dy = lineEnd.getValue() - lineStart.getValue();
double mag = Math.hypot(dx, dy);
if (mag > 0.0) {
dx /= mag;
dy /= mag;
}
double pvx = pt.getKey() - lineStart.getKey();
double pvy = pt.getValue() - lineStart.getValue();
double pvdot = dx * pvx + dy * pvy;
double ax = pvx - pvdot * dx;
double ay = pvy - pvdot * dy;
return Math.hypot(ax, ay);
}
private static void ramerDouglasPeucker(List<Point> pointList, double epsilon, List<Point> out) {
if (pointList.size() < 2) throw new IllegalArgumentException("Not enough points to simplify");
double dmax = 0.0;
int index = 0;
int end = pointList.size() - 1;
for (int i = 1; i < end; ++i) {
double d = perpendicularDistance(pointList.get(i), pointList.get(0), pointList.get(end));
if (d > dmax) {
index = i;
dmax = d;
}
}
if (dmax > epsilon) {
List<Point> recResults1 = new ArrayList<>();
List<Point> recResults2 = new ArrayList<>();
List<Point> firstLine = pointList.subList(0, index + 1);
List<Point> lastLine = pointList.subList(index, pointList.size());
ramerDouglasPeucker(firstLine, epsilon, recResults1);
ramerDouglasPeucker(lastLine, epsilon, recResults2);
out.addAll(recResults1.subList(0, recResults1.size() - 1));
out.addAll(recResults2);
if (out.size() < 2) throw new RuntimeException("Problem assembling output");
} else {
out.clear();
out.add(pointList.get(0));
out.add(pointList.get(pointList.size() - 1));
}
}
public static void main(String[] args) {
List<Point> pointList = List.of(
new Point(0.0, 0.0),
new Point(1.0, 0.1),
new Point(2.0, -0.1),
new Point(3.0, 5.0),
new Point(4.0, 6.0),
new Point(5.0, 7.0),
new Point(6.0, 8.1),
new Point(7.0, 9.0),
new Point(8.0, 9.0),
new Point(9.0, 9.0)
);
List<Point> pointListOut = new ArrayList<>();
ramerDouglasPeucker(pointList, 1.0, pointListOut);
System.out.println("Points remaining after simplification:");
pointListOut.forEach(System.out::println);
}
}
| func perpendicular_distance(Arr start, Arr end, Arr point) {
((point == start) || (point == end)) && return 0
var (Δx, Δy ) = ( end »-« start)...
var (Δpx, Δpy) = (point »-« start)...
var h = hypot(Δx, Δy)
[\Δx, \Δy].map { *_ /= h }
(([Δpx, Δpy] »-« ([Δx, Δy] »*» (Δx*Δpx + Δy*Δpy))) »**» 2).sum.sqrt
}
func Ramer_Douglas_Peucker(Arr points { .all { .len > 1 } }, ε = 1) {
points.len == 2 && return points
var d = (^points -> map {
perpendicular_distance(points[0], points[-1], points[_])
})
if (d.max > ε) {
var i = d.index(d.max)
return [Ramer_Douglas_Peucker(points.ft(0, i), ε).ft(0, -2)...,
Ramer_Douglas_Peucker(points.ft(i), ε)...]
}
return [points[0,-1]]
}
say Ramer_Douglas_Peucker(
[[0,0],[1,0.1],[2,-0.1],[3,5],[4,6],[5,7],[6,8.1],[7,9],[8,9],[9,9]]
)
|
Write a version of this Java function in Ruby with identical behavior. | import javafx.util.Pair;
import java.util.ArrayList;
import java.util.List;
public class LineSimplification {
private static class Point extends Pair<Double, Double> {
Point(Double key, Double value) {
super(key, value);
}
@Override
public String toString() {
return String.format("(%f, %f)", getKey(), getValue());
}
}
private static double perpendicularDistance(Point pt, Point lineStart, Point lineEnd) {
double dx = lineEnd.getKey() - lineStart.getKey();
double dy = lineEnd.getValue() - lineStart.getValue();
double mag = Math.hypot(dx, dy);
if (mag > 0.0) {
dx /= mag;
dy /= mag;
}
double pvx = pt.getKey() - lineStart.getKey();
double pvy = pt.getValue() - lineStart.getValue();
double pvdot = dx * pvx + dy * pvy;
double ax = pvx - pvdot * dx;
double ay = pvy - pvdot * dy;
return Math.hypot(ax, ay);
}
private static void ramerDouglasPeucker(List<Point> pointList, double epsilon, List<Point> out) {
if (pointList.size() < 2) throw new IllegalArgumentException("Not enough points to simplify");
double dmax = 0.0;
int index = 0;
int end = pointList.size() - 1;
for (int i = 1; i < end; ++i) {
double d = perpendicularDistance(pointList.get(i), pointList.get(0), pointList.get(end));
if (d > dmax) {
index = i;
dmax = d;
}
}
if (dmax > epsilon) {
List<Point> recResults1 = new ArrayList<>();
List<Point> recResults2 = new ArrayList<>();
List<Point> firstLine = pointList.subList(0, index + 1);
List<Point> lastLine = pointList.subList(index, pointList.size());
ramerDouglasPeucker(firstLine, epsilon, recResults1);
ramerDouglasPeucker(lastLine, epsilon, recResults2);
out.addAll(recResults1.subList(0, recResults1.size() - 1));
out.addAll(recResults2);
if (out.size() < 2) throw new RuntimeException("Problem assembling output");
} else {
out.clear();
out.add(pointList.get(0));
out.add(pointList.get(pointList.size() - 1));
}
}
public static void main(String[] args) {
List<Point> pointList = List.of(
new Point(0.0, 0.0),
new Point(1.0, 0.1),
new Point(2.0, -0.1),
new Point(3.0, 5.0),
new Point(4.0, 6.0),
new Point(5.0, 7.0),
new Point(6.0, 8.1),
new Point(7.0, 9.0),
new Point(8.0, 9.0),
new Point(9.0, 9.0)
);
List<Point> pointListOut = new ArrayList<>();
ramerDouglasPeucker(pointList, 1.0, pointListOut);
System.out.println("Points remaining after simplification:");
pointListOut.forEach(System.out::println);
}
}
| func perpendicular_distance(Arr start, Arr end, Arr point) {
((point == start) || (point == end)) && return 0
var (Δx, Δy ) = ( end »-« start)...
var (Δpx, Δpy) = (point »-« start)...
var h = hypot(Δx, Δy)
[\Δx, \Δy].map { *_ /= h }
(([Δpx, Δpy] »-« ([Δx, Δy] »*» (Δx*Δpx + Δy*Δpy))) »**» 2).sum.sqrt
}
func Ramer_Douglas_Peucker(Arr points { .all { .len > 1 } }, ε = 1) {
points.len == 2 && return points
var d = (^points -> map {
perpendicular_distance(points[0], points[-1], points[_])
})
if (d.max > ε) {
var i = d.index(d.max)
return [Ramer_Douglas_Peucker(points.ft(0, i), ε).ft(0, -2)...,
Ramer_Douglas_Peucker(points.ft(i), ε)...]
}
return [points[0,-1]]
}
say Ramer_Douglas_Peucker(
[[0,0],[1,0.1],[2,-0.1],[3,5],[4,6],[5,7],[6,8.1],[7,9],[8,9],[9,9]]
)
|
Rewrite the snippet below in Ruby so it works the same as the original Java code. | import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class BilinearInterpolation {
private static int get(int self, int n) {
return (self >> (n * 8)) & 0xFF;
}
private static float lerp(float s, float e, float t) {
return s + (e - s) * t;
}
private static float blerp(final Float c00, float c10, float c01, float c11, float tx, float ty) {
return lerp(lerp(c00, c10, tx), lerp(c01, c11, tx), ty);
}
private static BufferedImage scale(BufferedImage self, float scaleX, float scaleY) {
int newWidth = (int) (self.getWidth() * scaleX);
int newHeight = (int) (self.getHeight() * scaleY);
BufferedImage newImage = new BufferedImage(newWidth, newHeight, self.getType());
for (int x = 0; x < newWidth; ++x) {
for (int y = 0; y < newHeight; ++y) {
float gx = ((float) x) / newWidth * (self.getWidth() - 1);
float gy = ((float) y) / newHeight * (self.getHeight() - 1);
int gxi = (int) gx;
int gyi = (int) gy;
int rgb = 0;
int c00 = self.getRGB(gxi, gyi);
int c10 = self.getRGB(gxi + 1, gyi);
int c01 = self.getRGB(gxi, gyi + 1);
int c11 = self.getRGB(gxi + 1, gyi + 1);
for (int i = 0; i <= 2; ++i) {
float b00 = get(c00, i);
float b10 = get(c10, i);
float b01 = get(c01, i);
float b11 = get(c11, i);
int ble = ((int) blerp(b00, b10, b01, b11, gx - gxi, gy - gyi)) << (8 * i);
rgb = rgb | ble;
}
newImage.setRGB(x, y, rgb);
}
}
return newImage;
}
public static void main(String[] args) throws IOException {
File lenna = new File("Lenna100.jpg");
BufferedImage image = ImageIO.read(lenna);
BufferedImage image2 = scale(image, 1.6f, 1.6f);
File lenna2 = new File("Lenna100_larger.jpg");
ImageIO.write(image2, "jpg", lenna2);
}
}
| require('Imager')
func scale(img, scaleX, scaleY) {
var (width, height) = (img.getwidth, img.getheight)
var (newWidth, newHeight) = (int(width*scaleX), int(height*scaleY))
var out = %O<Imager>.new(xsize => newWidth, ysize => newHeight)
var lerp = { |s, e, t|
s + t*(e-s)
}
var blerp = { |c00, c10, c01, c11, tx, ty|
lerp(lerp(c00, c10, tx), lerp(c01, c11, tx), ty)
}
for x,y in (^newWidth ~X ^newHeight) {
var gxf = (x/newWidth * (width - 1))
var gyf = (y/newHeight * (height - 1))
var gx = gxf.int
var gy = gyf.int
var *c00 = img.getpixel(x => gx, y => gy ).rgba
var *c10 = img.getpixel(x => gx+1, y => gy ).rgba
var *c01 = img.getpixel(x => gx, y => gy+1).rgba
var *c11 = img.getpixel(x => gx+1, y => gy+1).rgba
var rgb = 3.of { |i|
blerp(c00[i], c10[i], c01[i], c11[i], gxf - gx, gyf - gy).int
}
out.setpixel(x => x, y => y, color => rgb)
}
return out
}
var img = %O<Imager>.new(file => "input.png")
var out = scale(img, 1.6, 1.6)
out.write(file => "output.png")
|
Please provide an equivalent version of this Java code in Ruby. | import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class BilinearInterpolation {
private static int get(int self, int n) {
return (self >> (n * 8)) & 0xFF;
}
private static float lerp(float s, float e, float t) {
return s + (e - s) * t;
}
private static float blerp(final Float c00, float c10, float c01, float c11, float tx, float ty) {
return lerp(lerp(c00, c10, tx), lerp(c01, c11, tx), ty);
}
private static BufferedImage scale(BufferedImage self, float scaleX, float scaleY) {
int newWidth = (int) (self.getWidth() * scaleX);
int newHeight = (int) (self.getHeight() * scaleY);
BufferedImage newImage = new BufferedImage(newWidth, newHeight, self.getType());
for (int x = 0; x < newWidth; ++x) {
for (int y = 0; y < newHeight; ++y) {
float gx = ((float) x) / newWidth * (self.getWidth() - 1);
float gy = ((float) y) / newHeight * (self.getHeight() - 1);
int gxi = (int) gx;
int gyi = (int) gy;
int rgb = 0;
int c00 = self.getRGB(gxi, gyi);
int c10 = self.getRGB(gxi + 1, gyi);
int c01 = self.getRGB(gxi, gyi + 1);
int c11 = self.getRGB(gxi + 1, gyi + 1);
for (int i = 0; i <= 2; ++i) {
float b00 = get(c00, i);
float b10 = get(c10, i);
float b01 = get(c01, i);
float b11 = get(c11, i);
int ble = ((int) blerp(b00, b10, b01, b11, gx - gxi, gy - gyi)) << (8 * i);
rgb = rgb | ble;
}
newImage.setRGB(x, y, rgb);
}
}
return newImage;
}
public static void main(String[] args) throws IOException {
File lenna = new File("Lenna100.jpg");
BufferedImage image = ImageIO.read(lenna);
BufferedImage image2 = scale(image, 1.6f, 1.6f);
File lenna2 = new File("Lenna100_larger.jpg");
ImageIO.write(image2, "jpg", lenna2);
}
}
| require('Imager')
func scale(img, scaleX, scaleY) {
var (width, height) = (img.getwidth, img.getheight)
var (newWidth, newHeight) = (int(width*scaleX), int(height*scaleY))
var out = %O<Imager>.new(xsize => newWidth, ysize => newHeight)
var lerp = { |s, e, t|
s + t*(e-s)
}
var blerp = { |c00, c10, c01, c11, tx, ty|
lerp(lerp(c00, c10, tx), lerp(c01, c11, tx), ty)
}
for x,y in (^newWidth ~X ^newHeight) {
var gxf = (x/newWidth * (width - 1))
var gyf = (y/newHeight * (height - 1))
var gx = gxf.int
var gy = gyf.int
var *c00 = img.getpixel(x => gx, y => gy ).rgba
var *c10 = img.getpixel(x => gx+1, y => gy ).rgba
var *c01 = img.getpixel(x => gx, y => gy+1).rgba
var *c11 = img.getpixel(x => gx+1, y => gy+1).rgba
var rgb = 3.of { |i|
blerp(c00[i], c10[i], c01[i], c11[i], gxf - gx, gyf - gy).int
}
out.setpixel(x => x, y => y, color => rgb)
}
return out
}
var img = %O<Imager>.new(file => "input.png")
var out = scale(img, 1.6, 1.6)
out.write(file => "output.png")
|
Change the following Java code into Ruby without altering its purpose. | import java.util.Locale;
public class Test {
public static void main(String[] args) {
System.out.println(new Vec2(5, 7).add(new Vec2(2, 3)));
System.out.println(new Vec2(5, 7).sub(new Vec2(2, 3)));
System.out.println(new Vec2(5, 7).mult(11));
System.out.println(new Vec2(5, 7).div(2));
}
}
class Vec2 {
final double x, y;
Vec2(double x, double y) {
this.x = x;
this.y = y;
}
Vec2 add(Vec2 v) {
return new Vec2(x + v.x, y + v.y);
}
Vec2 sub(Vec2 v) {
return new Vec2(x - v.x, y - v.y);
}
Vec2 div(double val) {
return new Vec2(x / val, y / val);
}
Vec2 mult(double val) {
return new Vec2(x * val, y * val);
}
@Override
public String toString() {
return String.format(Locale.US, "[%s, %s]", x, y);
}
}
| class Vector
def self.polar(r, angle=0)
new(r*Math.cos(angle), r*Math.sin(angle))
end
attr_reader :x, :y
def initialize(x, y)
raise TypeError unless x.is_a?(Numeric) and y.is_a?(Numeric)
@x, @y = x, y
end
def +(other)
raise TypeError if self.class != other.class
self.class.new(@x + other.x, @y + other.y)
end
def -@; self.class.new(-@x, -@y) end
def -(other) self + (-other) end
def *(scalar)
raise TypeError unless scalar.is_a?(Numeric)
self.class.new(@x * scalar, @y * scalar)
end
def /(scalar)
raise TypeError unless scalar.is_a?(Numeric) and scalar.nonzero?
self.class.new(@x / scalar, @y / scalar)
end
def r; @r ||= Math.hypot(@x, @y) end
def angle; @angle ||= Math.atan2(@y, @x) end
def polar; [r, angle] end
def rect; [@x, @y] end
def to_s; "
alias inspect to_s
end
p v = Vector.new(1,1)
p w = Vector.new(3,4)
p v + w
p v - w
p -v
p w * 5
p w / 2.0
p w.x
p w.y
p v.polar
p w.polar
p z = Vector.polar(1, Math::PI/2)
p z.rect
p z.polar
p z = Vector.polar(-2, Math::PI/4)
p z.polar
|
Generate an equivalent Ruby version of this Java code. | import static java.lang.Math.*;
import java.util.Locale;
public class Test {
public static void main(String[] args) {
Pt a = Pt.fromY(1);
Pt b = Pt.fromY(2);
System.out.printf("a = %s%n", a);
System.out.printf("b = %s%n", b);
Pt c = a.plus(b);
System.out.printf("c = a + b = %s%n", c);
Pt d = c.neg();
System.out.printf("d = -c = %s%n", d);
System.out.printf("c + d = %s%n", c.plus(d));
System.out.printf("a + b + d = %s%n", a.plus(b).plus(d));
System.out.printf("a * 12345 = %s%n", a.mult(12345));
}
}
class Pt {
final static int bCoeff = 7;
double x, y;
Pt(double x, double y) {
this.x = x;
this.y = y;
}
static Pt zero() {
return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
}
boolean isZero() {
return this.x > 1e20 || this.x < -1e20;
}
static Pt fromY(double y) {
return new Pt(cbrt(pow(y, 2) - bCoeff), y);
}
Pt dbl() {
if (isZero())
return this;
double L = (3 * this.x * this.x) / (2 * this.y);
double x2 = pow(L, 2) - 2 * this.x;
return new Pt(x2, L * (this.x - x2) - this.y);
}
Pt neg() {
return new Pt(this.x, -this.y);
}
Pt plus(Pt q) {
if (this.x == q.x && this.y == q.y)
return dbl();
if (isZero())
return q;
if (q.isZero())
return this;
double L = (q.y - this.y) / (q.x - this.x);
double xx = pow(L, 2) - this.x - q.x;
return new Pt(xx, L * (this.x - xx) - this.y);
}
Pt mult(int n) {
Pt r = Pt.zero();
Pt p = this;
for (int i = 1; i <= n; i <<= 1) {
if ((i & n) != 0)
r = r.plus(p);
p = p.dbl();
}
return r;
}
@Override
public String toString() {
if (isZero())
return "Zero";
return String.format(Locale.US, "(%.3f,%.3f)", this.x, this.y);
}
}
| module EC {
var A = 0
var B = 7
class Horizon {
method to_s {
"EC Point at horizon"
}
method *(_) {
self
}
method -(_) {
self
}
}
class Point(Number x, Number y) {
method to_s {
"EC Point at x=
}
method neg {
Point(x, -y)
}
method -(Point p) {
self + -p
}
method +(Point p) {
if (x == p.x) {
return (y == p.y ? self*2 : Horizon())
}
else {
var slope = (p.y - y)/(p.x - x)
var x2 = (slope**2 - x - p.x)
var y2 = (slope * (x - x2) - y)
Point(x2, y2)
}
}
method +(Horizon _) {
self
}
method *((0)) {
Horizon()
}
method *((1)) {
self
}
method *((2)) {
var l = (3 * x**2 + A)/(2 * y)
var x2 = (l**2 - 2*x)
var y2 = (l * (x - x2) - y)
Point(x2, y2)
}
method *(Number n) {
2*(self * (n>>1)) + self*(n % 2)
}
}
class Horizon {
method +(Point p) {
p
}
}
class Number {
method +(Point p) {
p + self
}
method *(Point p) {
p * self
}
method *(Horizon h) {
h
}
method -(Point p) {
-p + self
}
}
}
say var p = with(1) {|v| EC::Point(v, sqrt(abs(1 - v**3 - EC::A*v - EC::B))) }
say var q = with(2) {|v| EC::Point(v, sqrt(abs(1 - v**3 - EC::A*v - EC::B))) }
say var s = (p + q)
say ("checking alignment: ", abs((p.x - q.x)*(-s.y - q.y) - (p.y - q.y)*(s.x - q.x)) < 1e-20)
|
Change the programming language of this snippet from Java to Ruby without modifying what it does. | import static java.lang.Math.*;
import java.util.Locale;
public class Test {
public static void main(String[] args) {
Pt a = Pt.fromY(1);
Pt b = Pt.fromY(2);
System.out.printf("a = %s%n", a);
System.out.printf("b = %s%n", b);
Pt c = a.plus(b);
System.out.printf("c = a + b = %s%n", c);
Pt d = c.neg();
System.out.printf("d = -c = %s%n", d);
System.out.printf("c + d = %s%n", c.plus(d));
System.out.printf("a + b + d = %s%n", a.plus(b).plus(d));
System.out.printf("a * 12345 = %s%n", a.mult(12345));
}
}
class Pt {
final static int bCoeff = 7;
double x, y;
Pt(double x, double y) {
this.x = x;
this.y = y;
}
static Pt zero() {
return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
}
boolean isZero() {
return this.x > 1e20 || this.x < -1e20;
}
static Pt fromY(double y) {
return new Pt(cbrt(pow(y, 2) - bCoeff), y);
}
Pt dbl() {
if (isZero())
return this;
double L = (3 * this.x * this.x) / (2 * this.y);
double x2 = pow(L, 2) - 2 * this.x;
return new Pt(x2, L * (this.x - x2) - this.y);
}
Pt neg() {
return new Pt(this.x, -this.y);
}
Pt plus(Pt q) {
if (this.x == q.x && this.y == q.y)
return dbl();
if (isZero())
return q;
if (q.isZero())
return this;
double L = (q.y - this.y) / (q.x - this.x);
double xx = pow(L, 2) - this.x - q.x;
return new Pt(xx, L * (this.x - xx) - this.y);
}
Pt mult(int n) {
Pt r = Pt.zero();
Pt p = this;
for (int i = 1; i <= n; i <<= 1) {
if ((i & n) != 0)
r = r.plus(p);
p = p.dbl();
}
return r;
}
@Override
public String toString() {
if (isZero())
return "Zero";
return String.format(Locale.US, "(%.3f,%.3f)", this.x, this.y);
}
}
| module EC {
var A = 0
var B = 7
class Horizon {
method to_s {
"EC Point at horizon"
}
method *(_) {
self
}
method -(_) {
self
}
}
class Point(Number x, Number y) {
method to_s {
"EC Point at x=
}
method neg {
Point(x, -y)
}
method -(Point p) {
self + -p
}
method +(Point p) {
if (x == p.x) {
return (y == p.y ? self*2 : Horizon())
}
else {
var slope = (p.y - y)/(p.x - x)
var x2 = (slope**2 - x - p.x)
var y2 = (slope * (x - x2) - y)
Point(x2, y2)
}
}
method +(Horizon _) {
self
}
method *((0)) {
Horizon()
}
method *((1)) {
self
}
method *((2)) {
var l = (3 * x**2 + A)/(2 * y)
var x2 = (l**2 - 2*x)
var y2 = (l * (x - x2) - y)
Point(x2, y2)
}
method *(Number n) {
2*(self * (n>>1)) + self*(n % 2)
}
}
class Horizon {
method +(Point p) {
p
}
}
class Number {
method +(Point p) {
p + self
}
method *(Point p) {
p * self
}
method *(Horizon h) {
h
}
method -(Point p) {
-p + self
}
}
}
say var p = with(1) {|v| EC::Point(v, sqrt(abs(1 - v**3 - EC::A*v - EC::B))) }
say var q = with(2) {|v| EC::Point(v, sqrt(abs(1 - v**3 - EC::A*v - EC::B))) }
say var s = (p + q)
say ("checking alignment: ", abs((p.x - q.x)*(-s.y - q.y) - (p.y - q.y)*(s.x - q.x)) < 1e-20)
|
Produce a functionally identical Ruby code for the snippet given in Java. | import static java.lang.Math.*;
import java.util.function.Function;
public class ChebyshevCoefficients {
static double map(double x, double min_x, double max_x, double min_to,
double max_to) {
return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to;
}
static void chebyshevCoef(Function<Double, Double> func, double min,
double max, double[] coef) {
int N = coef.length;
for (int i = 0; i < N; i++) {
double m = map(cos(PI * (i + 0.5f) / N), -1, 1, min, max);
double f = func.apply(m) * 2 / N;
for (int j = 0; j < N; j++) {
coef[j] += f * cos(PI * j * (i + 0.5f) / N);
}
}
}
public static void main(String[] args) {
final int N = 10;
double[] c = new double[N];
double min = 0, max = 1;
chebyshevCoef(x -> cos(x), min, max, c);
System.out.println("Coefficients:");
for (double d : c)
System.out.println(d);
}
}
| def mapp(x, min_x, max_x, min_to, max_to)
return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to
end
def chebyshevCoef(func, min, max, coef)
n = coef.length
for i in 0 .. n-1 do
m = mapp(Math.cos(Math::PI * (i + 0.5) / n), -1, 1, min, max)
f = func.call(m) * 2 / n
for j in 0 .. n-1 do
coef[j] = coef[j] + f * Math.cos(Math::PI * j * (i + 0.5) / n)
end
end
end
N = 10
def main
c = Array.new(N, 0)
min = 0
max = 1
chebyshevCoef(lambda { |x| Math.cos(x) }, min, max, c)
puts "Coefficients:"
puts c
end
main()
|
Keep all operations the same but rewrite the snippet in Ruby. | import static java.lang.Math.*;
import java.util.function.Function;
public class ChebyshevCoefficients {
static double map(double x, double min_x, double max_x, double min_to,
double max_to) {
return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to;
}
static void chebyshevCoef(Function<Double, Double> func, double min,
double max, double[] coef) {
int N = coef.length;
for (int i = 0; i < N; i++) {
double m = map(cos(PI * (i + 0.5f) / N), -1, 1, min, max);
double f = func.apply(m) * 2 / N;
for (int j = 0; j < N; j++) {
coef[j] += f * cos(PI * j * (i + 0.5f) / N);
}
}
}
public static void main(String[] args) {
final int N = 10;
double[] c = new double[N];
double min = 0, max = 1;
chebyshevCoef(x -> cos(x), min, max, c);
System.out.println("Coefficients:");
for (double d : c)
System.out.println(d);
}
}
| def mapp(x, min_x, max_x, min_to, max_to)
return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to
end
def chebyshevCoef(func, min, max, coef)
n = coef.length
for i in 0 .. n-1 do
m = mapp(Math.cos(Math::PI * (i + 0.5) / n), -1, 1, min, max)
f = func.call(m) * 2 / n
for j in 0 .. n-1 do
coef[j] = coef[j] + f * Math.cos(Math::PI * j * (i + 0.5) / n)
end
end
end
N = 10
def main
c = Array.new(N, 0)
min = 0
max = 1
chebyshevCoef(lambda { |x| Math.cos(x) }, min, max, c)
puts "Coefficients:"
puts c
end
main()
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | import java.util.ArrayList;
import java.util.List;
public class BWT {
private static final String STX = "\u0002";
private static final String ETX = "\u0003";
private static String bwt(String s) {
if (s.contains(STX) || s.contains(ETX)) {
throw new IllegalArgumentException("String cannot contain STX or ETX");
}
String ss = STX + s + ETX;
List<String> table = new ArrayList<>();
for (int i = 0; i < ss.length(); i++) {
String before = ss.substring(i);
String after = ss.substring(0, i);
table.add(before + after);
}
table.sort(String::compareTo);
StringBuilder sb = new StringBuilder();
for (String str : table) {
sb.append(str.charAt(str.length() - 1));
}
return sb.toString();
}
private static String ibwt(String r) {
int len = r.length();
List<String> table = new ArrayList<>();
for (int i = 0; i < len; ++i) {
table.add("");
}
for (int j = 0; j < len; ++j) {
for (int i = 0; i < len; ++i) {
table.set(i, r.charAt(i) + table.get(i));
}
table.sort(String::compareTo);
}
for (String row : table) {
if (row.endsWith(ETX)) {
return row.substring(1, len - 1);
}
}
return "";
}
private static String makePrintable(String s) {
return s.replace(STX, "^").replace(ETX, "|");
}
public static void main(String[] args) {
List<String> tests = List.of(
"banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"\u0002ABC\u0003"
);
for (String test : tests) {
System.out.println(makePrintable(test));
System.out.print(" --> ");
String t = "";
try {
t = bwt(test);
System.out.println(makePrintable(t));
} catch (IllegalArgumentException e) {
System.out.println("ERROR: " + e.getMessage());
}
String r = ibwt(t);
System.out.printf(" --> %s\n\n", r);
}
}
}
| STX = "\u0002"
ETX = "\u0003"
def bwt(s)
for c in s.split('')
if c == STX or c == ETX then
raise ArgumentError.new("Input can't contain STX or ETX")
end
end
ss = ("%s%s%s" % [STX, s, ETX]).split('')
table = []
for i in 0 .. ss.length - 1
table.append(ss.join)
ss = ss.rotate(-1)
end
table = table.sort
return table.map{ |e| e[-1] }.join
end
def ibwt(r)
len = r.length
table = [""] * len
for i in 0 .. len - 1
for j in 0 .. len - 1
table[j] = r[j] + table[j]
end
table = table.sort
end
for row in table
if row[-1] == ETX then
return row[1 .. -2]
end
end
return ""
end
def makePrintable(s)
s = s.gsub(STX, "^")
return s.gsub(ETX, "|")
end
def main
tests = [
"banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"\u0002ABC\u0003"
]
for test in tests
print makePrintable(test), "\n"
print " --> "
begin
t = bwt(test)
print makePrintable(t), "\n"
r = ibwt(t)
print " --> ", r, "\n\n"
rescue ArgumentError => e
print e.message, "\n"
print " -->\n\n"
end
end
end
main()
|
Port the provided Java code into Ruby while preserving the original functionality. | import java.util.ArrayList;
import java.util.List;
public class BWT {
private static final String STX = "\u0002";
private static final String ETX = "\u0003";
private static String bwt(String s) {
if (s.contains(STX) || s.contains(ETX)) {
throw new IllegalArgumentException("String cannot contain STX or ETX");
}
String ss = STX + s + ETX;
List<String> table = new ArrayList<>();
for (int i = 0; i < ss.length(); i++) {
String before = ss.substring(i);
String after = ss.substring(0, i);
table.add(before + after);
}
table.sort(String::compareTo);
StringBuilder sb = new StringBuilder();
for (String str : table) {
sb.append(str.charAt(str.length() - 1));
}
return sb.toString();
}
private static String ibwt(String r) {
int len = r.length();
List<String> table = new ArrayList<>();
for (int i = 0; i < len; ++i) {
table.add("");
}
for (int j = 0; j < len; ++j) {
for (int i = 0; i < len; ++i) {
table.set(i, r.charAt(i) + table.get(i));
}
table.sort(String::compareTo);
}
for (String row : table) {
if (row.endsWith(ETX)) {
return row.substring(1, len - 1);
}
}
return "";
}
private static String makePrintable(String s) {
return s.replace(STX, "^").replace(ETX, "|");
}
public static void main(String[] args) {
List<String> tests = List.of(
"banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"\u0002ABC\u0003"
);
for (String test : tests) {
System.out.println(makePrintable(test));
System.out.print(" --> ");
String t = "";
try {
t = bwt(test);
System.out.println(makePrintable(t));
} catch (IllegalArgumentException e) {
System.out.println("ERROR: " + e.getMessage());
}
String r = ibwt(t);
System.out.printf(" --> %s\n\n", r);
}
}
}
| STX = "\u0002"
ETX = "\u0003"
def bwt(s)
for c in s.split('')
if c == STX or c == ETX then
raise ArgumentError.new("Input can't contain STX or ETX")
end
end
ss = ("%s%s%s" % [STX, s, ETX]).split('')
table = []
for i in 0 .. ss.length - 1
table.append(ss.join)
ss = ss.rotate(-1)
end
table = table.sort
return table.map{ |e| e[-1] }.join
end
def ibwt(r)
len = r.length
table = [""] * len
for i in 0 .. len - 1
for j in 0 .. len - 1
table[j] = r[j] + table[j]
end
table = table.sort
end
for row in table
if row[-1] == ETX then
return row[1 .. -2]
end
end
return ""
end
def makePrintable(s)
s = s.gsub(STX, "^")
return s.gsub(ETX, "|")
end
def main
tests = [
"banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"\u0002ABC\u0003"
]
for test in tests
print makePrintable(test), "\n"
print " --> "
begin
t = bwt(test)
print makePrintable(t), "\n"
r = ibwt(t)
print " --> ", r, "\n\n"
rescue ArgumentError => e
print e.message, "\n"
print " -->\n\n"
end
end
end
main()
|
Write the same code in Ruby as shown below in Java. | import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
public class CardShuffles{
private static final Random rand = new Random();
public static <T> LinkedList<T> riffleShuffle(List<T> list, int flips){
LinkedList<T> newList = new LinkedList<T>();
newList.addAll(list);
for(int n = 0; n < flips; n++){
int cutPoint = newList.size() / 2
+ (rand.nextBoolean() ? -1 : 1 ) * rand.nextInt((int)(newList.size() * 0.1));
List<T> left = new LinkedList<T>();
left.addAll(newList.subList(0, cutPoint));
List<T> right = new LinkedList<T>();
right.addAll(newList.subList(cutPoint, newList.size()));
newList.clear();
while(left.size() > 0 && right.size() > 0){
if(rand.nextDouble() >= ((double)left.size() / right.size()) / 2){
newList.add(right.remove(0));
}else{
newList.add(left.remove(0));
}
}
if(left.size() > 0) newList.addAll(left);
if(right.size() > 0) newList.addAll(right);
}
return newList;
}
public static <T> LinkedList<T> overhandShuffle(List<T> list, int passes){
LinkedList<T> mainHand = new LinkedList<T>();
mainHand.addAll(list);
for(int n = 0; n < passes; n++){
LinkedList<T> otherHand = new LinkedList<T>();
while(mainHand.size() > 0){
int cutSize = rand.nextInt((int)(list.size() * 0.2)) + 1;
LinkedList<T> temp = new LinkedList<T>();
for(int i = 0; i < cutSize && mainHand.size() > 0; i++){
temp.add(mainHand.remove());
}
if(rand.nextDouble() >= 0.1){
otherHand.addAll(0, temp);
}else{
otherHand.addAll(temp);
}
}
mainHand = otherHand;
}
return mainHand;
}
public static void main(String[] args){
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
System.out.println(list);
list = riffleShuffle(list, 10);
System.out.println(list + "\n");
list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
System.out.println(list);
list = riffleShuffle(list, 1);
System.out.println(list + "\n");
list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
System.out.println(list);
list = overhandShuffle(list, 10);
System.out.println(list + "\n");
list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
System.out.println(list);
list = overhandShuffle(list, 1);
System.out.println(list + "\n");
list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
System.out.println(list);
Collections.shuffle(list);
System.out.println(list + "\n");
}
}
| def riffle deck
left, right = deck.partition{rand(10).odd?}
new_deck = []
until ((left_card=left.pop).to_i + (right_card=right.shift).to_i).zero? do
new_deck << left_card if left_card
new_deck << right_card if right_card
end
new_deck
end
def overhand deck
deck, new_deck = deck.dup, []
s = deck.size
new_deck += deck.pop(rand(s * 0.2)) until deck.empty?
new_deck
end
def bonus deck
deck.sort { |a, b| Time.now.to_i % a <=> Time.now.to_i % b }
end
deck = [*1..20]
p riffle(deck)
p overhand(deck)
p bonus(deck)
|
Translate the given Java code snippet into Ruby without altering its behavior. | import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
public class CardShuffles{
private static final Random rand = new Random();
public static <T> LinkedList<T> riffleShuffle(List<T> list, int flips){
LinkedList<T> newList = new LinkedList<T>();
newList.addAll(list);
for(int n = 0; n < flips; n++){
int cutPoint = newList.size() / 2
+ (rand.nextBoolean() ? -1 : 1 ) * rand.nextInt((int)(newList.size() * 0.1));
List<T> left = new LinkedList<T>();
left.addAll(newList.subList(0, cutPoint));
List<T> right = new LinkedList<T>();
right.addAll(newList.subList(cutPoint, newList.size()));
newList.clear();
while(left.size() > 0 && right.size() > 0){
if(rand.nextDouble() >= ((double)left.size() / right.size()) / 2){
newList.add(right.remove(0));
}else{
newList.add(left.remove(0));
}
}
if(left.size() > 0) newList.addAll(left);
if(right.size() > 0) newList.addAll(right);
}
return newList;
}
public static <T> LinkedList<T> overhandShuffle(List<T> list, int passes){
LinkedList<T> mainHand = new LinkedList<T>();
mainHand.addAll(list);
for(int n = 0; n < passes; n++){
LinkedList<T> otherHand = new LinkedList<T>();
while(mainHand.size() > 0){
int cutSize = rand.nextInt((int)(list.size() * 0.2)) + 1;
LinkedList<T> temp = new LinkedList<T>();
for(int i = 0; i < cutSize && mainHand.size() > 0; i++){
temp.add(mainHand.remove());
}
if(rand.nextDouble() >= 0.1){
otherHand.addAll(0, temp);
}else{
otherHand.addAll(temp);
}
}
mainHand = otherHand;
}
return mainHand;
}
public static void main(String[] args){
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
System.out.println(list);
list = riffleShuffle(list, 10);
System.out.println(list + "\n");
list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
System.out.println(list);
list = riffleShuffle(list, 1);
System.out.println(list + "\n");
list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
System.out.println(list);
list = overhandShuffle(list, 10);
System.out.println(list + "\n");
list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
System.out.println(list);
list = overhandShuffle(list, 1);
System.out.println(list + "\n");
list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
System.out.println(list);
Collections.shuffle(list);
System.out.println(list + "\n");
}
}
| def riffle deck
left, right = deck.partition{rand(10).odd?}
new_deck = []
until ((left_card=left.pop).to_i + (right_card=right.shift).to_i).zero? do
new_deck << left_card if left_card
new_deck << right_card if right_card
end
new_deck
end
def overhand deck
deck, new_deck = deck.dup, []
s = deck.size
new_deck += deck.pop(rand(s * 0.2)) until deck.empty?
new_deck
end
def bonus deck
deck.sort { |a, b| Time.now.to_i % a <=> Time.now.to_i % b }
end
deck = [*1..20]
p riffle(deck)
p overhand(deck)
p bonus(deck)
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Arrays;
import java.util.stream.LongStream;
public class FaulhabersTriangle {
private static final MathContext MC = new MathContext(256);
private static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
private static class Frac implements Comparable<Frac> {
private long num;
private long denom;
public static final Frac ZERO = new Frac(0, 1);
public Frac(long n, long d) {
if (d == 0) throw new IllegalArgumentException("d must not be zero");
long nn = n;
long dd = d;
if (nn == 0) {
dd = 1;
} else if (dd < 0) {
nn = -nn;
dd = -dd;
}
long g = Math.abs(gcd(nn, dd));
if (g > 1) {
nn /= g;
dd /= g;
}
num = nn;
denom = dd;
}
public Frac plus(Frac rhs) {
return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);
}
public Frac unaryMinus() {
return new Frac(-num, denom);
}
public Frac minus(Frac rhs) {
return this.plus(rhs.unaryMinus());
}
public Frac times(Frac rhs) {
return new Frac(this.num * rhs.num, this.denom * rhs.denom);
}
@Override
public int compareTo(Frac o) {
double diff = toDouble() - o.toDouble();
return Double.compare(diff, 0.0);
}
@Override
public boolean equals(Object obj) {
return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;
}
@Override
public String toString() {
if (denom == 1) {
return Long.toString(num);
}
return String.format("%d/%d", num, denom);
}
public double toDouble() {
return (double) num / denom;
}
public BigDecimal toBigDecimal() {
return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);
}
}
private static Frac bernoulli(int n) {
if (n < 0) throw new IllegalArgumentException("n may not be negative or zero");
Frac[] a = new Frac[n + 1];
Arrays.fill(a, Frac.ZERO);
for (int m = 0; m <= n; ++m) {
a[m] = new Frac(1, m + 1);
for (int j = m; j >= 1; --j) {
a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));
}
}
if (n != 1) return a[0];
return a[0].unaryMinus();
}
private static long binomial(int n, int k) {
if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();
if (n == 0 || k == 0) return 1;
long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);
long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);
return num / den;
}
private static Frac[] faulhaberTriangle(int p) {
Frac[] coeffs = new Frac[p + 1];
Arrays.fill(coeffs, Frac.ZERO);
Frac q = new Frac(1, p + 1);
int sign = -1;
for (int j = 0; j <= p; ++j) {
sign *= -1;
coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));
}
return coeffs;
}
public static void main(String[] args) {
for (int i = 0; i <= 9; ++i) {
Frac[] coeffs = faulhaberTriangle(i);
for (Frac coeff : coeffs) {
System.out.printf("%5s ", coeff);
}
System.out.println();
}
System.out.println();
int k = 17;
Frac[] cc = faulhaberTriangle(k);
int n = 1000;
BigDecimal nn = BigDecimal.valueOf(n);
BigDecimal np = BigDecimal.ONE;
BigDecimal sum = BigDecimal.ZERO;
for (Frac c : cc) {
np = np.multiply(nn);
sum = sum.add(np.multiply(c.toBigDecimal()));
}
System.out.println(sum.toBigInteger());
}
}
| class Frac
attr_accessor:num
attr_accessor:denom
def initialize(n,d)
if d == 0 then
raise ArgumentError.new('d cannot be zero')
end
nn = n
dd = d
if nn == 0 then
dd = 1
elsif dd < 0 then
nn = -nn
dd = -dd
end
g = nn.abs.gcd(dd.abs)
if g > 1 then
nn = nn / g
dd = dd / g
end
@num = nn
@denom = dd
end
def to_s
if self.denom == 1 then
return self.num.to_s
else
return "%d/%d" % [self.num, self.denom]
end
end
def -@
return Frac.new(-self.num, self.denom)
end
def +(rhs)
return Frac.new(self.num * rhs.denom + self.denom * rhs.num, rhs.denom * self.denom)
end
def -(rhs)
return Frac.new(self.num * rhs.denom - self.denom * rhs.num, rhs.denom * self.denom)
end
def *(rhs)
return Frac.new(self.num * rhs.num, rhs.denom * self.denom)
end
end
FRAC_ZERO = Frac.new(0, 1)
FRAC_ONE = Frac.new(1, 1)
def bernoulli(n)
if n < 0 then
raise ArgumentError.new('n cannot be negative')
end
a = Array.new(n + 1)
a[0] = FRAC_ZERO
for m in 0 .. n do
a[m] = Frac.new(1, m + 1)
m.downto(1) do |j|
a[j - 1] = (a[j - 1] - a[j]) * Frac.new(j, 1)
end
end
if n != 1 then
return a[0]
end
return -a[0]
end
def binomial(n, k)
if n < 0 then
raise ArgumentError.new('n cannot be negative')
end
if k < 0 then
raise ArgumentError.new('k cannot be negative')
end
if n < k then
raise ArgumentError.new('n cannot be less than k')
end
if n == 0 or k == 0 then
return 1
end
num = 1
for i in k + 1 .. n do
num = num * i
end
den = 1
for i in 2 .. n - k do
den = den * i
end
return num / den
end
def faulhaberTriangle(p)
coeffs = Array.new(p + 1)
coeffs[0] = FRAC_ZERO
q = Frac.new(1, p + 1)
sign = -1
for j in 0 .. p do
sign = -sign
coeffs[p - j] = q * Frac.new(sign, 1) * Frac.new(binomial(p + 1, j), 1) * bernoulli(j)
end
return coeffs
end
def main
for i in 0 .. 9 do
coeffs = faulhaberTriangle(i)
coeffs.each do |coeff|
print "%5s " % [coeff]
end
puts
end
end
main()
|
Transform the following Java implementation into Ruby, maintaining the same output and logic. | import java.math.BigInteger;
import java.util.Arrays;
class Test {
final static int nMax = 250;
final static int nBranches = 4;
static BigInteger[] rooted = new BigInteger[nMax + 1];
static BigInteger[] unrooted = new BigInteger[nMax + 1];
static BigInteger[] c = new BigInteger[nBranches];
static void tree(int br, int n, int l, int inSum, BigInteger cnt) {
int sum = inSum;
for (int b = br + 1; b <= nBranches; b++) {
sum += n;
if (sum > nMax || (l * 2 >= sum && b >= nBranches))
return;
BigInteger tmp = rooted[n];
if (b == br + 1) {
c[br] = tmp.multiply(cnt);
} else {
c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));
c[br] = c[br].divide(BigInteger.valueOf(b - br));
}
if (l * 2 < sum)
unrooted[sum] = unrooted[sum].add(c[br]);
if (b < nBranches)
rooted[sum] = rooted[sum].add(c[br]);
for (int m = n - 1; m > 0; m--)
tree(b, m, l, sum, c[br]);
}
}
static void bicenter(int s) {
if ((s & 1) == 0) {
BigInteger tmp = rooted[s / 2];
tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);
unrooted[s] = unrooted[s].add(tmp.shiftRight(1));
}
}
public static void main(String[] args) {
Arrays.fill(rooted, BigInteger.ZERO);
Arrays.fill(unrooted, BigInteger.ZERO);
rooted[0] = rooted[1] = BigInteger.ONE;
unrooted[0] = unrooted[1] = BigInteger.ONE;
for (int n = 1; n <= nMax; n++) {
tree(0, n, n, 1, BigInteger.ONE);
bicenter(n);
System.out.printf("%d: %s%n", n, unrooted[n]);
}
}
}
| MAX_N = 500
BRANCH = 4
def tree(br, n, l=n, sum=1, cnt=1)
for b in br+1 .. BRANCH
sum += n
return if sum >= MAX_N
return if l * 2 >= sum and b >= BRANCH
if b == br + 1
c = $ra[n] * cnt
else
c = c * ($ra[n] + (b - br - 1)) / (b - br)
end
$unrooted[sum] += c if l * 2 < sum
next if b >= BRANCH
$ra[sum] += c
(1...n).each {|m| tree(b, m, l, sum, c)}
end
end
def bicenter(s)
return if s.odd?
aux = $ra[s / 2]
$unrooted[s] += aux * (aux + 1) / 2
end
$ra = [0] * MAX_N
$unrooted = [0] * MAX_N
$ra[0] = $ra[1] = $unrooted[0] = $unrooted[1] = 1
for n in 1...MAX_N
tree(0, n)
bicenter(n)
puts "%d: %d" % [n, $unrooted[n]]
end
|
Preserve the algorithm and functionality while converting the code from Java to Ruby. | import java.math.BigInteger;
import java.util.Arrays;
class Test {
final static int nMax = 250;
final static int nBranches = 4;
static BigInteger[] rooted = new BigInteger[nMax + 1];
static BigInteger[] unrooted = new BigInteger[nMax + 1];
static BigInteger[] c = new BigInteger[nBranches];
static void tree(int br, int n, int l, int inSum, BigInteger cnt) {
int sum = inSum;
for (int b = br + 1; b <= nBranches; b++) {
sum += n;
if (sum > nMax || (l * 2 >= sum && b >= nBranches))
return;
BigInteger tmp = rooted[n];
if (b == br + 1) {
c[br] = tmp.multiply(cnt);
} else {
c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));
c[br] = c[br].divide(BigInteger.valueOf(b - br));
}
if (l * 2 < sum)
unrooted[sum] = unrooted[sum].add(c[br]);
if (b < nBranches)
rooted[sum] = rooted[sum].add(c[br]);
for (int m = n - 1; m > 0; m--)
tree(b, m, l, sum, c[br]);
}
}
static void bicenter(int s) {
if ((s & 1) == 0) {
BigInteger tmp = rooted[s / 2];
tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);
unrooted[s] = unrooted[s].add(tmp.shiftRight(1));
}
}
public static void main(String[] args) {
Arrays.fill(rooted, BigInteger.ZERO);
Arrays.fill(unrooted, BigInteger.ZERO);
rooted[0] = rooted[1] = BigInteger.ONE;
unrooted[0] = unrooted[1] = BigInteger.ONE;
for (int n = 1; n <= nMax; n++) {
tree(0, n, n, 1, BigInteger.ONE);
bicenter(n);
System.out.printf("%d: %s%n", n, unrooted[n]);
}
}
}
| MAX_N = 500
BRANCH = 4
def tree(br, n, l=n, sum=1, cnt=1)
for b in br+1 .. BRANCH
sum += n
return if sum >= MAX_N
return if l * 2 >= sum and b >= BRANCH
if b == br + 1
c = $ra[n] * cnt
else
c = c * ($ra[n] + (b - br - 1)) / (b - br)
end
$unrooted[sum] += c if l * 2 < sum
next if b >= BRANCH
$ra[sum] += c
(1...n).each {|m| tree(b, m, l, sum, c)}
end
end
def bicenter(s)
return if s.odd?
aux = $ra[s / 2]
$unrooted[s] += aux * (aux + 1) / 2
end
$ra = [0] * MAX_N
$unrooted = [0] * MAX_N
$ra[0] = $ra[1] = $unrooted[0] = $unrooted[1] = 1
for n in 1...MAX_N
tree(0, n)
bicenter(n)
puts "%d: %d" % [n, $unrooted[n]]
end
|
Rewrite the snippet below in Ruby so it works the same as the original Java code. | import java.util.Arrays;
import java.util.stream.IntStream;
public class FaulhabersFormula {
private static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
private static class Frac implements Comparable<Frac> {
private long num;
private long denom;
public static final Frac ZERO = new Frac(0, 1);
public static final Frac ONE = new Frac(1, 1);
public Frac(long n, long d) {
if (d == 0) throw new IllegalArgumentException("d must not be zero");
long nn = n;
long dd = d;
if (nn == 0) {
dd = 1;
} else if (dd < 0) {
nn = -nn;
dd = -dd;
}
long g = Math.abs(gcd(nn, dd));
if (g > 1) {
nn /= g;
dd /= g;
}
num = nn;
denom = dd;
}
public Frac plus(Frac rhs) {
return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);
}
public Frac unaryMinus() {
return new Frac(-num, denom);
}
public Frac minus(Frac rhs) {
return this.plus(rhs.unaryMinus());
}
public Frac times(Frac rhs) {
return new Frac(this.num * rhs.num, this.denom * rhs.denom);
}
@Override
public int compareTo(Frac o) {
double diff = toDouble() - o.toDouble();
return Double.compare(diff, 0.0);
}
@Override
public boolean equals(Object obj) {
return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;
}
@Override
public String toString() {
if (denom == 1) {
return Long.toString(num);
}
return String.format("%d/%d", num, denom);
}
private double toDouble() {
return (double) num / denom;
}
}
private static Frac bernoulli(int n) {
if (n < 0) throw new IllegalArgumentException("n may not be negative or zero");
Frac[] a = new Frac[n + 1];
Arrays.fill(a, Frac.ZERO);
for (int m = 0; m <= n; ++m) {
a[m] = new Frac(1, m + 1);
for (int j = m; j >= 1; --j) {
a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));
}
}
if (n != 1) return a[0];
return a[0].unaryMinus();
}
private static int binomial(int n, int k) {
if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();
if (n == 0 || k == 0) return 1;
int num = IntStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);
int den = IntStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);
return num / den;
}
private static void faulhaber(int p) {
System.out.printf("%d : ", p);
Frac q = new Frac(1, p + 1);
int sign = -1;
for (int j = 0; j <= p; ++j) {
sign *= -1;
Frac coeff = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));
if (Frac.ZERO.equals(coeff)) continue;
if (j == 0) {
if (!Frac.ONE.equals(coeff)) {
if (Frac.ONE.unaryMinus().equals(coeff)) {
System.out.print("-");
} else {
System.out.print(coeff);
}
}
} else {
if (Frac.ONE.equals(coeff)) {
System.out.print(" + ");
} else if (Frac.ONE.unaryMinus().equals(coeff)) {
System.out.print(" - ");
} else if (coeff.compareTo(Frac.ZERO) > 0) {
System.out.printf(" + %s", coeff);
} else {
System.out.printf(" - %s", coeff.unaryMinus());
}
}
int pwr = p + 1 - j;
if (pwr > 1)
System.out.printf("n^%d", pwr);
else
System.out.print("n");
}
System.out.println();
}
public static void main(String[] args) {
for (int i = 0; i <= 9; ++i) {
faulhaber(i);
}
}
}
| def binomial(n,k)
if n < 0 or k < 0 or n < k then
return -1
end
if n == 0 or k == 0 then
return 1
end
num = 1
for i in k+1 .. n do
num = num * i
end
denom = 1
for i in 2 .. n-k do
denom = denom * i
end
return num / denom
end
def bernoulli(n)
if n < 0 then
raise "n cannot be less than zero"
end
a = Array.new(16)
for m in 0 .. n do
a[m] = Rational(1, m + 1)
for j in m.downto(1) do
a[j-1] = (a[j-1] - a[j]) * Rational(j)
end
end
if n != 1 then
return a[0]
end
return -a[0]
end
def faulhaber(p)
print("%d : " % [p])
q = Rational(1, p + 1)
sign = -1
for j in 0 .. p do
sign = -1 * sign
coeff = q * Rational(sign) * Rational(binomial(p+1, j)) * bernoulli(j)
if coeff == 0 then
next
end
if j == 0 then
if coeff != 1 then
if coeff == -1 then
print "-"
else
print coeff
end
end
else
if coeff == 1 then
print " + "
elsif coeff == -1 then
print " - "
elsif 0 < coeff then
print " + "
print coeff
else
print " - "
print -coeff
end
end
pwr = p + 1 - j
if pwr > 1 then
print "n^%d" % [pwr]
else
print "n"
end
end
print "\n"
end
def main
for i in 0 .. 9 do
faulhaber(i)
end
end
main()
|
Write the same algorithm in Ruby as shown in this Java implementation. | import java.io.IOException;
import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
public class LdapSearchDemo {
public static void main(String[] args) throws IOException, LdapException, CursorException {
new LdapSearchDemo().demonstrateSearch();
}
private void demonstrateSearch() throws IOException, LdapException, CursorException {
try (LdapConnection conn = new LdapNetworkConnection("localhost", 11389)) {
conn.bind("uid=admin,ou=system", "********");
search(conn, "*mil*");
conn.unBind();
}
}
private void search(LdapConnection connection, String uid) throws LdapException, CursorException {
String baseDn = "ou=users,o=mojo";
String filter = "(&(objectClass=person)(&(uid=" + uid + ")))";
SearchScope scope = SearchScope.SUBTREE;
String[] attributes = {"dn", "cn", "sn", "uid"};
int ksearch = 0;
EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);
while (cursor.next()) {
ksearch++;
Entry entry = cursor.get();
System.out.printf("Search entry %d = %s%n", ksearch, entry);
}
}
}
| require 'rubygems'
require 'net/ldap'
ldap = Net::LDAP.new(:host => 'hostname', :base => 'base')
ldap.authenticate('bind_dn', 'bind_pass')
filter = Net::LDAP::Filter.pres('objectclass')
filter &= Net::LDAP::Filter.eq('sn','Jackman')
filter = Net::LDAP::Filter.construct('(&(objectclass=*)(sn=Jackman))')
results = ldap.search(:filter => filter)
puts results[0][:sn]
|
Convert this Java block to Ruby, preserving its control flow and logic. | public class PrimeConspiracy {
public static void main(String[] args) {
final int limit = 1000_000;
final int sieveLimit = 15_500_000;
int[][] buckets = new int[10][10];
int prevDigit = 2;
boolean[] notPrime = sieve(sieveLimit);
for (int n = 3, primeCount = 1; primeCount < limit; n++) {
if (notPrime[n])
continue;
int digit = n % 10;
buckets[prevDigit][digit]++;
prevDigit = digit;
primeCount++;
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (buckets[i][j] != 0) {
System.out.printf("%d -> %d : %2f%n", i,
j, buckets[i][j] / (limit / 100.0));
}
}
}
}
public static boolean[] sieve(int limit) {
boolean[] composite = new boolean[limit];
composite[0] = composite[1] = true;
int max = (int) Math.sqrt(limit);
for (int n = 2; n <= max; n++) {
if (!composite[n]) {
for (int k = n * n; k < limit; k += n) {
composite[k] = true;
}
}
}
return composite;
}
}
| require "prime"
def prime_conspiracy(m)
conspiracy = Hash.new(0)
Prime.take(m).map{|n| n%10}.each_cons(2){|a,b| conspiracy[[a,b]] += 1}
puts "
conspiracy.sort.each do |(a,b),v|
puts "%d → %d count:%10d frequency:%7.4f %" % [a, b, v, 100.0*v/m]
end
end
prime_conspiracy(1_000_000)
|
Convert this Java block to Ruby, preserving its control flow and logic. | import java.util.ArrayList;
import java.util.List;
public class ListRootedTrees {
private static final List<Long> TREE_LIST = new ArrayList<>();
private static final List<Integer> OFFSET = new ArrayList<>();
static {
for (int i = 0; i < 32; i++) {
if (i == 1) {
OFFSET.add(1);
} else {
OFFSET.add(0);
}
}
}
private static void append(long t) {
TREE_LIST.add(1 | (t << 1));
}
private static void show(long t, int l) {
while (l-- > 0) {
if (t % 2 == 1) {
System.out.print('(');
} else {
System.out.print(')');
}
t = t >> 1;
}
}
private static void listTrees(int n) {
for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) {
show(TREE_LIST.get(i), n * 2);
System.out.println();
}
}
private static void assemble(int n, long t, int sl, int pos, int rem) {
if (rem == 0) {
append(t);
return;
}
var pp = pos;
var ss = sl;
if (sl > rem) {
ss = rem;
pp = OFFSET.get(ss);
} else if (pp >= OFFSET.get(ss + 1)) {
ss--;
if (ss == 0) {
return;
}
pp = OFFSET.get(ss);
}
assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss);
assemble(n, t, ss, pp + 1, rem);
}
private static void makeTrees(int n) {
if (OFFSET.get(n + 1) != 0) {
return;
}
if (n > 0) {
makeTrees(n - 1);
}
assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1);
OFFSET.set(n + 1, TREE_LIST.size());
}
private static void test(int n) {
if (n < 1 || n > 12) {
throw new IllegalArgumentException("Argument must be between 1 and 12");
}
append(0);
makeTrees(n);
System.out.printf("Number of %d-trees: %d\n", n, OFFSET.get(n + 1) - OFFSET.get(n));
listTrees(n);
}
public static void main(String[] args) {
test(5);
}
}
| TREE_LIST = []
OFFSET = []
for i in 0..31
if i == 1 then
OFFSET << 1
else
OFFSET << 0
end
end
def append(t)
TREE_LIST << (1 | (t << 1))
end
def show(t, l)
while l > 0
l = l - 1
if t % 2 == 1 then
print '('
else
print ')'
end
t = t >> 1
end
end
def listTrees(n)
for i in OFFSET[n] .. OFFSET[n + 1] - 1
show(TREE_LIST[i], n * 2)
print "\n"
end
end
def assemble(n, t, sl, pos, rem)
if rem == 0 then
append(t)
return
end
if sl > rem then
sl = rem
pos = OFFSET[sl]
elsif pos >= OFFSET[sl + 1] then
sl = sl - 1
if sl == 0 then
return
end
pos = OFFSET[sl]
end
assemble(n, t << (2 * sl) | TREE_LIST[pos], sl, pos, rem - sl)
assemble(n, t, sl, pos + 1, rem)
end
def makeTrees(n)
if OFFSET[n + 1] != 0 then
return
end
if n > 0 then
makeTrees(n - 1)
end
assemble(n, 0, n - 1, OFFSET[n - 1], n - 1)
OFFSET[n + 1] = TREE_LIST.length()
end
def test(n)
if n < 1 || n > 12 then
raise ArgumentError.new("Argument must be between 1 and 12")
end
append(0)
makeTrees(n)
print "Number of %d-trees: %d\n" % [n, OFFSET[n + 1] - OFFSET[n]]
listTrees(n)
end
test(5)
|
Translate this program into Ruby but keep the logic exactly as in Java. | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class LuckyNumbers {
private static int MAX = 200000;
private static List<Integer> luckyEven = luckyNumbers(MAX, true);
private static List<Integer> luckyOdd = luckyNumbers(MAX, false);
public static void main(String[] args) {
if ( args.length == 1 || ( args.length == 2 && args[1].compareTo("lucky") == 0 ) ) {
int n = Integer.parseInt(args[0]);
System.out.printf("LuckyNumber(%d) = %d%n", n, luckyOdd.get(n-1));
}
else if ( args.length == 2 && args[1].compareTo("evenLucky") == 0 ) {
int n = Integer.parseInt(args[0]);
System.out.printf("EvenLuckyNumber(%d) = %d%n", n, luckyEven.get(n-1));
}
else if ( args.length == 2 || args.length == 3 ) {
int j = Integer.parseInt(args[0]);
int k = Integer.parseInt(args[1]);
if ( ( args.length == 2 && k > 0 ) || (args.length == 3 && k > 0 && args[2].compareTo("lucky") == 0 ) ) {
System.out.printf("LuckyNumber(%d) through LuckyNumber(%d) = %s%n", j, k, luckyOdd.subList(j-1, k));
}
else if ( args.length == 3 && k > 0 && args[2].compareTo("evenLucky") == 0 ) {
System.out.printf("EvenLuckyNumber(%d) through EvenLuckyNumber(%d) = %s%n", j, k, luckyEven.subList(j-1, k));
}
else if ( ( args.length == 2 && k < 0 ) || (args.length == 3 && k < 0 && args[2].compareTo("lucky") == 0 ) ) {
int n = Collections.binarySearch(luckyOdd, j);
int m = Collections.binarySearch(luckyOdd, -k);
System.out.printf("Lucky Numbers in the range %d to %d inclusive = %s%n", j, -k, luckyOdd.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));
}
else if ( args.length == 3 && k < 0 && args[2].compareTo("evenLucky") == 0 ) {
int n = Collections.binarySearch(luckyEven, j);
int m = Collections.binarySearch(luckyEven, -k);
System.out.printf("Even Lucky Numbers in the range %d to %d inclusive = %s%n", j, -k, luckyEven.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));
}
}
}
private static List<Integer> luckyNumbers(int max, boolean even) {
List<Integer> luckyList = new ArrayList<>();
for ( int i = even ? 2 : 1 ; i <= max ; i += 2 ) {
luckyList.add(i);
}
int start = 1;
boolean removed = true;
while ( removed ) {
removed = false;
int increment = luckyList.get(start);
List<Integer> remove = new ArrayList<>();
for ( int i = increment-1 ; i < luckyList.size() ; i += increment ) {
remove.add(0, i);
removed = true;
}
for ( int i : remove ) {
luckyList.remove(i);
}
start++;
}
return luckyList;
}
}
| def generator(even=false, nmax=1000000)
start = even ? 2 : 1
Enumerator.new do |y|
n = 1
ary = [0] + (start..nmax).step(2).to_a
y << ary[n]
while (m = ary[n+=1]) < ary.size
y << m
(m...ary.size).step(m){|i| ary[i]=nil}
ary.compact!
end
ary[n..-1].each{|i| y << i}
raise StopIteration
end
end
def lucky(argv)
j, k = argv[0].to_i, argv[1].to_i
mode = /even/i=~argv[2] ? :'even lucky' : :lucky
seq = generator(mode == :'even lucky')
ord = ->(n){"
if k.zero?
puts "
elsif 0 < k
puts "
"
else
k = -k
ary = []
loop do
case num=seq.next
when 1...j
when j..k then ary << num
else break
end
end
puts "all
"
end
end
if __FILE__ == $0
lucky(ARGV)
end
|
Rewrite the snippet below in Ruby so it works the same as the original Java code. | public class ImaginaryBaseNumber {
private static class Complex {
private Double real, imag;
public Complex(double r, double i) {
this.real = r;
this.imag = i;
}
public Complex(int r, int i) {
this.real = (double) r;
this.imag = (double) i;
}
public Complex add(Complex rhs) {
return new Complex(
real + rhs.real,
imag + rhs.imag
);
}
public Complex times(Complex rhs) {
return new Complex(
real * rhs.real - imag * rhs.imag,
real * rhs.imag + imag * rhs.real
);
}
public Complex times(double rhs) {
return new Complex(
real * rhs,
imag * rhs
);
}
public Complex inv() {
double denom = real * real + imag * imag;
return new Complex(
real / denom,
-imag / denom
);
}
public Complex unaryMinus() {
return new Complex(-real, -imag);
}
public Complex divide(Complex rhs) {
return this.times(rhs.inv());
}
public QuaterImaginary toQuaterImaginary() {
if (real == 0.0 && imag == 0.0) return new QuaterImaginary("0");
int re = real.intValue();
int im = imag.intValue();
int fi = -1;
StringBuilder sb = new StringBuilder();
while (re != 0) {
int rem = re % -4;
re /= -4;
if (rem < 0) {
rem += 4;
re++;
}
sb.append(rem);
sb.append(0);
}
if (im != 0) {
Double f = new Complex(0.0, imag).divide(new Complex(0.0, 2.0)).real;
im = ((Double) Math.ceil(f)).intValue();
f = -4.0 * (f - im);
int index = 1;
while (im != 0) {
int rem = im % -4;
im /= -4;
if (rem < 0) {
rem += 4;
im++;
}
if (index < sb.length()) {
sb.setCharAt(index, (char) (rem + 48));
} else {
sb.append(0);
sb.append(rem);
}
index += 2;
}
fi = f.intValue();
}
sb.reverse();
if (fi != -1) sb.append(".").append(fi);
while (sb.charAt(0) == '0') sb.deleteCharAt(0);
if (sb.charAt(0) == '.') sb.insert(0, '0');
return new QuaterImaginary(sb.toString());
}
@Override
public String toString() {
double real2 = real == -0.0 ? 0.0 : real;
double imag2 = imag == -0.0 ? 0.0 : imag;
String result = imag2 >= 0.0 ? String.format("%.0f + %.0fi", real2, imag2) : String.format("%.0f - %.0fi", real2, -imag2);
result = result.replace(".0 ", " ").replace(".0i", "i").replace(" + 0i", "");
if (result.startsWith("0 + ")) result = result.substring(4);
if (result.startsWith("0 - ")) result = result.substring(4);
return result;
}
}
private static class QuaterImaginary {
private static final Complex TWOI = new Complex(0.0, 2.0);
private static final Complex INVTWOI = TWOI.inv();
private String b2i;
public QuaterImaginary(String b2i) {
if (b2i.equals("") || !b2i.chars().allMatch(c -> "0123.".indexOf(c) > -1) || b2i.chars().filter(c -> c == '.').count() > 1) {
throw new RuntimeException("Invalid Base 2i number");
}
this.b2i = b2i;
}
public Complex toComplex() {
int pointPos = b2i.indexOf(".");
int posLen = pointPos != -1 ? pointPos : b2i.length();
Complex sum = new Complex(0, 0);
Complex prod = new Complex(1, 0);
for (int j = 0; j < posLen; ++j) {
double k = b2i.charAt(posLen - 1 - j) - '0';
if (k > 0.0) sum = sum.add(prod.times(k));
prod = prod.times(TWOI);
}
if (pointPos != -1) {
prod = INVTWOI;
for (int j = posLen + 1; j < b2i.length(); ++j) {
double k = b2i.charAt(j) - '0';
if (k > 0.0) sum = sum.add(prod.times(k));
prod = prod.times(INVTWOI);
}
}
return sum;
}
@Override
public String toString() {
return b2i;
}
}
public static void main(String[] args) {
String fmt = "%4s -> %8s -> %4s";
for (int i = 1; i <= 16; ++i) {
Complex c1 = new Complex(i, 0);
QuaterImaginary qi = c1.toQuaterImaginary();
Complex c2 = qi.toComplex();
System.out.printf(fmt + " ", c1, qi, c2);
c1 = c2.unaryMinus();
qi = c1.toQuaterImaginary();
c2 = qi.toComplex();
System.out.printf(fmt, c1, qi, c2);
System.out.println();
}
System.out.println();
for (int i = 1; i <= 16; ++i) {
Complex c1 = new Complex(0, i);
QuaterImaginary qi = c1.toQuaterImaginary();
Complex c2 = qi.toComplex();
System.out.printf(fmt + " ", c1, qi, c2);
c1 = c2.unaryMinus();
qi = c1.toQuaterImaginary();
c2 = qi.toComplex();
System.out.printf(fmt, c1, qi, c2);
System.out.println();
}
}
}
|
def base2i_decode(qi)
return 0 if qi == '0'
md = qi.match(/^(?<int>[0-3]+)(?:\.(?<frc>[0-3]+))?$/)
raise 'ill-formed quarter-imaginary base value' if !md
ls_pow = md[:frc] ? -(md[:frc].length) : 0
value = 0
(md[:int] + (md[:frc] ? md[:frc] : '')).reverse.each_char.with_index do |dig, inx|
value += dig.to_i * (2i)**(inx + ls_pow)
end
return value
end
def base2i_encode(gi)
odd = gi.imag.to_i.odd?
frac = (gi.imag.to_i != 0)
real = gi.real.to_i
imag = (gi.imag.to_i + 1) / 2
value = ''
phase_real = true
while (real != 0) || (imag != 0)
if phase_real
real, rem = real.divmod(4)
real = -real
else
imag, rem = imag.divmod(4)
imag = -imag
end
value.prepend(rem.to_s)
phase_real = !phase_real
end
value = '0' if value == ''
value.concat(odd ? '.2' : '.0') if frac
return value
end
|
Write the same algorithm in Ruby as shown in this Java implementation. | import static java.lang.Math.*;
import static java.util.Arrays.stream;
import java.util.Locale;
import java.util.function.DoubleSupplier;
import static java.util.stream.Collectors.joining;
import java.util.stream.DoubleStream;
import static java.util.stream.IntStream.range;
public class Test implements DoubleSupplier {
private double mu, sigma;
private double[] state = new double[2];
private int index = state.length;
Test(double m, double s) {
mu = m;
sigma = s;
}
static double[] meanStdDev(double[] numbers) {
if (numbers.length == 0)
return new double[]{0.0, 0.0};
double sx = 0.0, sxx = 0.0;
long n = 0;
for (double x : numbers) {
sx += x;
sxx += pow(x, 2);
n++;
}
return new double[]{sx / n, pow((n * sxx - pow(sx, 2)), 0.5) / n};
}
static String replicate(int n, String s) {
return range(0, n + 1).mapToObj(i -> s).collect(joining());
}
static void showHistogram01(double[] numbers) {
final int maxWidth = 50;
long[] bins = new long[10];
for (double x : numbers)
bins[(int) (x * bins.length)]++;
double maxFreq = stream(bins).max().getAsLong();
for (int i = 0; i < bins.length; i++)
System.out.printf(" %3.1f: %s%n", i / (double) bins.length,
replicate((int) (bins[i] / maxFreq * maxWidth), "*"));
System.out.println();
}
@Override
public double getAsDouble() {
index++;
if (index >= state.length) {
double r = sqrt(-2 * log(random())) * sigma;
double x = 2 * PI * random();
state = new double[]{mu + r * sin(x), mu + r * cos(x)};
index = 0;
}
return state[index];
}
public static void main(String[] args) {
Locale.setDefault(Locale.US);
double[] data = DoubleStream.generate(new Test(0.0, 0.5)).limit(100_000)
.toArray();
double[] res = meanStdDev(data);
System.out.printf("Mean: %8.6f, SD: %8.6f%n", res[0], res[1]);
showHistogram01(stream(data).map(a -> max(0.0, min(0.9999, a / 3 + 0.5)))
.toArray());
}
}
|
class NormalFromUniform
def initialize()
@next = nil
end
def rand()
if @next
retval, @next = @next, nil
return retval
else
u = v = s = nil
loop do
u = Random.rand(-1.0..1.0)
v = Random.rand(-1.0..1.0)
s = u**2 + v**2
break if (s > 0.0) && (s <= 1.0)
end
f = Math.sqrt(-2.0 * Math.log(s) / s)
@next = v * f
return u * f
end
end
end
|
Write the same algorithm in Ruby as shown in this Java implementation. | import java.util.Arrays;
import static java.util.Arrays.stream;
import java.util.concurrent.*;
public class VogelsApproximationMethod {
final static int[] demand = {30, 20, 70, 30, 60};
final static int[] supply = {50, 60, 50, 50};
final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},
{19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};
final static int nRows = supply.length;
final static int nCols = demand.length;
static boolean[] rowDone = new boolean[nRows];
static boolean[] colDone = new boolean[nCols];
static int[][] result = new int[nRows][nCols];
static ExecutorService es = Executors.newFixedThreadPool(2);
public static void main(String[] args) throws Exception {
int supplyLeft = stream(supply).sum();
int totalCost = 0;
while (supplyLeft > 0) {
int[] cell = nextCell();
int r = cell[0];
int c = cell[1];
int quantity = Math.min(demand[c], supply[r]);
demand[c] -= quantity;
if (demand[c] == 0)
colDone[c] = true;
supply[r] -= quantity;
if (supply[r] == 0)
rowDone[r] = true;
result[r][c] = quantity;
supplyLeft -= quantity;
totalCost += quantity * costs[r][c];
}
stream(result).forEach(a -> System.out.println(Arrays.toString(a)));
System.out.println("Total cost: " + totalCost);
es.shutdown();
}
static int[] nextCell() throws Exception {
Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true));
Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false));
int[] res1 = f1.get();
int[] res2 = f2.get();
if (res1[3] == res2[3])
return res1[2] < res2[2] ? res1 : res2;
return (res1[3] > res2[3]) ? res2 : res1;
}
static int[] diff(int j, int len, boolean isRow) {
int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
int minP = -1;
for (int i = 0; i < len; i++) {
if (isRow ? colDone[i] : rowDone[i])
continue;
int c = isRow ? costs[j][i] : costs[i][j];
if (c < min1) {
min2 = min1;
min1 = c;
minP = i;
} else if (c < min2)
min2 = c;
}
return new int[]{min2 - min1, min1, minP};
}
static int[] maxPenalty(int len1, int len2, boolean isRow) {
int md = Integer.MIN_VALUE;
int pc = -1, pm = -1, mc = -1;
for (int i = 0; i < len1; i++) {
if (isRow ? rowDone[i] : colDone[i])
continue;
int[] res = diff(i, len2, isRow);
if (res[0] > md) {
md = res[0];
pm = i;
mc = res[1];
pc = res[2];
}
}
return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md};
}
}
|
COSTS = {W: {A: 16, B: 16, C: 13, D: 22, E: 17},
X: {A: 14, B: 14, C: 13, D: 19, E: 15},
Y: {A: 19, B: 19, C: 20, D: 23, E: 50},
Z: {A: 50, B: 12, C: 50, D: 15, E: 11}}
demand = {A: 30, B: 20, C: 70, D: 30, E: 60}
supply = {W: 50, X: 60, Y: 50, Z: 50}
COLS = demand.keys
res = {}; COSTS.each_key{|k| res[k] = Hash.new(0)}
g = {}; supply.each_key{|x| g[x] = COSTS[x].keys.sort_by{|g| COSTS[x][g]}}
demand.each_key{|x| g[x] = COSTS.keys.sort_by{|g| COSTS[g][x]}}
until g.empty?
d = demand.collect{|x,y| [x, z = COSTS[g[x][0]][x], g[x][1] ? COSTS[g[x][1]][x] - z : z]}
dmax = d.max_by{|n| n[2]}
d = d.select{|x| x[2] == dmax[2]}.min_by{|n| n[1]}
s = supply.collect{|x,y| [x, z = COSTS[x][g[x][0]], g[x][1] ? COSTS[x][g[x][1]] - z : z]}
dmax = s.max_by{|n| n[2]}
s = s.select{|x| x[2] == dmax[2]}.min_by{|n| n[1]}
t,f = d[2]==s[2] ? [s[1], d[1]] : [d[2],s[2]]
d,s = t > f ? [d[0],g[d[0]][0]] : [g[s[0]][0],s[0]]
v = [supply[s], demand[d]].min
res[s][d] += v
demand[d] -= v
if demand[d] == 0 then
supply.reject{|k, n| n == 0}.each_key{|x| g[x].delete(d)}
g.delete(d)
demand.delete(d)
end
supply[s] -= v
if supply[s] == 0 then
demand.reject{|k, n| n == 0}.each_key{|x| g[x].delete(s)}
g.delete(s)
supply.delete(s)
end
end
COLS.each{|n| print "\t", n}
puts
cost = 0
COSTS.each_key do |g|
print g, "\t"
COLS.each do |n|
y = res[g][n]
print y if y != 0
cost += y * COSTS[g][n]
print "\t"
end
puts
end
print "\n\nTotal Cost = ", cost
|
Write a version of this Java function in Ruby with identical behavior. | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class MinimumNumberOnlyZeroAndOne {
public static void main(String[] args) {
for ( int n : getTestCases() ) {
BigInteger result = getA004290(n);
System.out.printf("A004290(%d) = %s = %s * %s%n", n, result, n, result.divide(BigInteger.valueOf(n)));
}
}
private static List<Integer> getTestCases() {
List<Integer> testCases = new ArrayList<>();
for ( int i = 1 ; i <= 10 ; i++ ) {
testCases.add(i);
}
for ( int i = 95 ; i <= 105 ; i++ ) {
testCases.add(i);
}
for (int i : new int[] {297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878} ) {
testCases.add(i);
}
return testCases;
}
private static BigInteger getA004290(int n) {
if ( n == 1 ) {
return BigInteger.valueOf(1);
}
int[][] L = new int[n][n];
for ( int i = 2 ; i < n ; i++ ) {
L[0][i] = 0;
}
L[0][0] = 1;
L[0][1] = 1;
int m = 0;
BigInteger ten = BigInteger.valueOf(10);
BigInteger nBi = BigInteger.valueOf(n);
while ( true ) {
m++;
if ( L[m-1][mod(ten.pow(m).negate(), nBi).intValue()] == 1 ) {
break;
}
L[m][0] = 1;
for ( int k = 1 ; k < n ; k++ ) {
L[m][k] = Math.max(L[m-1][k], L[m-1][mod(BigInteger.valueOf(k).subtract(ten.pow(m)), nBi).intValue()]);
}
}
BigInteger r = ten.pow(m);
BigInteger k = mod(r.negate(), nBi);
for ( int j = m-1 ; j >= 1 ; j-- ) {
if ( L[j-1][k.intValue()] == 0 ) {
r = r.add(ten.pow(j));
k = mod(k.subtract(ten.pow(j)), nBi);
}
}
if ( k.compareTo(BigInteger.ONE) == 0 ) {
r = r.add(BigInteger.ONE);
}
return r;
}
private static BigInteger mod(BigInteger m, BigInteger n) {
BigInteger result = m.mod(n);
if ( result.compareTo(BigInteger.ZERO) < 0 ) {
result = result.add(n);
}
return result;
}
@SuppressWarnings("unused")
private static int mod(int m, int n) {
int result = m % n;
if ( result < 0 ) {
result += n;
}
return result;
}
@SuppressWarnings("unused")
private static int pow(int base, int exp) {
return (int) Math.pow(base, exp);
}
}
| def mod(m, n)
result = m % n
if result < 0 then
result = result + n
end
return result
end
def getA004290(n)
if n == 1 then
return 1
end
arr = Array.new(n) { Array.new(n, 0) }
arr[0][0] = 1
arr[0][1] = 1
m = 0
while true
m = m + 1
if arr[m - 1][mod(-10 ** m, n)] == 1 then
break
end
arr[m][0] = 1
for k in 1 .. n - 1
arr[m][k] = [arr[m - 1][k], arr[m - 1][mod(k - 10 ** m, n)]].max
end
end
r = 10 ** m
k = mod(-r, n)
(m - 1).downto(1) { |j|
if arr[j - 1][k] == 0 then
r = r + 10 ** j
k = mod(k - 10 ** j, n)
end
}
if k == 1 then
r = r + 1
end
return r
end
testCases = Array(1 .. 10)
testCases.concat(Array(95 .. 105))
testCases.concat([297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878])
for n in testCases
result = getA004290(n)
print "A004290(%d) = %d = %d * %d\n" % [n, result, n, result / n]
end
|
Produce a language-to-language conversion: from Java to Ruby, same semantics. | public class MagicSquareSinglyEven {
public static void main(String[] args) {
int n = 6;
for (int[] row : magicSquareSinglyEven(n)) {
for (int x : row)
System.out.printf("%2s ", x);
System.out.println();
}
System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2);
}
public static int[][] magicSquareOdd(final int n) {
if (n < 3 || n % 2 == 0)
throw new IllegalArgumentException("base must be odd and > 2");
int value = 0;
int gridSize = n * n;
int c = n / 2, r = 0;
int[][] result = new int[n][n];
while (++value <= gridSize) {
result[r][c] = value;
if (r == 0) {
if (c == n - 1) {
r++;
} else {
r = n - 1;
c++;
}
} else if (c == n - 1) {
r--;
c = 0;
} else if (result[r - 1][c + 1] == 0) {
r--;
c++;
} else {
r++;
}
}
return result;
}
static int[][] magicSquareSinglyEven(final int n) {
if (n < 6 || (n - 2) % 4 != 0)
throw new IllegalArgumentException("base must be a positive "
+ "multiple of 4 plus 2");
int size = n * n;
int halfN = n / 2;
int subSquareSize = size / 4;
int[][] subSquare = magicSquareOdd(halfN);
int[] quadrantFactors = {0, 2, 3, 1};
int[][] result = new int[n][n];
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
int quadrant = (r / halfN) * 2 + (c / halfN);
result[r][c] = subSquare[r % halfN][c % halfN];
result[r][c] += quadrantFactors[quadrant] * subSquareSize;
}
}
int nColsLeft = halfN / 2;
int nColsRight = nColsLeft - 1;
for (int r = 0; r < halfN; r++)
for (int c = 0; c < n; c++) {
if (c < nColsLeft || c >= n - nColsRight
|| (c == nColsLeft && r == nColsLeft)) {
if (c == 0 && r == nColsLeft)
continue;
int tmp = result[r][c];
result[r][c] = result[r + halfN][c];
result[r + halfN][c] = tmp;
}
}
return result;
}
}
| def odd_magic_square(n)
n.times.map{|i| n.times.map{|j| n*((i+j+1+n/2)%n) + ((i+2*j-5)%n) + 1} }
end
def single_even_magic_square(n)
raise ArgumentError, "must be even, but not divisible by 4." unless (n-2) % 4 == 0
raise ArgumentError, "2x2 magic square not possible." if n == 2
order = (n-2)/4
odd_square = odd_magic_square(n/2)
to_add = (0..3).map{|f| f*n*n/4}
quarts = to_add.map{|f| odd_square.dup.map{|row|row.map{|el| el+f}} }
sq = []
quarts[0].zip(quarts[2]){|d1,d2| sq << [d1,d2].flatten}
quarts[3].zip(quarts[1]){|d1,d2| sq << [d1,d2].flatten}
sq = sq.transpose
order.times{|i| sq[i].rotate!(n/2)}
swap(sq[0][order], sq[0][-order-1])
swap(sq[order][order], sq[order][-order-1])
(order-1).times{|i| sq[-(i+1)].rotate!(n/2)}
randomize(sq)
end
def swap(a,b)
a,b = b,a
end
def randomize(square)
square.shuffle.transpose.shuffle
end
def to_string(square)
n = square.size
fmt = "%
square.inject(""){|str,row| str << fmt % row << "\n"}
end
puts to_string(single_even_magic_square(6))
|
Generate a Ruby translation of this Java snippet without changing its computational steps. | import java.util.ArrayList;
import java.util.List;
public class WeirdNumbers {
public static void main(String[] args) {
int n = 2;
for ( int count = 1 ; count <= 25 ; n += 2 ) {
if ( isWeird(n) ) {
System.out.printf("w(%d) = %d%n", count, n);
count++;
}
}
}
private static boolean isWeird(int n) {
List<Integer> properDivisors = getProperDivisors(n);
return isAbundant(properDivisors, n) && ! isSemiPerfect(properDivisors, n);
}
private static boolean isAbundant(List<Integer> divisors, int n) {
int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();
return divisorSum > n;
}
private static boolean isSemiPerfect(List<Integer> divisors, int sum) {
int size = divisors.size();
boolean subset[][] = new boolean[sum+1][size+1];
for (int i = 0; i <= size; i++) {
subset[0][i] = true;
}
for (int i = 1; i <= sum; i++) {
subset[i][0] = false;
}
for ( int i = 1 ; i <= sum ; i++ ) {
for ( int j = 1 ; j <= size ; j++ ) {
subset[i][j] = subset[i][j-1];
int test = divisors.get(j-1);
if ( i >= test ) {
subset[i][j] = subset[i][j] || subset[i - test][j-1];
}
}
}
return subset[sum][size];
}
private static final List<Integer> getProperDivisors(int number) {
List<Integer> divisors = new ArrayList<Integer>();
long sqrt = (long) Math.sqrt(number);
for ( int i = 1 ; i <= sqrt ; i++ ) {
if ( number % i == 0 ) {
divisors.add(i);
int div = number / i;
if ( div != i && div != number ) {
divisors.add(div);
}
}
}
return divisors;
}
}
| def divisors(n : Int32) : Array(Int32)
divs = [1]
divs2 = [] of Int32
i = 2
while i * i < n
if n % i == 0
j = n // i
divs << i
divs2 << j if i != j
end
i += 1
end
i = divs.size - 1
while i >= 0
divs2 << divs[i]
i -= 1
end
divs2
end
def abundant(n : Int32, divs : Array(Int32)) : Bool
divs.sum > n
end
def semiperfect(n : Int32, divs : Array(Int32)) : Bool
if divs.size > 0
h = divs[0]
t = divs[1..]
return n < h ? semiperfect(n, t) : n == h || semiperfect(n - h, t) || semiperfect(n, t)
end
return false
end
def sieve(limit : Int32) : Array(Bool)
w = Array(Bool).new(limit, false)
i = 2
while i < limit
if !w[i]
divs = divisors i
if !abundant(i, divs)
w[i] = true
elsif semiperfect(i, divs)
j = i
while j < limit
w[j] = true
j += i
end
end
end
i += 2
end
w
end
def main
w = sieve 17000
count = 0
max = 25
print "The first 25 weird numbers are: "
n = 2
while count < max
if !w[n]
print "
count += 1
end
n += 2
end
puts "\n"
end
require "benchmark"
puts Benchmark.measure { main }
|
Rewrite the snippet below in Ruby so it works the same as the original Java code. | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class AsciiArtDiagramConverter {
private static final String TEST = "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| ID |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"|QR| Opcode |AA|TC|RD|RA| Z | RCODE |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| QDCOUNT |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| ANCOUNT |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| NSCOUNT |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| ARCOUNT |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+";
public static void main(String[] args) {
validate(TEST);
display(TEST);
Map<String,List<Integer>> asciiMap = decode(TEST);
displayMap(asciiMap);
displayCode(asciiMap, "78477bbf5496e12e1bf169a4");
}
private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) {
System.out.printf("%nTest string in hex:%n%s%n%n", hex);
String bin = new BigInteger(hex,16).toString(2);
int length = 0;
for ( String code : asciiMap.keySet() ) {
List<Integer> pos = asciiMap.get(code);
length += pos.get(1) - pos.get(0) + 1;
}
while ( length > bin.length() ) {
bin = "0" + bin;
}
System.out.printf("Test string in binary:%n%s%n%n", bin);
System.out.printf("Name Size Bit Pattern%n");
System.out.printf("-------- ----- -----------%n");
for ( String code : asciiMap.keySet() ) {
List<Integer> pos = asciiMap.get(code);
int start = pos.get(0);
int end = pos.get(1);
System.out.printf("%-8s %2d %s%n", code, end-start+1, bin.substring(start, end+1));
}
}
private static void display(String ascii) {
System.out.printf("%nDiagram:%n%n");
for ( String s : TEST.split("\\r\\n") ) {
System.out.println(s);
}
}
private static void displayMap(Map<String,List<Integer>> asciiMap) {
System.out.printf("%nDecode:%n%n");
System.out.printf("Name Size Start End%n");
System.out.printf("-------- ----- ----- -----%n");
for ( String code : asciiMap.keySet() ) {
List<Integer> pos = asciiMap.get(code);
System.out.printf("%-8s %2d %2d %2d%n", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1));
}
}
private static Map<String,List<Integer>> decode(String ascii) {
Map<String,List<Integer>> map = new LinkedHashMap<>();
String[] split = TEST.split("\\r\\n");
int size = split[0].indexOf("+", 1) - split[0].indexOf("+");
int length = split[0].length() - 1;
for ( int i = 1 ; i < split.length ; i += 2 ) {
int barIndex = 1;
String test = split[i];
int next;
while ( barIndex < length && (next = test.indexOf("|", barIndex)) > 0 ) {
List<Integer> startEnd = new ArrayList<>();
startEnd.add((barIndex/size) + (i/2)*(length/size));
startEnd.add(((next-1)/size) + (i/2)*(length/size));
String code = test.substring(barIndex, next).replace(" ", "");
map.put(code, startEnd);
barIndex = next + 1;
}
}
return map;
}
private static void validate(String ascii) {
String[] split = TEST.split("\\r\\n");
if ( split.length % 2 != 1 ) {
throw new RuntimeException("ERROR 1: Invalid number of input lines. Line count = " + split.length);
}
int size = 0;
for ( int i = 0 ; i < split.length ; i++ ) {
String test = split[i];
if ( i % 2 == 0 ) {
if ( ! test.matches("^\\+([-]+\\+)+$") ) {
throw new RuntimeException("ERROR 2: Improper line format. Line = " + test);
}
if ( size == 0 ) {
int firstPlus = test.indexOf("+");
int secondPlus = test.indexOf("+", 1);
size = secondPlus - firstPlus;
}
if ( ((test.length()-1) % size) != 0 ) {
throw new RuntimeException("ERROR 3: Improper line format. Line = " + test);
}
for ( int j = 0 ; j < test.length()-1 ; j += size ) {
if ( test.charAt(j) != '+' ) {
throw new RuntimeException("ERROR 4: Improper line format. Line = " + test);
}
for ( int k = j+1 ; k < j + size ; k++ ) {
if ( test.charAt(k) != '-' ) {
throw new RuntimeException("ERROR 5: Improper line format. Line = " + test);
}
}
}
}
else {
if ( ! test.matches("^\\|(\\s*[A-Za-z]+\\s*\\|)+$") ) {
throw new RuntimeException("ERROR 6: Improper line format. Line = " + test);
}
for ( int j = 0 ; j < test.length()-1 ; j += size ) {
for ( int k = j+1 ; k < j + size ; k++ ) {
if ( test.charAt(k) == '|' ) {
throw new RuntimeException("ERROR 7: Improper line format. Line = " + test);
}
}
}
}
}
}
}
| header = <<HEADER
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
HEADER
Item = Struct.new(:name, :bits, :range)
RE = /\| *\w+ */
i = 0
table = header.scan(RE).map{|m| Item.new( m.delete("^A-Za-z"), b = m.size/3, i...(i += b)) }
teststr = "78477bbf5496e12e1bf169a4"
padding = table.sum(&:bits)
binstr = teststr.hex.to_s(2).rjust(padding, "0")
table.each{|el| p el.values}; puts
table.each{|el| puts "%7s, %2d bits: %s" % [el.name, el.bits, binstr[el.range] ]}
|
Produce a functionally identical Ruby code for the snippet given in Java. | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Peaceful {
enum Piece {
Empty,
Black,
White,
}
public static class Position {
public int x, y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Position) {
Position pos = (Position) obj;
return pos.x == x && pos.y == y;
}
return false;
}
}
private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {
if (m == 0) {
return true;
}
boolean placingBlack = true;
for (int i = 0; i < n; ++i) {
inner:
for (int j = 0; j < n; ++j) {
Position pos = new Position(i, j);
for (Position queen : pBlackQueens) {
if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {
continue inner;
}
}
for (Position queen : pWhiteQueens) {
if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {
continue inner;
}
}
if (placingBlack) {
pBlackQueens.add(pos);
placingBlack = false;
} else {
pWhiteQueens.add(pos);
if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {
return true;
}
pBlackQueens.remove(pBlackQueens.size() - 1);
pWhiteQueens.remove(pWhiteQueens.size() - 1);
placingBlack = true;
}
}
}
if (!placingBlack) {
pBlackQueens.remove(pBlackQueens.size() - 1);
}
return false;
}
private static boolean isAttacking(Position queen, Position pos) {
return queen.x == pos.x
|| queen.y == pos.y
|| Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);
}
private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {
Piece[] board = new Piece[n * n];
Arrays.fill(board, Piece.Empty);
for (Position queen : blackQueens) {
board[queen.x + n * queen.y] = Piece.Black;
}
for (Position queen : whiteQueens) {
board[queen.x + n * queen.y] = Piece.White;
}
for (int i = 0; i < board.length; ++i) {
if ((i != 0) && i % n == 0) {
System.out.println();
}
Piece b = board[i];
if (b == Piece.Black) {
System.out.print("B ");
} else if (b == Piece.White) {
System.out.print("W ");
} else {
int j = i / n;
int k = i - j * n;
if (j % 2 == k % 2) {
System.out.print("• ");
} else {
System.out.print("◦ ");
}
}
}
System.out.println('\n');
}
public static void main(String[] args) {
List<Position> nms = List.of(
new Position(2, 1),
new Position(3, 1),
new Position(3, 2),
new Position(4, 1),
new Position(4, 2),
new Position(4, 3),
new Position(5, 1),
new Position(5, 2),
new Position(5, 3),
new Position(5, 4),
new Position(5, 5),
new Position(6, 1),
new Position(6, 2),
new Position(6, 3),
new Position(6, 4),
new Position(6, 5),
new Position(6, 6),
new Position(7, 1),
new Position(7, 2),
new Position(7, 3),
new Position(7, 4),
new Position(7, 5),
new Position(7, 6),
new Position(7, 7)
);
for (Position nm : nms) {
int m = nm.y;
int n = nm.x;
System.out.printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n);
List<Position> blackQueens = new ArrayList<>();
List<Position> whiteQueens = new ArrayList<>();
if (place(m, n, blackQueens, whiteQueens)) {
printBoard(n, blackQueens, whiteQueens);
} else {
System.out.println("No solution exists.\n");
}
}
}
}
| class Position
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
def ==(other)
self.x == other.x &&
self.y == other.y
end
def to_s
'(%d, %d)' % [@x, @y]
end
def to_str
to_s
end
end
def isAttacking(queen, pos)
return queen.x == pos.x ||
queen.y == pos.y ||
(queen.x - pos.x).abs() == (queen.y - pos.y).abs()
end
def place(m, n, blackQueens, whiteQueens)
if m == 0 then
return true
end
placingBlack = true
for i in 0 .. n-1
for j in 0 .. n-1
catch :inner do
pos = Position.new(i, j)
for queen in blackQueens
if pos == queen || !placingBlack && isAttacking(queen, pos) then
throw :inner
end
end
for queen in whiteQueens
if pos == queen || placingBlack && isAttacking(queen, pos) then
throw :inner
end
end
if placingBlack then
blackQueens << pos
placingBlack = false
else
whiteQueens << pos
if place(m - 1, n, blackQueens, whiteQueens) then
return true
end
blackQueens.pop
whiteQueens.pop
placingBlack = true
end
end
end
end
if !placingBlack then
blackQueens.pop
end
return false
end
def printBoard(n, blackQueens, whiteQueens)
board = Array.new(n) { Array.new(n) { ' ' } }
for i in 0 .. n-1
for j in 0 .. n-1
if i % 2 == j % 2 then
board[i][j] = '•'
else
board[i][j] = '◦'
end
end
end
for queen in blackQueens
board[queen.y][queen.x] = 'B'
end
for queen in whiteQueens
board[queen.y][queen.x] = 'W'
end
for row in board
for cell in row
print cell, ' '
end
print "\n"
end
print "\n"
end
nms = [
[2, 1],
[3, 1], [3, 2],
[4, 1], [4, 2], [4, 3],
[5, 1], [5, 2], [5, 3], [5, 4], [5, 5],
[6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6],
[7, 1], [7, 2], [7, 3], [7, 4], [7, 5], [7, 6], [7, 7]
]
for nm in nms
m = nm[1]
n = nm[0]
print "%d black and %d white queens on a %d x %d board:\n" % [m, m, n, n]
blackQueens = []
whiteQueens = []
if place(m, n, blackQueens, whiteQueens) then
printBoard(n, blackQueens, whiteQueens)
else
print "No solution exists.\n\n"
end
end
|
Change the following Java code into Ruby without altering its purpose. | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class SequenceNthNumberWithExactlyNDivisors {
public static void main(String[] args) {
int max = 45;
smallPrimes(max);
for ( int n = 1; n <= max ; n++ ) {
System.out.printf("A073916(%d) = %s%n", n, OEISA073916(n));
}
}
private static List<Integer> smallPrimes = new ArrayList<>();
private static void smallPrimes(int numPrimes) {
smallPrimes.add(2);
for ( int n = 3, count = 0 ; count < numPrimes ; n += 2 ) {
if ( isPrime(n) ) {
smallPrimes.add(n);
count++;
}
}
}
private static final boolean isPrime(long test) {
if ( test == 2 ) {
return true;
}
if ( test % 2 == 0 ) {
return false;
}
for ( long d = 3 ; d*d <= test ; d += 2 ) {
if ( test % d == 0 ) {
return false;
}
}
return true;
}
private static int getDivisorCount(long n) {
int count = 1;
while ( n % 2 == 0 ) {
n /= 2;
count += 1;
}
for ( long d = 3 ; d*d <= n ; d += 2 ) {
long q = n / d;
long r = n % d;
int dc = 0;
while ( r == 0 ) {
dc += count;
n = q;
q = n / d;
r = n % d;
}
count += dc;
}
if ( n != 1 ) {
count *= 2;
}
return count;
}
private static BigInteger OEISA073916(int n) {
if ( isPrime(n) ) {
return BigInteger.valueOf(smallPrimes.get(n-1)).pow(n - 1);
}
int count = 0;
int result = 0;
for ( int i = 1 ; count < n ; i++ ) {
if ( n % 2 == 1 ) {
int sqrt = (int) Math.sqrt(i);
if ( sqrt*sqrt != i ) {
continue;
}
}
if ( getDivisorCount(i) == n ) {
count++;
result = i;
}
}
return BigInteger.valueOf(result);
}
}
| def isPrime(n)
return false if n < 2
return n == 2 if n % 2 == 0
return n == 3 if n % 3 == 0
k = 5
while k * k <= n
return false if n % k == 0
k = k + 2
end
return true
end
def getSmallPrimes(numPrimes)
smallPrimes = [2]
count = 0
n = 3
while count < numPrimes
if isPrime(n) then
smallPrimes << n
count = count + 1
end
n = n + 2
end
return smallPrimes
end
def getDivisorCount(n)
count = 1
while n % 2 == 0
n = (n / 2).floor
count = count + 1
end
d = 3
while d * d <= n
q = (n / d).floor
r = n % d
dc = 0
while r == 0
dc = dc + count
n = q
q = (n / d).floor
r = n % d
end
count = count + dc
d = d + 2
end
if n != 1 then
count = 2 * count
end
return count
end
MAX = 15
@smallPrimes = getSmallPrimes(MAX)
def OEISA073916(n)
if isPrime(n) then
return @smallPrimes[n - 1] ** (n - 1)
end
count = 0
result = 0
i = 1
while count < n
if n % 2 == 1 then
root = Math.sqrt(i)
if root * root != i then
i = i + 1
next
end
end
if getDivisorCount(i) == n then
count = count + 1
result = i
end
i = i + 1
end
return result
end
n = 1
while n <= MAX
print "A073916(", n, ") = ", OEISA073916(n), "\n"
n = n + 1
end
|
Preserve the algorithm and functionality while converting the code from Java to Ruby. | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class ReadlineInterface {
private static LinkedList<String> histArr = new LinkedList<>();
private static void hist() {
if (histArr.isEmpty()) {
System.out.println("No history");
} else {
histArr.forEach(cmd -> System.out.printf(" - %s\n", cmd));
}
class Crutch {}
histArr.add(Crutch.class.getEnclosingMethod().getName());
}
private static void hello() {
System.out.println("Hello World!");
class Crutch {}
histArr.add(Crutch.class.getEnclosingMethod().getName());
}
private static void help() {
System.out.println("Available commands:");
System.out.println(" hello");
System.out.println(" hist");
System.out.println(" exit");
System.out.println(" help");
class Crutch {}
histArr.add(Crutch.class.getEnclosingMethod().getName());
}
public static void main(String[] args) throws IOException {
Map<String, Runnable> cmdMap = new HashMap<>();
cmdMap.put("help", ReadlineInterface::help);
cmdMap.put("hist", ReadlineInterface::hist);
cmdMap.put("hello", ReadlineInterface::hello);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a command, type help for a listing.");
while (true) {
System.out.print(">");
String line = in.readLine();
if ("exit".equals(line)) {
break;
}
cmdMap.getOrDefault(line, ReadlineInterface::help).run();
}
}
}
| require "readline"
require "abbrev"
commands = %w[search download open help history quit url prev past]
Readline.completion_proc = commands.abbrev.to_proc
while buf = Readline.readline(">", true)
exit if buf.strip == "quit"
p buf
end
|
Change the following Java code into Ruby without altering its purpose. | public class AdditionChains {
private static class Pair {
int f, s;
Pair(int f, int s) {
this.f = f;
this.s = s;
}
}
private static int[] prepend(int n, int[] seq) {
int[] result = new int[seq.length + 1];
result[0] = n;
System.arraycopy(seq, 0, result, 1, seq.length);
return result;
}
private static Pair check_seq(int pos, int[] seq, int n, int min_len) {
if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);
else if (seq[0] == n) return new Pair(pos, 1);
else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);
else return new Pair(min_len, 0);
}
private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {
if (i > pos) return new Pair(min_len, 0);
Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);
Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);
if (res2.f < res1.f) return res2;
else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);
else throw new RuntimeException("Try_perm exception");
}
private static Pair init_try_perm(int x) {
return try_perm(0, 0, new int[]{1}, x, 12);
}
private static void find_brauer(int num) {
Pair res = init_try_perm(num);
System.out.println();
System.out.println("N = " + num);
System.out.println("Minimum length of chains: L(n)= " + res.f);
System.out.println("Number of minimum length Brauer chains: " + res.s);
}
public static void main(String[] args) {
int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};
for (int i : nums) {
find_brauer(i);
}
}
}
| def check_seq(pos, seq, n, min_len)
if pos > min_len or seq[0] > n then
return min_len, 0
elsif seq[0] == n then
return pos, 1
elsif pos < min_len then
return try_perm(0, pos, seq, n, min_len)
else
return min_len, 0
end
end
def try_perm(i, pos, seq, n, min_len)
if i > pos then
return min_len, 0
end
res11, res12 = check_seq(pos + 1, [seq[0] + seq[i]] + seq, n, min_len)
res21, res22 = try_perm(i + 1, pos, seq, n, res11)
if res21 < res11 then
return res21, res22
elsif res21 == res11 then
return res21, res12 + res22
else
raise "try_perm exception"
end
end
def init_try_perm(x)
return try_perm(0, 0, [1], x, 12)
end
def find_brauer(num)
actualMin, brauer = init_try_perm(num)
puts
print "N = ", num, "\n"
print "Minimum length of chains: L(n)= ", actualMin, "\n"
print "Number of minimum length Brauer chains: ", brauer, "\n"
end
def main
nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]
for i in nums do
find_brauer(i)
end
end
main()
|
Ensure the translated Ruby code behaves exactly like the original Java snippet. | import java.math.BigInteger;
public class MontgomeryReduction {
private static final BigInteger ZERO = BigInteger.ZERO;
private static final BigInteger ONE = BigInteger.ONE;
private static final BigInteger TWO = BigInteger.valueOf(2);
public static class Montgomery {
public static final int BASE = 2;
BigInteger m;
BigInteger rrm;
int n;
public Montgomery(BigInteger m) {
if (m.compareTo(BigInteger.ZERO) <= 0 || !m.testBit(0)) {
throw new IllegalArgumentException();
}
this.m = m;
this.n = m.bitLength();
this.rrm = ONE.shiftLeft(n * 2).mod(m);
}
public BigInteger reduce(BigInteger t) {
BigInteger a = t;
for (int i = 0; i < n; i++) {
if (a.testBit(0)) a = a.add(this.m);
a = a.shiftRight(1);
}
if (a.compareTo(m) >= 0) a = a.subtract(this.m);
return a;
}
}
public static void main(String[] args) {
BigInteger m = new BigInteger("750791094644726559640638407699");
BigInteger x1 = new BigInteger("540019781128412936473322405310");
BigInteger x2 = new BigInteger("515692107665463680305819378593");
Montgomery mont = new Montgomery(m);
BigInteger t1 = x1.multiply(mont.rrm);
BigInteger t2 = x2.multiply(mont.rrm);
BigInteger r1 = mont.reduce(t1);
BigInteger r2 = mont.reduce(t2);
BigInteger r = ONE.shiftLeft(mont.n);
System.out.printf("b : %s\n", Montgomery.BASE);
System.out.printf("n : %s\n", mont.n);
System.out.printf("r : %s\n", r);
System.out.printf("m : %s\n", mont.m);
System.out.printf("t1: %s\n", t1);
System.out.printf("t2: %s\n", t2);
System.out.printf("r1: %s\n", r1);
System.out.printf("r2: %s\n", r2);
System.out.println();
System.out.printf("Original x1 : %s\n", x1);
System.out.printf("Recovered from r1 : %s\n", mont.reduce(r1));
System.out.printf("Original x2 : %s\n", x2);
System.out.printf("Recovered from r2 : %s\n", mont.reduce(r2));
System.out.println();
System.out.println("Montgomery computation of x1 ^ x2 mod m :");
BigInteger prod = mont.reduce(mont.rrm);
BigInteger base = mont.reduce(x1.multiply(mont.rrm));
BigInteger exp = x2;
while (exp.bitLength()>0) {
if (exp.testBit(0)) prod=mont.reduce(prod.multiply(base));
exp = exp.shiftRight(1);
base = mont.reduce(base.multiply(base));
}
System.out.println(mont.reduce(prod));
System.out.println();
System.out.println("Library-based computation of x1 ^ x2 mod m :");
System.out.println(x1.modPow(x2, m));
}
}
| func montgomeryReduce(m, a) {
{
a += m if a.is_odd
a >>= 1
} * m.as_bin.len
a % m
}
var m = 750791094644726559640638407699
var t1 = 323165824550862327179367294465482435542970161392400401329100
var r1 = 440160025148131680164261562101
var r2 = 435362628198191204145287283255
var x1 = 540019781128412936473322405310
var x2 = 515692107665463680305819378593
say("Original x1: ", x1)
say("Recovererd from r1: ", montgomeryReduce(m, r1))
say("Original x2: ", x2)
say("Recovererd from r2: ", montgomeryReduce(m, r2))
print("\nMontgomery computation of x1^x2 mod m: ")
var prod = montgomeryReduce(m, t1/x1)
var base = montgomeryReduce(m, t1)
for (var exponent = x2; exponent ; exponent >>= 1) {
prod = montgomeryReduce(m, prod * base) if exponent.is_odd
base = montgomeryReduce(m, base * base)
}
say(montgomeryReduce(m, prod))
say("Library-based computation of x1^x2 mod m: ", x1.powmod(x2, m))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.