Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Ensure the translated Ruby code behaves exactly like the original Java snippet. | import java.util.*;
public class Sokoban {
String destBoard, currBoard;
int playerX, playerY, nCols;
Sokoban(String[] board) {
nCols = board[0].length();
StringBuilder destBuf = new StringBuilder();
StringBuilder currBuf = new StringBuilder();
for (int r = 0; r < board.length; r++) {
for (int c = 0; c < nCols; c++) {
char ch = board[r].charAt(c);
destBuf.append(ch != '$' && ch != '@' ? ch : ' ');
currBuf.append(ch != '.' ? ch : ' ');
if (ch == '@') {
this.playerX = c;
this.playerY = r;
}
}
}
destBoard = destBuf.toString();
currBoard = currBuf.toString();
}
String move(int x, int y, int dx, int dy, String trialBoard) {
int newPlayerPos = (y + dy) * nCols + x + dx;
if (trialBoard.charAt(newPlayerPos) != ' ')
return null;
char[] trial = trialBoard.toCharArray();
trial[y * nCols + x] = ' ';
trial[newPlayerPos] = '@';
return new String(trial);
}
String push(int x, int y, int dx, int dy, String trialBoard) {
int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;
if (trialBoard.charAt(newBoxPos) != ' ')
return null;
char[] trial = trialBoard.toCharArray();
trial[y * nCols + x] = ' ';
trial[(y + dy) * nCols + x + dx] = '@';
trial[newBoxPos] = '$';
return new String(trial);
}
boolean isSolved(String trialBoard) {
for (int i = 0; i < trialBoard.length(); i++)
if ((destBoard.charAt(i) == '.')
!= (trialBoard.charAt(i) == '$'))
return false;
return true;
}
String solve() {
class Board {
String cur, sol;
int x, y;
Board(String s1, String s2, int px, int py) {
cur = s1;
sol = s2;
x = px;
y = py;
}
}
char[][] dirLabels = {{'u', 'U'}, {'r', 'R'}, {'d', 'D'}, {'l', 'L'}};
int[][] dirs = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
Set<String> history = new HashSet<>();
LinkedList<Board> open = new LinkedList<>();
history.add(currBoard);
open.add(new Board(currBoard, "", playerX, playerY));
while (!open.isEmpty()) {
Board item = open.poll();
String cur = item.cur;
String sol = item.sol;
int x = item.x;
int y = item.y;
for (int i = 0; i < dirs.length; i++) {
String trial = cur;
int dx = dirs[i][0];
int dy = dirs[i][1];
if (trial.charAt((y + dy) * nCols + x + dx) == '$') {
if ((trial = push(x, y, dx, dy, trial)) != null) {
if (!history.contains(trial)) {
String newSol = sol + dirLabels[i][1];
if (isSolved(trial))
return newSol;
open.add(new Board(trial, newSol, x + dx, y + dy));
history.add(trial);
}
}
} else if ((trial = move(x, y, dx, dy, trial)) != null) {
if (!history.contains(trial)) {
String newSol = sol + dirLabels[i][0];
open.add(new Board(trial, newSol, x + dx, y + dy));
history.add(trial);
}
}
}
}
return "No solution";
}
public static void main(String[] a) {
String level = "#######,# #,# #,#. # #,#. $$ #,"
+ "#.$$ #,#.# @#,#######";
System.out.println(new Sokoban(level.split(",")).solve());
}
}
| require 'set'
class Sokoban
def initialize(level)
board = level.each_line.map(&:rstrip)
@nrows = board.map(&:size).max
board.map!{|line| line.ljust(@nrows)}
board.each_with_index do |row, r|
row.each_char.with_index do |ch, c|
@px, @py = c, r if ch == '@' or ch == '+'
end
end
@goal = board.join.tr(' .@
.each_char.with_index.select{|ch, c| ch == '.'}
.map(&:last)
@board = board.join.tr(' .@
end
def pos(x, y)
y * @nrows + x
end
def push(x, y, dx, dy, board)
return if board[pos(x+2*dx, y+2*dy)] != ' '
board[pos(x , y )] = ' '
board[pos(x + dx, y + dy)] = '@'
board[pos(x+2*dx, y+2*dy)] = '$'
end
def solved?(board)
@goal.all?{|i| board[i] == '$'}
end
DIRS = [[0, -1, 'u', 'U'], [ 1, 0, 'r', 'R'], [0, 1, 'd', 'D'], [-1, 0, 'l', 'L']]
def solve
queue = [[@board, "", @px, @py]]
visited = Set[@board]
until queue.empty?
current, csol, x, y = queue.shift
for dx, dy, cmove, cpush in DIRS
work = current.dup
case work[pos(x+dx, y+dy)]
when '$'
next unless push(x, y, dx, dy, work)
next unless visited.add?(work)
return csol+cpush if solved?(work)
queue << [work, csol+cpush, x+dx, y+dy]
when ' '
work[pos(x, y)] = ' '
work[pos(x+dx, y+dy)] = '@'
queue << [work, csol+cmove, x+dx, y+dy] if visited.add?(work)
end
end
end
"No solution"
end
end
|
Write a version of this Java function in Ruby with identical behavior. | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ZumkellerNumbers {
public static void main(String[] args) {
int n = 1;
System.out.printf("First 220 Zumkeller numbers:%n");
for ( int count = 1 ; count <= 220 ; n += 1 ) {
if ( isZumkeller(n) ) {
System.out.printf("%3d ", n);
if ( count % 20 == 0 ) {
System.out.printf("%n");
}
count++;
}
}
n = 1;
System.out.printf("%nFirst 40 odd Zumkeller numbers:%n");
for ( int count = 1 ; count <= 40 ; n += 2 ) {
if ( isZumkeller(n) ) {
System.out.printf("%6d", n);
if ( count % 10 == 0 ) {
System.out.printf("%n");
}
count++;
}
}
n = 1;
System.out.printf("%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n");
for ( int count = 1 ; count <= 40 ; n += 2 ) {
if ( n % 5 != 0 && isZumkeller(n) ) {
System.out.printf("%8d", n);
if ( count % 10 == 0 ) {
System.out.printf("%n");
}
count++;
}
}
}
private static boolean isZumkeller(int n) {
if ( n % 18 == 6 || n % 18 == 12 ) {
return true;
}
List<Integer> divisors = getDivisors(n);
int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();
if ( divisorSum % 2 == 1 ) {
return false;
}
int abundance = divisorSum - 2 * n;
if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {
return true;
}
Collections.sort(divisors);
int j = divisors.size() - 1;
int sum = divisorSum/2;
if ( divisors.get(j) > sum ) {
return false;
}
return canPartition(j, divisors, sum, new int[2]);
}
private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {
if ( j < 0 ) {
return true;
}
for ( int i = 0 ; i < 2 ; i++ ) {
if ( buckets[i] + divisors.get(j) <= sum ) {
buckets[i] += divisors.get(j);
if ( canPartition(j-1, divisors, sum, buckets) ) {
return true;
}
buckets[i] -= divisors.get(j);
}
if( buckets[i] == 0 ) {
break;
}
}
return false;
}
private static final List<Integer> getDivisors(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 ) {
divisors.add(div);
}
}
}
return divisors;
}
}
| class Integer
def divisors
res = [1, self]
(2..Integer.sqrt(self)).each do |n|
div, mod = divmod(n)
res << n << div if mod.zero?
end
res.uniq.sort
end
def zumkeller?
divs = divisors
sum = divs.sum
return false unless sum.even? && sum >= self*2
half = sum / 2
max_combi_size = divs.size / 2
1.upto(max_combi_size).any? do |combi_size|
divs.combination(combi_size).any?{|combi| combi.sum == half}
end
end
end
def p_enum(enum, cols = 10, col_width = 8)
enum.each_slice(cols) {|slice| puts "%
end
puts "
p_enum 1.step.lazy.select(&:zumkeller?).take(n), 14, 6
puts "\n
p_enum 1.step(by: 2).lazy.select(&:zumkeller?).take(n)
puts "\n
p_enum 1.step(by: 2).lazy.select{|x| x % 5 > 0 && x.zumkeller?}.take(n)
|
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version. | import java.util.ArrayList;
import java.util.List;
public class SuffixTreeProblem {
private static class Node {
String sub = "";
List<Integer> ch = new ArrayList<>();
}
private static class SuffixTree {
private List<Node> nodes = new ArrayList<>();
public SuffixTree(String str) {
nodes.add(new Node());
for (int i = 0; i < str.length(); ++i) {
addSuffix(str.substring(i));
}
}
private void addSuffix(String suf) {
int n = 0;
int i = 0;
while (i < suf.length()) {
char b = suf.charAt(i);
List<Integer> children = nodes.get(n).ch;
int x2 = 0;
int n2;
while (true) {
if (x2 == children.size()) {
n2 = nodes.size();
Node temp = new Node();
temp.sub = suf.substring(i);
nodes.add(temp);
children.add(n2);
return;
}
n2 = children.get(x2);
if (nodes.get(n2).sub.charAt(0) == b) break;
x2++;
}
String sub2 = nodes.get(n2).sub;
int j = 0;
while (j < sub2.length()) {
if (suf.charAt(i + j) != sub2.charAt(j)) {
int n3 = n2;
n2 = nodes.size();
Node temp = new Node();
temp.sub = sub2.substring(0, j);
temp.ch.add(n3);
nodes.add(temp);
nodes.get(n3).sub = sub2.substring(j);
nodes.get(n).ch.set(x2, n2);
break;
}
j++;
}
i += j;
n = n2;
}
}
public void visualize() {
if (nodes.isEmpty()) {
System.out.println("<empty>");
return;
}
visualize_f(0, "");
}
private void visualize_f(int n, String pre) {
List<Integer> children = nodes.get(n).ch;
if (children.isEmpty()) {
System.out.println("- " + nodes.get(n).sub);
return;
}
System.out.println("┐ " + nodes.get(n).sub);
for (int i = 0; i < children.size() - 1; i++) {
Integer c = children.get(i);
System.out.print(pre + "├─");
visualize_f(c, pre + "│ ");
}
System.out.print(pre + "└─");
visualize_f(children.get(children.size() - 1), pre + " ");
}
}
public static void main(String[] args) {
new SuffixTree("banana$").visualize();
}
}
| func suffix_tree(Str t) {
suffix_tree(^t.len -> map { t.substr(_) })
}
func suffix_tree(a {.len == 1}) {
Hash(a[0] => nil)
}
func suffix_tree(Arr a) {
var h = Hash()
for k,v in (a.group_by { .char(0) }) {
var subtree = suffix_tree(v.map { .substr(1) })
var subkeys = subtree.keys
if (subkeys.len == 1) {
var subk = subkeys[0]
h{k + subk} = subtree{subk}
}
else {
h{k} = subtree
}
}
return h
}
say suffix_tree('banana$')
|
Change the programming language of this snippet from Java to Ruby without modifying what it does. | import java.util.ArrayList;
import java.util.List;
public class SuffixTreeProblem {
private static class Node {
String sub = "";
List<Integer> ch = new ArrayList<>();
}
private static class SuffixTree {
private List<Node> nodes = new ArrayList<>();
public SuffixTree(String str) {
nodes.add(new Node());
for (int i = 0; i < str.length(); ++i) {
addSuffix(str.substring(i));
}
}
private void addSuffix(String suf) {
int n = 0;
int i = 0;
while (i < suf.length()) {
char b = suf.charAt(i);
List<Integer> children = nodes.get(n).ch;
int x2 = 0;
int n2;
while (true) {
if (x2 == children.size()) {
n2 = nodes.size();
Node temp = new Node();
temp.sub = suf.substring(i);
nodes.add(temp);
children.add(n2);
return;
}
n2 = children.get(x2);
if (nodes.get(n2).sub.charAt(0) == b) break;
x2++;
}
String sub2 = nodes.get(n2).sub;
int j = 0;
while (j < sub2.length()) {
if (suf.charAt(i + j) != sub2.charAt(j)) {
int n3 = n2;
n2 = nodes.size();
Node temp = new Node();
temp.sub = sub2.substring(0, j);
temp.ch.add(n3);
nodes.add(temp);
nodes.get(n3).sub = sub2.substring(j);
nodes.get(n).ch.set(x2, n2);
break;
}
j++;
}
i += j;
n = n2;
}
}
public void visualize() {
if (nodes.isEmpty()) {
System.out.println("<empty>");
return;
}
visualize_f(0, "");
}
private void visualize_f(int n, String pre) {
List<Integer> children = nodes.get(n).ch;
if (children.isEmpty()) {
System.out.println("- " + nodes.get(n).sub);
return;
}
System.out.println("┐ " + nodes.get(n).sub);
for (int i = 0; i < children.size() - 1; i++) {
Integer c = children.get(i);
System.out.print(pre + "├─");
visualize_f(c, pre + "│ ");
}
System.out.print(pre + "└─");
visualize_f(children.get(children.size() - 1), pre + " ");
}
}
public static void main(String[] args) {
new SuffixTree("banana$").visualize();
}
}
| func suffix_tree(Str t) {
suffix_tree(^t.len -> map { t.substr(_) })
}
func suffix_tree(a {.len == 1}) {
Hash(a[0] => nil)
}
func suffix_tree(Arr a) {
var h = Hash()
for k,v in (a.group_by { .char(0) }) {
var subtree = suffix_tree(v.map { .substr(1) })
var subkeys = subtree.keys
if (subkeys.len == 1) {
var subk = subkeys[0]
h{k + subk} = subtree{subk}
}
else {
h{k} = subtree
}
}
return h
}
say suffix_tree('banana$')
|
Generate a Ruby translation of this Java snippet without changing its computational steps. | import java.lang.reflect.Field;
public class ListFields {
public int examplePublicField = 42;
private boolean examplePrivateField = true;
public static void main(String[] args) throws IllegalAccessException {
ListFields obj = new ListFields();
Class clazz = obj.getClass();
System.out.println("All public fields (including inherited):");
for (Field f : clazz.getFields()) {
System.out.printf("%s\t%s\n", f, f.get(obj));
}
System.out.println();
System.out.println("All declared fields (excluding inherited):");
for (Field f : clazz.getDeclaredFields()) {
System.out.printf("%s\t%s\n", f, f.get(obj));
}
}
}
| class Foo
@@xyz = nil
def initialize(name, age)
@name, @age = name, age
end
def add_sex(sex)
@sex = sex
end
end
p foo = Foo.new("Angel", 18)
p foo.instance_variables
p foo.instance_variable_defined?(:@age)
p foo.instance_variable_get(:@age)
p foo.instance_variable_set(:@age, 19)
p foo
foo.add_sex(:woman)
p foo.instance_variables
p foo
foo.instance_variable_set(:@bar, nil)
p foo.instance_variables
p Foo.class_variables
p Foo.class_variable_defined?(:@@xyz)
p Foo.class_variable_get(:@@xyz)
p Foo.class_variable_set(:@@xyz, :xyz)
p Foo.class_variable_get(:@@xyz)
p Foo.class_variable_set(:@@abc, 123)
p Foo.class_variables
|
Write a version of this Java function in Ruby with identical behavior. | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Eertree {
public static void main(String[] args) {
List<Node> tree = eertree("eertree");
List<String> result = subPalindromes(tree);
System.out.println(result);
}
private static class Node {
int length;
Map<Character, Integer> edges = new HashMap<>();
int suffix;
public Node(int length) {
this.length = length;
}
public Node(int length, Map<Character, Integer> edges, int suffix) {
this.length = length;
this.edges = edges != null ? edges : new HashMap<>();
this.suffix = suffix;
}
}
private static final int EVEN_ROOT = 0;
private static final int ODD_ROOT = 1;
private static List<Node> eertree(String s) {
List<Node> tree = new ArrayList<>();
tree.add(new Node(0, null, ODD_ROOT));
tree.add(new Node(-1, null, ODD_ROOT));
int suffix = ODD_ROOT;
int n, k;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
for (n = suffix; ; n = tree.get(n).suffix) {
k = tree.get(n).length;
int b = i - k - 1;
if (b >= 0 && s.charAt(b) == c) {
break;
}
}
if (tree.get(n).edges.containsKey(c)) {
suffix = tree.get(n).edges.get(c);
continue;
}
suffix = tree.size();
tree.add(new Node(k + 2));
tree.get(n).edges.put(c, suffix);
if (tree.get(suffix).length == 1) {
tree.get(suffix).suffix = 0;
continue;
}
while (true) {
n = tree.get(n).suffix;
int b = i - tree.get(n).length - 1;
if (b >= 0 && s.charAt(b) == c) {
break;
}
}
tree.get(suffix).suffix = tree.get(n).edges.get(c);
}
return tree;
}
private static List<String> subPalindromes(List<Node> tree) {
List<String> s = new ArrayList<>();
subPalindromes_children(0, "", tree, s);
for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {
String ct = String.valueOf(cm.getKey());
s.add(ct);
subPalindromes_children(cm.getValue(), ct, tree, s);
}
return s;
}
private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {
for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {
Character c = cm.getKey();
Integer m = cm.getValue();
String pl = c + p + c;
s.add(pl);
subPalindromes_children(m, pl, tree, s);
}
}
}
| class Node
def initialize(length, edges = {}, suffix = 0)
@length = length
@edges = edges
@suffix = suffix
end
attr_reader :length
attr_reader :edges
attr_accessor :suffix
end
EVEN_ROOT = 0
ODD_ROOT = 1
def eertree(s)
tree = [
Node.new(0, {}, ODD_ROOT),
Node.new(-1, {}, ODD_ROOT)
]
suffix = ODD_ROOT
s.each_char.with_index { |c, i|
n = suffix
k = 0
loop do
k = tree[n].length
b = i - k - 1
if b >= 0 and s[b] == c then
break
end
n = tree[n].suffix
end
if tree[n].edges.key?(c) then
suffix = tree[n].edges[c]
next
end
suffix = tree.length
tree << Node.new(k + 2)
tree[n].edges[c] = suffix
if tree[suffix].length == 1 then
tree[suffix].suffix = 0
next
end
loop do
n = tree[n].suffix
b = i - tree[n].length - 1
if b >= 0 and s[b] == c then
break
end
end
tree[suffix].suffix = tree[n].edges[c]
}
return tree
end
def subPalindromes(tree)
s = []
children = lambda { |n,p,f|
for c,v in tree[n].edges
m = tree[n].edges[c]
p = c + p + c
s << p
f.call(m, p, f)
end
}
children.call(0, '', children)
for c,n in tree[1].edges
s << c
children.call(n, c, children)
end
return s
end
tree = eertree("eertree")
print subPalindromes(tree), "\n"
|
Maintain the same structure and functionality when rewriting this code in Ruby. | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Eertree {
public static void main(String[] args) {
List<Node> tree = eertree("eertree");
List<String> result = subPalindromes(tree);
System.out.println(result);
}
private static class Node {
int length;
Map<Character, Integer> edges = new HashMap<>();
int suffix;
public Node(int length) {
this.length = length;
}
public Node(int length, Map<Character, Integer> edges, int suffix) {
this.length = length;
this.edges = edges != null ? edges : new HashMap<>();
this.suffix = suffix;
}
}
private static final int EVEN_ROOT = 0;
private static final int ODD_ROOT = 1;
private static List<Node> eertree(String s) {
List<Node> tree = new ArrayList<>();
tree.add(new Node(0, null, ODD_ROOT));
tree.add(new Node(-1, null, ODD_ROOT));
int suffix = ODD_ROOT;
int n, k;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
for (n = suffix; ; n = tree.get(n).suffix) {
k = tree.get(n).length;
int b = i - k - 1;
if (b >= 0 && s.charAt(b) == c) {
break;
}
}
if (tree.get(n).edges.containsKey(c)) {
suffix = tree.get(n).edges.get(c);
continue;
}
suffix = tree.size();
tree.add(new Node(k + 2));
tree.get(n).edges.put(c, suffix);
if (tree.get(suffix).length == 1) {
tree.get(suffix).suffix = 0;
continue;
}
while (true) {
n = tree.get(n).suffix;
int b = i - tree.get(n).length - 1;
if (b >= 0 && s.charAt(b) == c) {
break;
}
}
tree.get(suffix).suffix = tree.get(n).edges.get(c);
}
return tree;
}
private static List<String> subPalindromes(List<Node> tree) {
List<String> s = new ArrayList<>();
subPalindromes_children(0, "", tree, s);
for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {
String ct = String.valueOf(cm.getKey());
s.add(ct);
subPalindromes_children(cm.getValue(), ct, tree, s);
}
return s;
}
private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {
for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {
Character c = cm.getKey();
Integer m = cm.getValue();
String pl = c + p + c;
s.add(pl);
subPalindromes_children(m, pl, tree, s);
}
}
}
| class Node
def initialize(length, edges = {}, suffix = 0)
@length = length
@edges = edges
@suffix = suffix
end
attr_reader :length
attr_reader :edges
attr_accessor :suffix
end
EVEN_ROOT = 0
ODD_ROOT = 1
def eertree(s)
tree = [
Node.new(0, {}, ODD_ROOT),
Node.new(-1, {}, ODD_ROOT)
]
suffix = ODD_ROOT
s.each_char.with_index { |c, i|
n = suffix
k = 0
loop do
k = tree[n].length
b = i - k - 1
if b >= 0 and s[b] == c then
break
end
n = tree[n].suffix
end
if tree[n].edges.key?(c) then
suffix = tree[n].edges[c]
next
end
suffix = tree.length
tree << Node.new(k + 2)
tree[n].edges[c] = suffix
if tree[suffix].length == 1 then
tree[suffix].suffix = 0
next
end
loop do
n = tree[n].suffix
b = i - tree[n].length - 1
if b >= 0 and s[b] == c then
break
end
end
tree[suffix].suffix = tree[n].edges[c]
}
return tree
end
def subPalindromes(tree)
s = []
children = lambda { |n,p,f|
for c,v in tree[n].edges
m = tree[n].edges[c]
p = c + p + c
s << p
f.call(m, p, f)
end
}
children.call(0, '', children)
for c,n in tree[1].edges
s << c
children.call(n, c, children)
end
return s
end
tree = eertree("eertree")
print subPalindromes(tree), "\n"
|
Port the following code from Java to Ruby with equivalent syntax and logic. | import java.math.BigInteger;
import java.util.List;
public class Base58CheckEncoding {
private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
private static final BigInteger BIG0 = BigInteger.ZERO;
private static final BigInteger BIG58 = BigInteger.valueOf(58);
private static String convertToBase58(String hash) {
return convertToBase58(hash, 16);
}
private static String convertToBase58(String hash, int base) {
BigInteger x;
if (base == 16 && hash.substring(0, 2).equals("0x")) {
x = new BigInteger(hash.substring(2), 16);
} else {
x = new BigInteger(hash, base);
}
StringBuilder sb = new StringBuilder();
while (x.compareTo(BIG0) > 0) {
int r = x.mod(BIG58).intValue();
sb.append(ALPHABET.charAt(r));
x = x.divide(BIG58);
}
return sb.reverse().toString();
}
public static void main(String[] args) {
String s = "25420294593250030202636073700053352635053786165627414518";
String b = convertToBase58(s, 10);
System.out.printf("%s -> %s\n", s, b);
List<String> hashes = List.of(
"0x61",
"0x626262",
"0x636363",
"0x73696d706c792061206c6f6e6720737472696e67",
"0x516b6fcd0f",
"0xbf4f89001e670274dd",
"0x572e4794",
"0xecac89cad93923c02321",
"0x10c8511e"
);
for (String hash : hashes) {
String b58 = convertToBase58(hash);
System.out.printf("%-56s -> %s\n", hash, b58);
}
}
}
| ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
nums = [25420294593250030202636073700053352635053786165627414518,
0x61,
0x626262,
0x636363,
0x73696d706c792061206c6f6e6720737472696e67,
0x516b6fcd0f,
0xbf4f89001e670274dd,
0x572e4794,
0xecac89cad93923c02321,
0x10c8511e]
puts nums.map{|n| n.digits(58).reverse.map{|i| ALPHABET[i]}.join}
|
Change the following Java code into Ruby without altering its purpose. | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LatinSquaresInReducedForm {
public static void main(String[] args) {
System.out.printf("Reduced latin squares of order 4:%n");
for ( LatinSquare square : getReducedLatinSquares(4) ) {
System.out.printf("%s%n", square);
}
System.out.printf("Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n");
for ( int n = 1 ; n <= 6 ; n++ ) {
List<LatinSquare> list = getReducedLatinSquares(n);
System.out.printf("Size = %d, %d * %d * %d = %,d%n", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1));
}
}
private static long fact(int n) {
if ( n == 0 ) {
return 1;
}
int prod = 1;
for ( int i = 1 ; i <= n ; i++ ) {
prod *= i;
}
return prod;
}
private static List<LatinSquare> getReducedLatinSquares(int n) {
List<LatinSquare> squares = new ArrayList<>();
squares.add(new LatinSquare(n));
PermutationGenerator permGen = new PermutationGenerator(n);
for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) {
List<LatinSquare> squaresNext = new ArrayList<>();
for ( LatinSquare square : squares ) {
while ( permGen.hasMore() ) {
int[] perm = permGen.getNext();
if ( (perm[0]+1) != (fillRow+1) ) {
continue;
}
boolean permOk = true;
done:
for ( int row = 0 ; row < fillRow ; row++ ) {
for ( int col = 0 ; col < n ; col++ ) {
if ( square.get(row, col) == (perm[col]+1) ) {
permOk = false;
break done;
}
}
}
if ( permOk ) {
LatinSquare newSquare = new LatinSquare(square);
for ( int col = 0 ; col < n ; col++ ) {
newSquare.set(fillRow, col, perm[col]+1);
}
squaresNext.add(newSquare);
}
}
permGen.reset();
}
squares = squaresNext;
}
return squares;
}
@SuppressWarnings("unused")
private static int[] display(int[] in) {
int [] out = new int[in.length];
for ( int i = 0 ; i < in.length ; i++ ) {
out[i] = in[i] + 1;
}
return out;
}
private static class LatinSquare {
int[][] square;
int size;
public LatinSquare(int n) {
square = new int[n][n];
size = n;
for ( int col = 0 ; col < n ; col++ ) {
set(0, col, col + 1);
}
}
public LatinSquare(LatinSquare ls) {
int n = ls.size;
square = new int[n][n];
size = n;
for ( int row = 0 ; row < n ; row++ ) {
for ( int col = 0 ; col < n ; col++ ) {
set(row, col, ls.get(row, col));
}
}
}
public void set(int row, int col, int value) {
square[row][col] = value;
}
public int get(int row, int col) {
return square[row][col];
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for ( int row = 0 ; row < size ; row++ ) {
sb.append(Arrays.toString(square[row]));
sb.append("\n");
}
return sb.toString();
}
}
private static class PermutationGenerator {
private int[] a;
private BigInteger numLeft;
private BigInteger total;
public PermutationGenerator (int n) {
if (n < 1) {
throw new IllegalArgumentException ("Min 1");
}
a = new int[n];
total = getFactorial(n);
reset();
}
private void reset () {
for ( int i = 0 ; i < a.length ; i++ ) {
a[i] = i;
}
numLeft = new BigInteger(total.toString());
}
public boolean hasMore() {
return numLeft.compareTo(BigInteger.ZERO) == 1;
}
private static BigInteger getFactorial (int n) {
BigInteger fact = BigInteger.ONE;
for ( int i = n ; i > 1 ; i-- ) {
fact = fact.multiply(new BigInteger(Integer.toString(i)));
}
return fact;
}
public int[] getNext() {
if ( numLeft.equals(total) ) {
numLeft = numLeft.subtract (BigInteger.ONE);
return a;
}
int j = a.length - 2;
while ( a[j] > a[j+1] ) {
j--;
}
int k = a.length - 1;
while ( a[j] > a[k] ) {
k--;
}
int temp = a[k];
a[k] = a[j];
a[j] = temp;
int r = a.length - 1;
int s = j + 1;
while (r > s) {
int temp2 = a[s];
a[s] = a[r];
a[r] = temp2;
r--;
s++;
}
numLeft = numLeft.subtract(BigInteger.ONE);
return a;
}
}
}
| def printSquare(a)
for row in a
print row, "\n"
end
print "\n"
end
def dList(n, start)
start = start - 1
a = Array.new(n) {|i| i}
a[0], a[start] = a[start], a[0]
a[1..] = a[1..].sort
first = a[1]
r = []
recurse = lambda {|last|
if last == first then
a[1..].each_with_index {|v, j|
if j + 1 == v then
return
end
}
b = a.map { |i| i + 1 }
r << b
return
end
i = last
while i >= 1 do
a[i], a[last] = a[last], a[i]
recurse.call(last - 1)
a[i], a[last] = a[last], a[i]
i = i - 1
end
}
recurse.call(n - 1)
return r
end
def reducedLatinSquares(n, echo)
if n <= 0 then
if echo then
print "[]\n\n"
end
return 0
end
if n == 1 then
if echo then
print "[1]\n\n"
end
return 1
end
rlatin = Array.new(n) { Array.new(n, Float::NAN)}
for j in 0 .. n - 1
rlatin[0][j] = j + 1
end
count = 0
recurse = lambda {|i|
rows = dList(n, i)
for r in 0 .. rows.length - 1
rlatin[i - 1] = rows[r].dup
catch (:outer) do
for k in 0 .. i - 2
for j in 1 .. n - 1
if rlatin[k][j] == rlatin[i - 1][j] then
if r < rows.length - 1 then
throw :outer
end
if i > 2 then
return
end
end
end
end
if i < n then
recurse.call(i + 1)
else
count = count + 1
if echo then
printSquare(rlatin)
end
end
end
end
}
recurse.call(2)
return count
end
def factorial(n)
if n == 0 then
return 1
end
prod = 1
for i in 2 .. n
prod = prod * i
end
return prod
end
print "The four reduced latin squares of order 4 are:\n"
reducedLatinSquares(4, true)
print "The size of the set of reduced latin squares for the following orders\n"
print "and hence the total number of latin squares of these orders are:\n"
for n in 1 .. 6
size = reducedLatinSquares(n, false)
f = factorial(n - 1)
f = f * f * n * size
print "Order %d Size %-4d x %d! x %d! => Total %d\n" % [n, size, n, n - 1, f]
end
|
Maintain the same structure and functionality when rewriting this code in Ruby. | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.IntConsumer;
import java.util.stream.Collectors;
public class Kosaraju {
static class Recursive<I> {
I func;
}
private static List<Integer> kosaraju(List<List<Integer>> g) {
int size = g.size();
boolean[] vis = new boolean[size];
int[] l = new int[size];
AtomicInteger x = new AtomicInteger(size);
List<List<Integer>> t = new ArrayList<>();
for (int i = 0; i < size; ++i) {
t.add(new ArrayList<>());
}
Recursive<IntConsumer> visit = new Recursive<>();
visit.func = (int u) -> {
if (!vis[u]) {
vis[u] = true;
for (Integer v : g.get(u)) {
visit.func.accept(v);
t.get(v).add(u);
}
int xval = x.decrementAndGet();
l[xval] = u;
}
};
for (int i = 0; i < size; ++i) {
visit.func.accept(i);
}
int[] c = new int[size];
Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>();
assign.func = (Integer u, Integer root) -> {
if (vis[u]) {
vis[u] = false;
c[u] = root;
for (Integer v : t.get(u)) {
assign.func.accept(v, root);
}
}
};
for (int u : l) {
assign.func.accept(u, u);
}
return Arrays.stream(c).boxed().collect(Collectors.toList());
}
public static void main(String[] args) {
List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < 8; ++i) {
g.add(new ArrayList<>());
}
g.get(0).add(1);
g.get(1).add(2);
g.get(2).add(0);
g.get(3).add(1);
g.get(3).add(2);
g.get(3).add(4);
g.get(4).add(3);
g.get(4).add(5);
g.get(5).add(2);
g.get(5).add(6);
g.get(6).add(5);
g.get(7).add(4);
g.get(7).add(6);
g.get(7).add(7);
List<Integer> output = kosaraju(g);
System.out.println(output);
}
}
| func korasaju(Array g) {
var vis = g.len.of(false)
var L = []
var x = g.end
var t = g.len.of { [] }
func visit(u) {
if (!vis[u]) {
vis[u] = true
g[u].each {|v|
visit(v)
t[v] << u
}
L[x--] = u
}
}
g.range.each {|u|
visit(u)
}
var c = []
func assign(u, root) {
if (vis[u]) {
vis[u] = false
c[u] = root
t[u].each {|v|
assign(v, root)
}
}
}
L.each {|u|
assign(u, u)
}
return c
}
var g = [[1], [2], [0], [1, 2, 4], [3, 5], [2, 6], [5], [4, 6, 7]]
say korasaju(g)
|
Change the programming language of this snippet from Java to Ruby without modifying what it does. | import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
public class MarkovChain {
private static Random r = new Random();
private static String markov(String filePath, int keySize, int outputSize) throws IOException {
if (keySize < 1) throw new IllegalArgumentException("Key size can't be less than 1");
Path path = Paths.get(filePath);
byte[] bytes = Files.readAllBytes(path);
String[] words = new String(bytes).trim().split(" ");
if (outputSize < keySize || outputSize >= words.length) {
throw new IllegalArgumentException("Output size is out of range");
}
Map<String, List<String>> dict = new HashMap<>();
for (int i = 0; i < (words.length - keySize); ++i) {
StringBuilder key = new StringBuilder(words[i]);
for (int j = i + 1; j < i + keySize; ++j) {
key.append(' ').append(words[j]);
}
String value = (i + keySize < words.length) ? words[i + keySize] : "";
if (!dict.containsKey(key.toString())) {
ArrayList<String> list = new ArrayList<>();
list.add(value);
dict.put(key.toString(), list);
} else {
dict.get(key.toString()).add(value);
}
}
int n = 0;
int rn = r.nextInt(dict.size());
String prefix = (String) dict.keySet().toArray()[rn];
List<String> output = new ArrayList<>(Arrays.asList(prefix.split(" ")));
while (true) {
List<String> suffix = dict.get(prefix);
if (suffix.size() == 1) {
if (Objects.equals(suffix.get(0), "")) return output.stream().reduce("", (a, b) -> a + " " + b);
output.add(suffix.get(0));
} else {
rn = r.nextInt(suffix.size());
output.add(suffix.get(rn));
}
if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce("", (a, b) -> a + " " + b);
n++;
prefix = output.stream().skip(n).limit(keySize).reduce("", (a, b) -> a + " " + b).trim();
}
}
public static void main(String[] args) throws IOException {
System.out.println(markov("alice_oz.txt", 3, 200));
}
}
| class Markov(N)
@dictionary = Hash(StaticArray(String, N), Array(String)).new { [] of String }
def parse(filename : String)
File.open(filename) do |file|
parse(file)
end
end
private def prefix_from(array)
StaticArray(String, N).new { |i| array[-(N - i)] }
end
def parse(input : IO)
sequence = [] of String
loop do
word = input.gets(' ', true)
break unless word
if sequence.size == N
prefix = prefix_from(sequence)
@dictionary[prefix] = (@dictionary[prefix] << word)
end
sequence << word
sequence.shift if sequence.size > N
end
end
def generate(count)
prefix = @dictionary.keys.sample
result = Array(String).new(prefix.size) { |i| prefix[i] }
(count - N).times do
prefix = prefix_from(result)
values = @dictionary[prefix]
break if values.size == 0
result << values.sample
end
result.join(' ')
end
end
chain = Markov(3).new
chain.parse("alice_oz.txt")
puts chain.generate(200)
|
Convert this Java block to Ruby, preserving its control flow and logic. | import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class ArithmeticCoding {
private static class Triple<A, B, C> {
A a;
B b;
C c;
Triple(A a, B b, C c) {
this.a = a;
this.b = b;
this.c = c;
}
}
private static class Freq extends HashMap<Character, Long> {
}
private static Freq cumulativeFreq(Freq freq) {
long total = 0;
Freq cf = new Freq();
for (int i = 0; i < 256; ++i) {
char c = (char) i;
Long v = freq.get(c);
if (v != null) {
cf.put(c, total);
total += v;
}
}
return cf;
}
private static Triple<BigInteger, Integer, Freq> arithmeticCoding(String str, Long radix) {
char[] chars = str.toCharArray();
Freq freq = new Freq();
for (char c : chars) {
if (!freq.containsKey(c))
freq.put(c, 1L);
else
freq.put(c, freq.get(c) + 1);
}
Freq cf = cumulativeFreq(freq);
BigInteger base = BigInteger.valueOf(chars.length);
BigInteger lower = BigInteger.ZERO;
BigInteger pf = BigInteger.ONE;
for (char c : chars) {
BigInteger x = BigInteger.valueOf(cf.get(c));
lower = lower.multiply(base).add(x.multiply(pf));
pf = pf.multiply(BigInteger.valueOf(freq.get(c)));
}
BigInteger upper = lower.add(pf);
int powr = 0;
BigInteger bigRadix = BigInteger.valueOf(radix);
while (true) {
pf = pf.divide(bigRadix);
if (pf.equals(BigInteger.ZERO)) break;
powr++;
}
BigInteger diff = upper.subtract(BigInteger.ONE).divide(bigRadix.pow(powr));
return new Triple<>(diff, powr, freq);
}
private static String arithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {
BigInteger powr = BigInteger.valueOf(radix);
BigInteger enc = num.multiply(powr.pow(pwr));
long base = 0;
for (Long v : freq.values()) base += v;
Freq cf = cumulativeFreq(freq);
Map<Long, Character> dict = new HashMap<>();
for (Map.Entry<Character, Long> entry : cf.entrySet()) dict.put(entry.getValue(), entry.getKey());
long lchar = -1;
for (long i = 0; i < base; ++i) {
Character v = dict.get(i);
if (v != null) {
lchar = v;
} else if (lchar != -1) {
dict.put(i, (char) lchar);
}
}
StringBuilder decoded = new StringBuilder((int) base);
BigInteger bigBase = BigInteger.valueOf(base);
for (long i = base - 1; i >= 0; --i) {
BigInteger pow = bigBase.pow((int) i);
BigInteger div = enc.divide(pow);
Character c = dict.get(div.longValue());
BigInteger fv = BigInteger.valueOf(freq.get(c));
BigInteger cv = BigInteger.valueOf(cf.get(c));
BigInteger diff = enc.subtract(pow.multiply(cv));
enc = diff.divide(fv);
decoded.append(c);
}
return decoded.toString();
}
public static void main(String[] args) {
long radix = 10;
String[] strings = {"DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT"};
String fmt = "%-25s=> %19s * %d^%s\n";
for (String str : strings) {
Triple<BigInteger, Integer, Freq> encoded = arithmeticCoding(str, radix);
String dec = arithmeticDecoding(encoded.a, radix, encoded.b, encoded.c);
System.out.printf(fmt, str, encoded.a, radix, encoded.b);
if (!Objects.equals(str, dec)) throw new RuntimeException("\tHowever that is incorrect!");
}
}
}
| def cumulative_freq(freq)
cf = {}
total = 0
freq.keys.sort.each do |b|
cf[b] = total
total += freq[b]
end
return cf
end
def arithmethic_coding(bytes, radix)
freq = Hash.new(0)
bytes.each { |b| freq[b] += 1 }
cf = cumulative_freq(freq)
base = bytes.size
lower = 0
pf = 1
bytes.each do |b|
lower = lower*base + cf[b]*pf
pf *= freq[b]
end
upper = lower+pf
pow = 0
loop do
pf /= radix
break if pf==0
pow += 1
end
enc = ((upper-1) / radix**pow)
[enc, pow, freq]
end
def arithmethic_decoding(enc, radix, pow, freq)
enc *= radix**pow;
base = freq.values.reduce(:+)
cf = cumulative_freq(freq)
dict = {}
cf.each_pair do |k,v|
dict[v] = k
end
lchar = nil
(0...base).each do |i|
if dict.has_key?(i)
lchar = dict[i]
elsif lchar != nil
dict[i] = lchar
end
end
decoded = []
(0...base).reverse_each do |i|
pow = base**i
div = enc/pow
c = dict[div]
fv = freq[c]
cv = cf[c]
rem = ((enc - pow*cv) / fv)
enc = rem
decoded << c
end
return decoded
end
radix = 10
%w(DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT).each do |str|
enc, pow, freq = arithmethic_coding(str.bytes, radix)
dec = arithmethic_decoding(enc, radix, pow, freq).map{|b| b.chr }.join
printf("%-25s=> %19s * %d^%s\n", str, enc, radix, pow)
if str != dec
raise "\tHowever that is incorrect!"
end
end
|
Produce a functionally identical Ruby code for the snippet given in Java. | import java.awt.Point;
import java.util.Scanner;
public class PlayfairCipher {
private static char[][] charTable;
private static Point[] positions;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n: ", sc, 1);
boolean changeJtoI = jti.equalsIgnoreCase("y");
createTable(key, changeJtoI);
String enc = encode(prepareText(txt, changeJtoI));
System.out.printf("%nEncoded message: %n%s%n", enc);
System.out.printf("%nDecoded message: %n%s%n", decode(enc));
}
private static String prompt(String promptText, Scanner sc, int minLen) {
String s;
do {
System.out.print(promptText);
s = sc.nextLine().trim();
} while (s.length() < minLen);
return s;
}
private static String prepareText(String s, boolean changeJtoI) {
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return changeJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTable(String key, boolean changeJtoI) {
charTable = new char[5][5];
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++) {
char c = s.charAt(i);
if (positions[c - 'A'] == null) {
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5);
k++;
}
}
}
private static String encode(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2) {
if (i == sb.length() - 1)
sb.append(sb.length() % 2 == 1 ? 'X' : "");
else if (sb.charAt(i) == sb.charAt(i + 1))
sb.insert(i + 1, 'X');
}
return codec(sb, 1);
}
private static String decode(String s) {
return codec(new StringBuilder(s), 4);
}
private static String codec(StringBuilder text, int direction) {
int len = text.length();
for (int i = 0; i < len; i += 2) {
char a = text.charAt(i);
char b = text.charAt(i + 1);
int row1 = positions[a - 'A'].y;
int row2 = positions[b - 'A'].y;
int col1 = positions[a - 'A'].x;
int col2 = positions[b - 'A'].x;
if (row1 == row2) {
col1 = (col1 + direction) % 5;
col2 = (col2 + direction) % 5;
} else if (col1 == col2) {
row1 = (row1 + direction) % 5;
row2 = (row2 + direction) % 5;
} else {
int tmp = col1;
col1 = col2;
col2 = tmp;
}
text.setCharAt(i, charTable[row1][col1]);
text.setCharAt(i + 1, charTable[row2][col2]);
}
return text.toString();
}
}
| class Playfair
Size = 5
def initialize(key, missing)
@missing = missing.upcase
alphabet = ('A'..'Z').to_a.join.upcase.delete(@missing).split''
extended = key.upcase.gsub(/[^A-Z]/,'').split('') + alphabet
grid = extended.uniq[0...Size*Size].each_slice(Size).to_a
coords = {}
grid.each_with_index do |row, i|
row.each_with_index do |letter, j|
coords[letter] = [i,j]
end
end
@encode = {}
alphabet.product(alphabet).reject { |a,b| a==b }.each do |a, b|
i1, j1 = coords[a]
i2, j2 = coords[b]
if i1 == i2 then
j1 = (j1 + 1) % Size
j2 = (j2 + 1) % Size
elsif j1 == j2 then
i1 = (i1 + 1) % Size
i2 = (i2 + 1) % Size
else
j1, j2 = j2, j1
end
@encode["
@decode = @encode.invert
end
end
def encode(plaintext)
plain = plaintext.upcase.gsub(/[^A-Z]/,'')
if @missing == 'J' then
plain = plain.gsub(/J/, 'I')
else
plain = plain.gsub(@missing, 'X')
end
plain = plain.gsub(/(.)\1/, '\1X\1')
if plain.length % 2 == 1 then
plain += 'X'
end
return plain.upcase.split('').each_slice(2).map do |pair|
@encode[pair.join]
end.join.split('').each_slice(5).map{|s|s.join}.join(' ')
end
def decode(ciphertext)
cipher = ciphertext.upcase.gsub(/[^A-Z]/,'')
return cipher.upcase.split('').each_slice(2).map do |pair|
@decode[pair.join]
end.join.split('').each_slice(5).map{|s|s.join}.join(' ')
end
end
|
Translate this program into Ruby but keep the logic exactly as in Java. | import java.awt.Point;
import java.util.Scanner;
public class PlayfairCipher {
private static char[][] charTable;
private static Point[] positions;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n: ", sc, 1);
boolean changeJtoI = jti.equalsIgnoreCase("y");
createTable(key, changeJtoI);
String enc = encode(prepareText(txt, changeJtoI));
System.out.printf("%nEncoded message: %n%s%n", enc);
System.out.printf("%nDecoded message: %n%s%n", decode(enc));
}
private static String prompt(String promptText, Scanner sc, int minLen) {
String s;
do {
System.out.print(promptText);
s = sc.nextLine().trim();
} while (s.length() < minLen);
return s;
}
private static String prepareText(String s, boolean changeJtoI) {
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return changeJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTable(String key, boolean changeJtoI) {
charTable = new char[5][5];
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++) {
char c = s.charAt(i);
if (positions[c - 'A'] == null) {
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5);
k++;
}
}
}
private static String encode(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2) {
if (i == sb.length() - 1)
sb.append(sb.length() % 2 == 1 ? 'X' : "");
else if (sb.charAt(i) == sb.charAt(i + 1))
sb.insert(i + 1, 'X');
}
return codec(sb, 1);
}
private static String decode(String s) {
return codec(new StringBuilder(s), 4);
}
private static String codec(StringBuilder text, int direction) {
int len = text.length();
for (int i = 0; i < len; i += 2) {
char a = text.charAt(i);
char b = text.charAt(i + 1);
int row1 = positions[a - 'A'].y;
int row2 = positions[b - 'A'].y;
int col1 = positions[a - 'A'].x;
int col2 = positions[b - 'A'].x;
if (row1 == row2) {
col1 = (col1 + direction) % 5;
col2 = (col2 + direction) % 5;
} else if (col1 == col2) {
row1 = (row1 + direction) % 5;
row2 = (row2 + direction) % 5;
} else {
int tmp = col1;
col1 = col2;
col2 = tmp;
}
text.setCharAt(i, charTable[row1][col1]);
text.setCharAt(i + 1, charTable[row2][col2]);
}
return text.toString();
}
}
| class Playfair
Size = 5
def initialize(key, missing)
@missing = missing.upcase
alphabet = ('A'..'Z').to_a.join.upcase.delete(@missing).split''
extended = key.upcase.gsub(/[^A-Z]/,'').split('') + alphabet
grid = extended.uniq[0...Size*Size].each_slice(Size).to_a
coords = {}
grid.each_with_index do |row, i|
row.each_with_index do |letter, j|
coords[letter] = [i,j]
end
end
@encode = {}
alphabet.product(alphabet).reject { |a,b| a==b }.each do |a, b|
i1, j1 = coords[a]
i2, j2 = coords[b]
if i1 == i2 then
j1 = (j1 + 1) % Size
j2 = (j2 + 1) % Size
elsif j1 == j2 then
i1 = (i1 + 1) % Size
i2 = (i2 + 1) % Size
else
j1, j2 = j2, j1
end
@encode["
@decode = @encode.invert
end
end
def encode(plaintext)
plain = plaintext.upcase.gsub(/[^A-Z]/,'')
if @missing == 'J' then
plain = plain.gsub(/J/, 'I')
else
plain = plain.gsub(@missing, 'X')
end
plain = plain.gsub(/(.)\1/, '\1X\1')
if plain.length % 2 == 1 then
plain += 'X'
end
return plain.upcase.split('').each_slice(2).map do |pair|
@encode[pair.join]
end.join.split('').each_slice(5).map{|s|s.join}.join(' ')
end
def decode(ciphertext)
cipher = ciphertext.upcase.gsub(/[^A-Z]/,'')
return cipher.upcase.split('').each_slice(2).map do |pair|
@decode[pair.join]
end.join.split('').each_slice(5).map{|s|s.join}.join(' ')
end
end
|
Change the following Java code into Ruby without altering its purpose. | import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class WordBreak {
public static void main(String[] args) {
List<String> dict = Arrays.asList("a", "aa", "b", "ab", "aab");
for ( String testString : Arrays.asList("aab", "aa b") ) {
List<List<String>> matches = wordBreak(testString, dict);
System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size());
for ( List<String> match : matches ) {
System.out.printf(" Word Break = %s%n", match);
}
System.out.printf("%n");
}
dict = Arrays.asList("abc", "a", "ac", "b", "c", "cb", "d");
for ( String testString : Arrays.asList("abcd", "abbc", "abcbcd", "acdbc", "abcdd") ) {
List<List<String>> matches = wordBreak(testString, dict);
System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size());
for ( List<String> match : matches ) {
System.out.printf(" Word Break = %s%n", match);
}
System.out.printf("%n");
}
}
private static List<List<String>> wordBreak(String s, List<String> dictionary) {
List<List<String>> matches = new ArrayList<>();
Queue<Node> queue = new LinkedList<>();
queue.add(new Node(s));
while ( ! queue.isEmpty() ) {
Node node = queue.remove();
if ( node.val.length() == 0 ) {
matches.add(node.parsed);
}
else {
for ( String word : dictionary ) {
if ( node.val.startsWith(word) ) {
String valNew = node.val.substring(word.length(), node.val.length());
List<String> parsedNew = new ArrayList<>();
parsedNew.addAll(node.parsed);
parsedNew.add(word);
queue.add(new Node(valNew, parsedNew));
}
}
}
}
return matches;
}
private static class Node {
private String val;
private List<String> parsed;
public Node(String initial) {
val = initial;
parsed = new ArrayList<>();
}
public Node(String s, List<String> p) {
val = s;
parsed = p;
}
}
}
| def split_text_with_dict(text, dict, splited=[])
solutions = []
dict.each do |word|
if text.start_with? word
new_text = text.delete_prefix word
new_splited = splited.dup<< word
if new_text.empty?
solutions << new_splited
else
sols = split_text_with_dict(new_text, dict, new_splited)
sols.each { |s| solutions << s }
end
end
end
return solutions
end
|
Rewrite the snippet below in Ruby so it works the same as the original Java code. | import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class ImmutableMap {
public static void main(String[] args) {
Map<String,Integer> hashMap = getImmutableMap();
try {
hashMap.put("Test", 23);
}
catch (UnsupportedOperationException e) {
System.out.println("ERROR: Unable to put new value.");
}
try {
hashMap.clear();
}
catch (UnsupportedOperationException e) {
System.out.println("ERROR: Unable to clear map.");
}
try {
hashMap.putIfAbsent("Test", 23);
}
catch (UnsupportedOperationException e) {
System.out.println("ERROR: Unable to put if absent.");
}
for ( String key : hashMap.keySet() ) {
System.out.printf("key = %s, value = %s%n", key, hashMap.get(key));
}
}
private static Map<String,Integer> getImmutableMap() {
Map<String,Integer> hashMap = new HashMap<>();
hashMap.put("Key 1", 34);
hashMap.put("Key 2", 105);
hashMap.put("Key 3", 144);
return Collections.unmodifiableMap(hashMap);
}
}
|
class FencedHash
def initialize(hash, obj=nil)
@default = obj
@hash = {}
hash.each_pair do |key, value|
@hash[key] = [value, value]
end
end
def initialize_clone(orig)
super
copy = {}
@hash.each_pair {|key, values| copy[key] = values.clone }
@hash = copy
end
def initialize_dup(orig)
super
copy = {}
@hash.each_pair {|key, values| copy[key] = values.dup }
@hash = copy
end
def [](key)
values = @hash[key]
if values
values[0]
else
@default
end
end
def []=(key, value)
values = @hash[key]
if values
values[0] = value
else
raise KeyError, "fence prevents adding new key:
end
end
alias store []=
def clear
@hash.each_value {|values| values[0] = values[1]}
self
end
def delete(key)
values = @hash[key]
if values
old = values[0]
values[0] = values[1]
old
end
end
def delete_if
if block_given?
@hash.each_pair do |key, values|
yield(key, values[0]) and values[0] = values[1]
end
self
else
enum_for(:delete_if) { @hash.size }
end
end
attr_accessor :default
def each_key(&block)
if block
@hash.each_key(&block)
self
else
enum_for(:each_key) { @hash.size }
end
end
def each_pair
if block_given?
@hash.each_pair {|key, values| yield [key, values[0]] }
self
else
enum_for(:each_pair) { @hash.size }
end
end
def each_value
if block_given?
@hash.each_value {|values| yield values[0] }
else
enum_for(:each_value) { @hash.size }
end
end
def fetch(*argv)
argc = argv.length
unless argc.between?(1, 2)
raise(ArgumentError,
"wrong number of arguments (
end
if argc == 2 and block_given?
warn("
"block supersedes default value argument")
end
key, default = argv
values = @hash[key]
if values
values[0]
elsif block_given?
yield key
elsif argc == 2
default
else
raise KeyError, "key not found:
end
end
def freeze
@hash.each_value {|values| values.freeze }
super
end
def has_key?(key)
@hash.has_key?(key)
end
alias include? has_key?
alias member? has_key?
def keep_if
if block_given?
@hash.each_pair do |key, values|
yield(key, values[0]) or values[0] = values[1]
end
self
else
enum_for(:keep_if) { @hash.size }
end
end
def keys
@hash.keys
end
def length
@hash.length
end
alias size length
def to_h
result = Hash.new(@default)
@hash.each_pair {|key, values| result[key] = values[0]}
result
end
def to_s
"
end
alias inspect to_s
def values
@hash.each_value.map {|values| values[0]}
end
def values_at(*keys)
keys.map {|key| self[key]}
end
end
|
Port the following code from Java to Ruby with equivalent syntax and logic. | import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class DecimalToBinary {
public static void main(String[] args) {
for ( String s : new String[] {"23.34375", ".1", "3.1415926535897932"} ) {
String binary = decimalToBinary(new BigDecimal(s));
System.out.printf("%s => %s%n", s, binary);
System.out.printf("%s => %s%n", binary, binaryToDecimal(binary));
}
}
private static BigDecimal binaryToDecimal(String binary) {
return binaryToDecimal(binary, 50);
}
private static BigDecimal binaryToDecimal(String binary, int digits) {
int decimalPosition = binary.indexOf(".");
String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary;
String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : "";
BigDecimal result = BigDecimal.ZERO;
BigDecimal powTwo = BigDecimal.ONE;
BigDecimal two = BigDecimal.valueOf(2);
for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) {
result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')));
powTwo = powTwo.multiply(two);
}
MathContext mc = new MathContext(digits);
powTwo = BigDecimal.ONE;
for ( char c : fractional.toCharArray() ) {
powTwo = powTwo.divide(two);
result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc);
}
return result;
}
private static String decimalToBinary(BigDecimal decimal) {
return decimalToBinary(decimal, 50);
}
private static String decimalToBinary(BigDecimal decimal, int digits) {
BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR);
BigDecimal fractional = decimal.subtract(integer);
StringBuilder sb = new StringBuilder();
BigDecimal two = BigDecimal.valueOf(2);
BigDecimal zero = BigDecimal.ZERO;
while ( integer.compareTo(zero) > 0 ) {
BigDecimal[] result = integer.divideAndRemainder(two);
sb.append(result[1]);
integer = result[0];
}
sb.reverse();
int count = 0;
if ( fractional.compareTo(zero) != 0 ) {
sb.append(".");
}
while ( fractional.compareTo(zero) != 0 ) {
count++;
fractional = fractional.multiply(two);
sb.append(fractional.setScale(0, RoundingMode.FLOOR));
if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) {
fractional = fractional.subtract(BigDecimal.ONE);
}
if ( count >= digits ) {
break;
}
}
return sb.toString();
}
}
| def dec2bin(dec, precision=16)
int, df = dec.split(".")
minus = int.delete!("-")
bin = (minus ? "-" : "") + int.to_i.to_s(2) + "."
if df and df.to_i>0
fp = ("."+df).to_f
digit = 1
until fp.zero? or digit>precision
fp *= 2
n = fp.to_i
bin << n.to_s
fp -= n
digit += 1
end
else
bin << "0"
end
bin
end
def bin2dec(bin)
int, df = bin.split(".")
minus = int.delete!("-")
dec = (minus ? "-" : "") + int.to_i(2).to_s
if df
dec << (df.to_i(2) / 2.0**(df.size)).to_s[1..-1]
else
dec << ".0"
end
end
data = %w[23.34375 11.90625 -23.34375 -11.90625]
data.each do |dec|
bin = dec2bin(dec)
dec2 = bin2dec(bin)
puts "%10s => %12s =>%10s" % [dec, bin, dec2]
end
|
Preserve the algorithm and functionality while converting the code from Java to Ruby. | import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class DecimalToBinary {
public static void main(String[] args) {
for ( String s : new String[] {"23.34375", ".1", "3.1415926535897932"} ) {
String binary = decimalToBinary(new BigDecimal(s));
System.out.printf("%s => %s%n", s, binary);
System.out.printf("%s => %s%n", binary, binaryToDecimal(binary));
}
}
private static BigDecimal binaryToDecimal(String binary) {
return binaryToDecimal(binary, 50);
}
private static BigDecimal binaryToDecimal(String binary, int digits) {
int decimalPosition = binary.indexOf(".");
String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary;
String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : "";
BigDecimal result = BigDecimal.ZERO;
BigDecimal powTwo = BigDecimal.ONE;
BigDecimal two = BigDecimal.valueOf(2);
for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) {
result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')));
powTwo = powTwo.multiply(two);
}
MathContext mc = new MathContext(digits);
powTwo = BigDecimal.ONE;
for ( char c : fractional.toCharArray() ) {
powTwo = powTwo.divide(two);
result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc);
}
return result;
}
private static String decimalToBinary(BigDecimal decimal) {
return decimalToBinary(decimal, 50);
}
private static String decimalToBinary(BigDecimal decimal, int digits) {
BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR);
BigDecimal fractional = decimal.subtract(integer);
StringBuilder sb = new StringBuilder();
BigDecimal two = BigDecimal.valueOf(2);
BigDecimal zero = BigDecimal.ZERO;
while ( integer.compareTo(zero) > 0 ) {
BigDecimal[] result = integer.divideAndRemainder(two);
sb.append(result[1]);
integer = result[0];
}
sb.reverse();
int count = 0;
if ( fractional.compareTo(zero) != 0 ) {
sb.append(".");
}
while ( fractional.compareTo(zero) != 0 ) {
count++;
fractional = fractional.multiply(two);
sb.append(fractional.setScale(0, RoundingMode.FLOOR));
if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) {
fractional = fractional.subtract(BigDecimal.ONE);
}
if ( count >= digits ) {
break;
}
}
return sb.toString();
}
}
| def dec2bin(dec, precision=16)
int, df = dec.split(".")
minus = int.delete!("-")
bin = (minus ? "-" : "") + int.to_i.to_s(2) + "."
if df and df.to_i>0
fp = ("."+df).to_f
digit = 1
until fp.zero? or digit>precision
fp *= 2
n = fp.to_i
bin << n.to_s
fp -= n
digit += 1
end
else
bin << "0"
end
bin
end
def bin2dec(bin)
int, df = bin.split(".")
minus = int.delete!("-")
dec = (minus ? "-" : "") + int.to_i(2).to_s
if df
dec << (df.to_i(2) / 2.0**(df.size)).to_s[1..-1]
else
dec << ".0"
end
end
data = %w[23.34375 11.90625 -23.34375 -11.90625]
data.each do |dec|
bin = dec2bin(dec)
dec2 = bin2dec(bin)
puts "%10s => %12s =>%10s" % [dec, bin, dec2]
end
|
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version. | import java.awt.Point;
import java.util.*;
import static java.util.Arrays.asList;
import java.util.function.Function;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
public class FreePolyominoesEnum {
static final List<Function<Point, Point>> transforms = new ArrayList<>();
static {
transforms.add(p -> new Point(p.y, -p.x));
transforms.add(p -> new Point(-p.x, -p.y));
transforms.add(p -> new Point(-p.y, p.x));
transforms.add(p -> new Point(-p.x, p.y));
transforms.add(p -> new Point(-p.y, -p.x));
transforms.add(p -> new Point(p.x, -p.y));
transforms.add(p -> new Point(p.y, p.x));
}
static Point findMinima(List<Point> poly) {
return new Point(
poly.stream().mapToInt(a -> a.x).min().getAsInt(),
poly.stream().mapToInt(a -> a.y).min().getAsInt());
}
static List<Point> translateToOrigin(List<Point> poly) {
final Point min = findMinima(poly);
poly.replaceAll(p -> new Point(p.x - min.x, p.y - min.y));
return poly;
}
static List<List<Point>> rotationsAndReflections(List<Point> poly) {
List<List<Point>> lst = new ArrayList<>();
lst.add(poly);
for (Function<Point, Point> t : transforms)
lst.add(poly.stream().map(t).collect(toList()));
return lst;
}
static Comparator<Point> byCoords = Comparator.<Point>comparingInt(p -> p.x)
.thenComparingInt(p -> p.y);
static List<Point> normalize(List<Point> poly) {
return rotationsAndReflections(poly).stream()
.map(lst -> translateToOrigin(lst))
.map(lst -> lst.stream().sorted(byCoords).collect(toList()))
.min(comparing(Object::toString))
.get();
}
static List<Point> neighborhoods(Point p) {
return asList(new Point(p.x - 1, p.y), new Point(p.x + 1, p.y),
new Point(p.x, p.y - 1), new Point(p.x, p.y + 1));
}
static List<Point> concat(List<Point> lst, Point pt) {
List<Point> r = new ArrayList<>();
r.addAll(lst);
r.add(pt);
return r;
}
static List<Point> newPoints(List<Point> poly) {
return poly.stream()
.flatMap(p -> neighborhoods(p).stream())
.filter(p -> !poly.contains(p))
.distinct()
.collect(toList());
}
static List<List<Point>> constructNextRank(List<Point> poly) {
return newPoints(poly).stream()
.map(p -> normalize(concat(poly, p)))
.distinct()
.collect(toList());
}
static List<List<Point>> rank(int n) {
if (n < 0)
throw new IllegalArgumentException("n cannot be negative");
if (n < 2) {
List<List<Point>> r = new ArrayList<>();
if (n == 1)
r.add(asList(new Point(0, 0)));
return r;
}
return rank(n - 1).stream()
.parallel()
.flatMap(lst -> constructNextRank(lst).stream())
.distinct()
.collect(toList());
}
public static void main(String[] args) {
for (List<Point> poly : rank(5)) {
for (Point p : poly)
System.out.printf("(%d,%d) ", p.x, p.y);
System.out.println();
}
}
}
| require 'set'
def translate2origin(poly)
minx = poly.map(&:first).min
miny = poly.map(&:last).min
poly.map{|x,y| [x - minx, y - miny]}.sort
end
def rotate90(x,y) [y, -x] end
def reflect(x,y) [-x, y] end
def rotations_and_reflections(poly)
[poly,
poly = poly.map{|x,y| rotate90(x,y)},
poly = poly.map{|x,y| rotate90(x,y)},
poly = poly.map{|x,y| rotate90(x,y)},
poly = poly.map{|x,y| reflect(x,y)},
poly = poly.map{|x,y| rotate90(x,y)},
poly = poly.map{|x,y| rotate90(x,y)},
poly.map{|x,y| rotate90(x,y)} ]
end
def canonical(poly)
rotations_and_reflections(poly).map{|pl| translate2origin(pl)}
end
def contiguous(x,y)
[[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]]
end
def new_points(poly)
points = []
poly.each{|x,y| contiguous(x,y).each{|point| points << point}}
(points - poly).uniq
end
def new_polys(polys)
pattern = Set.new
polys.each_with_object([]) do |poly, polyomino|
new_points(poly).each do |point|
next if pattern.include?(pl = translate2origin(poly + [point]))
polyomino << canonical(pl).each{|p| pattern << p}.min
end
end
end
def rank(n)
case n
when 0 then [[]]
when 1 then [[[0,0]]]
else new_polys(rank(n-1))
end
end
def text_representation(poly)
table = Hash.new(' ')
poly.each{|x,y| table[[x,y]] = '
maxx = poly.map(&:first).max
maxy = poly.map(&:last).max
(0..maxx).map{|x| (0..maxy).map{|y| table[[x,y]]}.join}
end
p (0..10).map{|n| rank(n).size}
n = ARGV[0] ? ARGV[0].to_i : 5
puts "\nAll free polyominoes of rank %d:" % n
rank(n).sort.each{|poly| puts text_representation(poly),""}
|
Change the programming language of this snippet from Java to Ruby without modifying what it does. | import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
public class IQPuzzle {
public static void main(String[] args) {
System.out.printf(" ");
for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {
System.out.printf(" %,6d", start);
}
System.out.printf("%n");
for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {
System.out.printf("%2d", start);
Map<Integer,Integer> solutions = solve(start);
for ( int end = 1 ; end < Puzzle.MAX_PEGS ; end++ ) {
System.out.printf(" %,6d", solutions.containsKey(end) ? solutions.get(end) : 0);
}
System.out.printf("%n");
}
int moveNum = 0;
System.out.printf("%nOne Solution:%n");
for ( Move m : oneSolution ) {
moveNum++;
System.out.printf("Move %d = %s%n", moveNum, m);
}
}
private static List<Move> oneSolution = null;
private static Map<Integer, Integer> solve(int emptyPeg) {
Puzzle puzzle = new Puzzle(emptyPeg);
Map<Integer,Integer> solutions = new HashMap<>();
Stack<Puzzle> stack = new Stack<Puzzle>();
stack.push(puzzle);
while ( ! stack.isEmpty() ) {
Puzzle p = stack.pop();
if ( p.solved() ) {
solutions.merge(p.getLastPeg(), 1, (v1,v2) -> v1 + v2);
if ( oneSolution == null ) {
oneSolution = p.moves;
}
continue;
}
for ( Move move : p.getValidMoves() ) {
Puzzle pMove = p.move(move);
stack.add(pMove);
}
}
return solutions;
}
private static class Puzzle {
public static int MAX_PEGS = 16;
private boolean[] pegs = new boolean[MAX_PEGS];
private List<Move> moves;
public Puzzle(int emptyPeg) {
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
pegs[i] = true;
}
pegs[emptyPeg] = false;
moves = new ArrayList<>();
}
public Puzzle() {
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
pegs[i] = true;
}
moves = new ArrayList<>();
}
private static Map<Integer,List<Move>> validMoves = new HashMap<>();
static {
validMoves.put(1, Arrays.asList(new Move(1, 2, 4), new Move(1, 3, 6)));
validMoves.put(2, Arrays.asList(new Move(2, 4, 7), new Move(2, 5, 9)));
validMoves.put(3, Arrays.asList(new Move(3, 5, 8), new Move(3, 6, 10)));
validMoves.put(4, Arrays.asList(new Move(4, 2, 1), new Move(4, 5, 6), new Move(4, 8, 13), new Move(4, 7, 11)));
validMoves.put(5, Arrays.asList(new Move(5, 8, 12), new Move(5, 9, 14)));
validMoves.put(6, Arrays.asList(new Move(6, 3, 1), new Move(6, 5, 4), new Move(6, 9, 13), new Move(6, 10, 15)));
validMoves.put(7, Arrays.asList(new Move(7, 4, 2), new Move(7, 8, 9)));
validMoves.put(8, Arrays.asList(new Move(8, 5, 3), new Move(8, 9, 10)));
validMoves.put(9, Arrays.asList(new Move(9, 5, 2), new Move(9, 8, 7)));
validMoves.put(10, Arrays.asList(new Move(10, 6, 3), new Move(10, 9, 8)));
validMoves.put(11, Arrays.asList(new Move(11, 7, 4), new Move(11, 12, 13)));
validMoves.put(12, Arrays.asList(new Move(12, 8, 5), new Move(12, 13, 14)));
validMoves.put(13, Arrays.asList(new Move(13, 12, 11), new Move(13, 8, 4), new Move(13, 9, 6), new Move(13, 14, 15)));
validMoves.put(14, Arrays.asList(new Move(14, 13, 12), new Move(14, 9, 5)));
validMoves.put(15, Arrays.asList(new Move(15, 14, 13), new Move(15, 10, 6)));
}
public List<Move> getValidMoves() {
List<Move> moves = new ArrayList<Move>();
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
if ( pegs[i] ) {
for ( Move testMove : validMoves.get(i) ) {
if ( pegs[testMove.jump] && ! pegs[testMove.end] ) {
moves.add(testMove);
}
}
}
}
return moves;
}
public boolean solved() {
boolean foundFirstPeg = false;
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
if ( pegs[i] ) {
if ( foundFirstPeg ) {
return false;
}
foundFirstPeg = true;
}
}
return true;
}
public Puzzle move(Move move) {
Puzzle p = new Puzzle();
if ( ! pegs[move.start] || ! pegs[move.jump] || pegs[move.end] ) {
throw new RuntimeException("Invalid move.");
}
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
p.pegs[i] = pegs[i];
}
p.pegs[move.start] = false;
p.pegs[move.jump] = false;
p.pegs[move.end] = true;
for ( Move m : moves ) {
p.moves.add(new Move(m.start, m.jump, m.end));
}
p.moves.add(new Move(move.start, move.jump, move.end));
return p;
}
public int getLastPeg() {
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
if ( pegs[i] ) {
return i;
}
}
throw new RuntimeException("ERROR: Illegal position.");
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
sb.append(pegs[i] ? 1 : 0);
sb.append(",");
}
sb.setLength(sb.length()-1);
sb.append("]");
return sb.toString();
}
}
private static class Move {
int start;
int jump;
int end;
public Move(int s, int j, int e) {
start = s; jump = j; end = e;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("s=" + start);
sb.append(", j=" + jump);
sb.append(", e=" + end);
sb.append("}");
return sb.toString();
}
}
}
|
G = [[0,1,3],[0,2,5],[1,3,6],[1,4,8],[2,4,7],[2,5,9],[3,4,5],[3,6,10],[3,7,12],[4,7,11],[4,8,13],[5,8,12],[5,9,14],[6,7,8],[7,8,9],[10,11,12],[11,12,13],[12,13,14],
[3,1,0],[5,2,0],[6,3,1],[8,4,1],[7,4,2],[9,5,2],[5,4,3],[10,6,3],[12,7,3],[11,7,4],[13,8,4],[12,8,5],[14,9,5],[8,7,6],[9,8,7],[12,11,10],[13,12,11],[14,13,12]]
FORMAT = (1..5).map{|i| " "*(5-i)+"%d "*i+"\n"}.join+"\n"
def solve n,i,g
return "Solved" if i == 1
return false unless n[g[0]]==0 and n[g[1]]==1 and n[g[2]]==1
e = n.clone; g.each{|n| e[n] = 1 - e[n]}
l=false; G.each{|g| l=solve(e,i-1,g); break if l}
return l ? "
end
puts FORMAT % (N=[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1])
l=false; G.each{|g| l=solve(N,N.inject(:+),g); break if l}
puts l ? l : "No solution found"
|
Generate a Ruby translation of this Java snippet without changing its computational steps. | import java.math.BigInteger;
public class PartitionFunction {
public static void main(String[] args) {
long start = System.currentTimeMillis();
BigInteger result = partitions(6666);
long end = System.currentTimeMillis();
System.out.println("P(6666) = " + result);
System.out.printf("elapsed time: %d milliseconds\n", end - start);
}
private static BigInteger partitions(int n) {
BigInteger[] p = new BigInteger[n + 1];
p[0] = BigInteger.ONE;
for (int i = 1; i <= n; ++i) {
p[i] = BigInteger.ZERO;
for (int k = 1; ; ++k) {
int j = (k * (3 * k - 1))/2;
if (j > i)
break;
if ((k & 1) != 0)
p[i] = p[i].add(p[i - j]);
else
p[i] = p[i].subtract(p[i - j]);
j += k;
if (j > i)
break;
if ((k & 1) != 0)
p[i] = p[i].add(p[i - j]);
else
p[i] = p[i].subtract(p[i - j]);
}
}
return p[n];
}
}
| say partitions(6666)
|
Change the programming language of this snippet from Java to Ruby without modifying what it does. | import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] N = {1, -12, 0, -42};
int[] D = {1, -3};
System.out.printf("%s / %s = %s",
Arrays.toString(N),
Arrays.toString(D),
Arrays.deepToString(extendedSyntheticDivision(N, D)));
}
static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {
int[] out = dividend.clone();
int normalizer = divisor[0];
for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {
out[i] /= normalizer;
int coef = out[i];
if (coef != 0) {
for (int j = 1; j < divisor.length; j++)
out[i + j] += -divisor[j] * coef;
}
}
int separator = out.length - (divisor.length - 1);
return new int[][]{
Arrays.copyOfRange(out, 0, separator),
Arrays.copyOfRange(out, separator, out.length)
};
}
}
| func extended_synthetic_division(dividend, divisor) {
var end = divisor.end
var out = dividend.clone
var normalizer = divisor[0]
for i in ^(dividend.len - end) {
out[i] /= normalizer
var coef = out[i]
if (coef != 0) {
for j in (1 .. end) {
out[i+j] += -(divisor[j] * coef)
}
}
}
var remainder = out.splice(-end)
var quotient = out
return(quotient, remainder)
}
var (n, d) = ([1, -12, 0, -42], [1, -3])
print(" %s / %s =" % (n, d))
print(" %s remainder %s\n" % extended_synthetic_division(n, d))
|
Change the following Java code into Ruby without altering its purpose. | import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] N = {1, -12, 0, -42};
int[] D = {1, -3};
System.out.printf("%s / %s = %s",
Arrays.toString(N),
Arrays.toString(D),
Arrays.deepToString(extendedSyntheticDivision(N, D)));
}
static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {
int[] out = dividend.clone();
int normalizer = divisor[0];
for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {
out[i] /= normalizer;
int coef = out[i];
if (coef != 0) {
for (int j = 1; j < divisor.length; j++)
out[i + j] += -divisor[j] * coef;
}
}
int separator = out.length - (divisor.length - 1);
return new int[][]{
Arrays.copyOfRange(out, 0, separator),
Arrays.copyOfRange(out, separator, out.length)
};
}
}
| func extended_synthetic_division(dividend, divisor) {
var end = divisor.end
var out = dividend.clone
var normalizer = divisor[0]
for i in ^(dividend.len - end) {
out[i] /= normalizer
var coef = out[i]
if (coef != 0) {
for j in (1 .. end) {
out[i+j] += -(divisor[j] * coef)
}
}
}
var remainder = out.splice(-end)
var quotient = out
return(quotient, remainder)
}
var (n, d) = ([1, -12, 0, -42], [1, -3])
print(" %s / %s =" % (n, d))
print(" %s remainder %s\n" % extended_synthetic_division(n, d))
|
Write a version of this Java function in Ruby with identical behavior. | import java.awt.*;
import javax.swing.*;
public class ColorWheel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ColorWheelFrame frame = new ColorWheelFrame();
frame.setVisible(true);
}
});
}
private static class ColorWheelFrame extends JFrame {
private ColorWheelFrame() {
super("Color Wheel");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new ColorWheelPanel());
pack();
}
}
private static class ColorWheelPanel extends JComponent {
private ColorWheelPanel() {
setPreferredSize(new Dimension(400, 400));
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
int margin = 10;
int radius = (Math.min(w, h) - 2 * margin)/2;
int cx = w/2;
int cy = h/2;
float[] dist = {0.F, 1.0F};
g2.setColor(Color.BLACK);
g2.fillRect(0, 0, w, h);
for (int angle = 0; angle < 360; ++angle) {
Color color = hsvToRgb(angle, 1.0, 1.0);
Color[] colors = {Color.WHITE, color};
RadialGradientPaint paint = new RadialGradientPaint(cx, cy,
radius, dist, colors);
g2.setPaint(paint);
g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,
angle, 1);
}
}
}
private static Color hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - Math.abs(hp % 2.0 - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <= 1) {
r = c;
g = x;
} else if (hp <= 2) {
r = x;
g = c;
} else if (hp <= 3) {
g = c;
b = x;
} else if (hp <= 4) {
g = x;
b = c;
} else if (hp <= 5) {
r = x;
b = c;
} else {
r = c;
b = x;
}
r += m;
g += m;
b += m;
return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));
}
}
| def settings
size(300, 300)
end
def setup
sketch_title 'Color Wheel'
background(0)
radius = width / 2.0
center = width / 2
grid(width, height) do |x, y|
rx = x - center
ry = y - center
sat = Math.hypot(rx, ry) / radius
if sat <= 1.0
hue = ((Math.atan2(ry, rx) / PI) + 1) / 2.0
color_mode(HSB)
col = color((hue * 255).to_i, (sat * 255).to_i, 255)
set(x, y, col)
end
end
end
|
Convert the following code from Java to Ruby, ensuring the logic remains intact. | public class MainApp {
public static void main(String[] args) {
int countOfPrimes = 0;
final int targetCountOfPrimes = 10;
long f = 1;
while (countOfPrimes < targetCountOfPrimes) {
long factorialNum = getFactorial(f);
boolean primePlus = isPrime(factorialNum + 1);
boolean primeMinus = isPrime(factorialNum - 1);
if (primeMinus) {
countOfPrimes++;
System.out.println(countOfPrimes + ": " + factorialNum + "! - 1 = " + (factorialNum - 1));
}
if (primePlus && f > 1) {
countOfPrimes++;
System.out.println(countOfPrimes + ": " + factorialNum + "! + 1 = " + (factorialNum + 1));
}
f++;
}
}
private static long getFactorial(long f) {
long factorial = 1;
for (long i = 1; i < f; i++) {
factorial *= i;
}
return factorial;
}
private static boolean isPrime(long num) {
if (num < 2) {return false;}
for (long i = 2; i < num; i++) {
if (num % i == 0) {return false;}
}
return true;
}
}
| require 'openssl'
factorial_primes = Enumerator.new do |y|
fact = 1
(1..).each do |i|
fact *= i
y << [i, "- 1", fact - 1] if OpenSSL::BN.new(fact - 1).prime?
y << [i, "+ 1", fact + 1] if OpenSSL::BN.new(fact + 1).prime?
end
end
factorial_primes.first(30).each do |a|
s = a.last.to_s
if s.size > 40 then
puts "%d! %s = " % a.first(2) + "
else
puts "%d! %s = %d" % a
end
end
|
Rewrite the snippet below in Ruby so it works the same as the original Java code. | import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Random;
import java.util.Scanner;
public class csprngBBS {
public static Scanner input = new Scanner(System.in);
private static final String fileformat = "png";
private static String bitsStri = "";
private static String parityEven = "";
private static String leastSig = "";
private static String randomJavaUtil = "";
private static int width = 0;
private static int BIT_LENGTH = 0;
private static final Random rand = new SecureRandom();
private static BigInteger p = null;
private static BigInteger q = null;
private static BigInteger m = null;
private static BigInteger seed = null;
private static BigInteger seedFinal = null;
private static final Random randMathUtil = new SecureRandom();
public static void main(String[] args) throws IOException {
System.out.print("Width: ");
width = input.nextInt();
System.out.print("Bit-Length: ");
BIT_LENGTH = input.nextInt();
System.out.print("Generator format: ");
String useGenerator = input.next();
p = BigInteger.probablePrime(BIT_LENGTH, rand);
q = BigInteger.probablePrime(BIT_LENGTH, rand);
m = p.multiply(q);
seed = BigInteger.probablePrime(BIT_LENGTH,rand);
seedFinal = seed.add(BigInteger.ZERO);
if(useGenerator.contains("parity") && useGenerator.contains("significant")) {
findLeastSignificant();
findBitParityEven();
createImage(parityEven, "parityEven");
createImage(leastSig, "significant");
}
if(useGenerator.contains("parity") && !useGenerator.contains("significant")){
findBitParityEven();
}
if(useGenerator.contains("significant") && !useGenerator.contains("parity")){
findLeastSignificant();
createImage(leastSig, "significant");
}
if(useGenerator.contains("util")){
findRandomJava(randMathUtil);
createImage(randomJavaUtil, "randomUtilJava");
}
}
public static void findRandomJava(Random random){
for(int x = 1; x <= Math.pow(width, 2); x++){
randomJavaUtil += random.nextInt(2);
}
}
public static void findBitParityEven(){
for(int x = 1; x <= Math.pow(width, 2); x++) {
seed = seed.pow(2).mod(m);
bitsStri = convertBinary(seed);
char[] bits = bitsStri.toCharArray();
int counter = 0;
for (char bit : bits) {
if (bit == '1') {
counter++;
}
}
if (counter % 2 != 0) {
parityEven += "1";
} else {
parityEven += "0";
}
}
}
public static void findLeastSignificant(){
seed = seedFinal;
for(int x = 1; x <= Math.pow(width, 2); x++){
seed = seed.pow(2).mod(m);
leastSig += bitsStri.substring(bitsStri.length() - 1);
}
}
public static String convertBinary(BigInteger value){
StringBuilder total = new StringBuilder();
BigInteger two = BigInteger.TWO;
while(value.compareTo(BigInteger.ZERO) > 0){
total.append(value.mod(two));
value = value.divide(two);
}
return total.reverse().toString();
}
public static void createImage(String useThis, String fileName) throws IOException {
int length = csprngBBS.width;
BufferedImage bufferedImage = new BufferedImage(length, length, 1);
Graphics2D g2d = bufferedImage.createGraphics();
for (int y = 1; y <= length; y++) {
for (int x = 1; x <= length; x++) {
if (useThis.startsWith("1")) {
useThis = useThis.substring(1);
g2d.setColor(Color.BLACK);
g2d.fillRect(x, y, 1, 1);
} else if (useThis.startsWith("0")) {
useThis = useThis.substring(1);
g2d.setColor(Color.WHITE);
g2d.fillRect(x, y, 1, 1);
}
}
System.out.print(y + "\t");
}
g2d.dispose();
File file = new File("REPLACEFILEPATHHERE" + fileName + "." + fileformat);
ImageIO.write(bufferedImage, fileformat, file);
}
}
| require('GD')
var img = %O<GD::Image>.new(500, 500, 1)
for y in (0..500), x in (0..500) {
var color = img.colorAllocate(255.irand, 255.irand, 255.irand)
img.setPixel(x, y, color)
}
File("image500.png").write(img.png, :raw)
|
Ensure the translated Ruby code behaves exactly like the original Java snippet. | import java.io.*;
import java.nio.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.security.*;
import java.util.*;
public class DuplicateFiles {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Directory name and minimum file size are required.");
System.exit(1);
}
try {
findDuplicateFiles(args[0], Long.parseLong(args[1]));
} catch (Exception e) {
e.printStackTrace();
}
}
private static void findDuplicateFiles(String directory, long minimumSize)
throws IOException, NoSuchAlgorithmException {
System.out.println("Directory: '" + directory + "', minimum size: " + minimumSize + " bytes.");
Path path = FileSystems.getDefault().getPath(directory);
FileVisitor visitor = new FileVisitor(path, minimumSize);
Files.walkFileTree(path, visitor);
System.out.println("The following sets of files have the same size and checksum:");
for (Map.Entry<FileKey, Map<Object, List<String>>> e : visitor.fileMap_.entrySet()) {
Map<Object, List<String>> map = e.getValue();
if (!containsDuplicates(map))
continue;
List<List<String>> fileSets = new ArrayList<>(map.values());
for (List<String> files : fileSets)
Collections.sort(files);
Collections.sort(fileSets, new StringListComparator());
FileKey key = e.getKey();
System.out.println();
System.out.println("Size: " + key.size_ + " bytes");
for (List<String> files : fileSets) {
for (int i = 0, n = files.size(); i < n; ++i) {
if (i > 0)
System.out.print(" = ");
System.out.print(files.get(i));
}
System.out.println();
}
}
}
private static class StringListComparator implements Comparator<List<String>> {
public int compare(List<String> a, List<String> b) {
int len1 = a.size(), len2 = b.size();
for (int i = 0; i < len1 && i < len2; ++i) {
int c = a.get(i).compareTo(b.get(i));
if (c != 0)
return c;
}
return Integer.compare(len1, len2);
}
}
private static boolean containsDuplicates(Map<Object, List<String>> map) {
if (map.size() > 1)
return true;
for (List<String> files : map.values()) {
if (files.size() > 1)
return true;
}
return false;
}
private static class FileVisitor extends SimpleFileVisitor<Path> {
private MessageDigest digest_;
private Path directory_;
private long minimumSize_;
private Map<FileKey, Map<Object, List<String>>> fileMap_ = new TreeMap<>();
private FileVisitor(Path directory, long minimumSize) throws NoSuchAlgorithmException {
directory_ = directory;
minimumSize_ = minimumSize;
digest_ = MessageDigest.getInstance("MD5");
}
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (attrs.size() >= minimumSize_) {
FileKey key = new FileKey(file, attrs, getMD5Sum(file));
Map<Object, List<String>> map = fileMap_.get(key);
if (map == null)
fileMap_.put(key, map = new HashMap<>());
List<String> files = map.get(attrs.fileKey());
if (files == null)
map.put(attrs.fileKey(), files = new ArrayList<>());
Path relative = directory_.relativize(file);
files.add(relative.toString());
}
return FileVisitResult.CONTINUE;
}
private byte[] getMD5Sum(Path file) throws IOException {
digest_.reset();
try (InputStream in = new FileInputStream(file.toString())) {
byte[] buffer = new byte[8192];
int bytes;
while ((bytes = in.read(buffer)) != -1) {
digest_.update(buffer, 0, bytes);
}
}
return digest_.digest();
}
}
private static class FileKey implements Comparable<FileKey> {
private byte[] hash_;
private long size_;
private FileKey(Path file, BasicFileAttributes attrs, byte[] hash) throws IOException {
size_ = attrs.size();
hash_ = hash;
}
public int compareTo(FileKey other) {
int c = Long.compare(other.size_, size_);
if (c == 0)
c = hashCompare(hash_, other.hash_);
return c;
}
}
private static int hashCompare(byte[] a, byte[] b) {
int len1 = a.length, len2 = b.length;
for (int i = 0; i < len1 && i < len2; ++i) {
int c = Byte.compare(a[i], b[i]);
if (c != 0)
return c;
}
return Integer.compare(len1, len2);
}
}
| require 'digest/md5'
def find_duplicate_files(dir)
puts "\nDirectory :
Dir.chdir(dir) do
file_size = Dir.foreach('.').select{|f| FileTest.file?(f)}.group_by{|f| File.size(f)}
file_size.each do |size, files|
next if files.size==1
files.group_by{|f| Digest::MD5.file(f).to_s}.each do |md5,fs|
next if fs.size==1
puts " --------------------------------------------"
fs.each{|file| puts "
end
end
end
end
find_duplicate_files("/Windows/System32")
|
Rewrite the snippet below in Ruby so it works the same as the original Java code. | import java.util.*;
public class LegendrePrimeCounter {
public static void main(String[] args) {
LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000);
for (int i = 0, n = 1; i < 10; ++i, n *= 10)
System.out.printf("10^%d\t%d\n", i, counter.primeCount((n)));
}
private List<Integer> primes;
public LegendrePrimeCounter(int limit) {
primes = generatePrimes((int)Math.sqrt((double)limit));
}
public int primeCount(int n) {
if (n < 2)
return 0;
int a = primeCount((int)Math.sqrt((double)n));
return phi(n, a) + a - 1;
}
private int phi(int x, int a) {
if (a == 0)
return x;
if (a == 1)
return x - (x >> 1);
int pa = primes.get(a - 1);
if (x <= pa)
return 1;
return phi(x, a - 1) - phi(x / pa, a - 1);
}
private static List<Integer> generatePrimes(int limit) {
boolean[] sieve = new boolean[limit >> 1];
Arrays.fill(sieve, true);
for (int p = 3, s = 9; s < limit; p += 2) {
if (sieve[p >> 1]) {
for (int q = s; q < limit; q += p << 1)
sieve[q >> 1] = false;
}
s += (p + 1) << 2;
}
List<Integer> primes = new ArrayList<>();
if (limit > 2)
primes.add(2);
for (int i = 1; i < sieve.length; ++i) {
if (sieve[i])
primes.add((i << 1) + 1);
}
return primes;
}
}
| require 'prime'
def pi(n)
@pr = Prime.each(Integer.sqrt(n)).to_a
a = @pr.size
case n
when 0,1 then 0
when 2 then 1
else phi(n,a) + a - 1
end
end
def phi(x,a)
case a
when 0 then x
when 1 then x-(x>>1)
else
pa = @pr[a-1]
return 1 if x <= pa
phi(x, a-1)- phi(x/pa, a-1)
end
end
(0..9).each {|n| puts "10E
|
Change the programming language of this snippet from Java to Ruby without modifying what it does. | import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class FindBareTags {
private static final String BASE = "http:
private static final Pattern TITLE_PATTERN = Pattern.compile("\"title\": \"([^\"]+)\"");
private static final Pattern HEADER_PATTERN = Pattern.compile("==\\{\\{header\\|([^}]+)}}==");
private static final Predicate<String> BARE_PREDICATE = Pattern.compile("<lang>").asPredicate();
public static void main(String[] args) throws Exception {
var client = HttpClient.newBuilder().build();
URI titleUri = URI.create(BASE + "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks");
var titleRequest = HttpRequest.newBuilder(titleUri).GET().build();
var titleResponse = client.send(titleRequest, HttpResponse.BodyHandlers.ofString());
if (titleResponse.statusCode() == 200) {
var titleBody = titleResponse.body();
var titleMatcher = TITLE_PATTERN.matcher(titleBody);
var titleList = titleMatcher.results().map(mr -> mr.group(1)).collect(Collectors.toList());
var countMap = new HashMap<String, Integer>();
for (String title : titleList) {
var pageUri = new URI("http", null, "
var pageRequest = HttpRequest.newBuilder(pageUri).GET().build();
var pageResponse = client.send(pageRequest, HttpResponse.BodyHandlers.ofString());
if (pageResponse.statusCode() == 200) {
var pageBody = pageResponse.body();
AtomicReference<String> language = new AtomicReference<>("no language");
pageBody.lines().forEach(line -> {
var headerMatcher = HEADER_PATTERN.matcher(line);
if (headerMatcher.matches()) {
language.set(headerMatcher.group(1));
} else if (BARE_PREDICATE.test(line)) {
int count = countMap.getOrDefault(language.get(), 0) + 1;
countMap.put(language.get(), count);
}
});
} else {
System.out.printf("Got a %d status code%n", pageResponse.statusCode());
}
}
for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
System.out.printf("%d in %s%n", entry.getValue(), entry.getKey());
}
} else {
System.out.printf("Got a %d status code%n", titleResponse.statusCode());
}
}
}
| require "open-uri"
require "cgi"
tasks = ["Greatest_common_divisor", "Greatest_element_of_a_list", "Greatest_subsequential_sum"]
part_uri = "http://rosettacode.org/wiki?action=raw&title="
Report = Struct.new(:count, :tasks)
result = Hash.new{|h,k| h[k] = Report.new(0, [])}
tasks.each do |task|
puts "processing
current_lang = "no language"
open(part_uri + CGI.escape(task)).each_line do |line|
current_lang = Regexp.last_match["lang"] if /==\{\{header\|(?<lang>.+)\}\}==/ =~ line
num_no_langs = line.scan(/<lang\s*>/).size
if num_no_langs > 0 then
result[current_lang].count += num_no_langs
result[current_lang].tasks << task
end
end
end
puts "\n
result.each{|k,v| puts "
|
Transform the following Java implementation into Ruby, maintaining the same output and logic. | import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
BigInteger d = new BigInteger("3"), a;
int lmt = 25, sl, c = 0;
for (int i = 3; i < 5808; ) {
a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);
if (a.isProbablePrime(1)) {
System.out.printf("%2d %4d ", ++c, i);
String s = a.toString(); sl = s.length();
if (sl < lmt) System.out.println(a);
else System.out.println(s.substring(0, 11) + ".." + s.substring(sl - 11, sl) + " " + sl + " digits");
}
i = BigInteger.valueOf(i).nextProbablePrime().intValue();
}
}
}
| require 'prime'
require 'gmp'
wagstaffs = Enumerator.new do |y|
odd_primes = Prime.each
odd_primes.next
loop do
p = odd_primes.next
candidate = (2 ** p + 1)/3
y << [p, candidate] unless GMP::Z.new(candidate).probab_prime?.zero?
end
end
10.times{puts "%5d - %s" % wagstaffs.next}
14.times{puts "%5d" % wagstaffs.next.first}
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
BigInteger d = new BigInteger("3"), a;
int lmt = 25, sl, c = 0;
for (int i = 3; i < 5808; ) {
a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);
if (a.isProbablePrime(1)) {
System.out.printf("%2d %4d ", ++c, i);
String s = a.toString(); sl = s.length();
if (sl < lmt) System.out.println(a);
else System.out.println(s.substring(0, 11) + ".." + s.substring(sl - 11, sl) + " " + sl + " digits");
}
i = BigInteger.valueOf(i).nextProbablePrime().intValue();
}
}
}
| require 'prime'
require 'gmp'
wagstaffs = Enumerator.new do |y|
odd_primes = Prime.each
odd_primes.next
loop do
p = odd_primes.next
candidate = (2 ** p + 1)/3
y << [p, candidate] unless GMP::Z.new(candidate).probab_prime?.zero?
end
end
10.times{puts "%5d - %s" % wagstaffs.next}
14.times{puts "%5d" % wagstaffs.next.first}
|
Change the following Java code into Ruby without altering its purpose. | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PalindromicGapfulNumbers {
public static void main(String[] args) {
System.out.println("First 20 palindromic gapful numbers ending in:");
displayMap(getPalindromicGapfulEnding(20, 20));
System.out.printf("%nLast 15 of first 100 palindromic gapful numbers ending in:%n");
displayMap(getPalindromicGapfulEnding(15, 100));
System.out.printf("%nLast 10 of first 1000 palindromic gapful numbers ending in:%n");
displayMap(getPalindromicGapfulEnding(10, 1000));
}
private static void displayMap(Map<Integer,List<Long>> map) {
for ( int key = 1 ; key <= 9 ; key++ ) {
System.out.println(key + " : " + map.get(key));
}
}
public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {
Map<Integer,List<Long>> map = new HashMap<>();
Map<Integer,Integer> mapCount = new HashMap<>();
for ( int i = 1 ; i <= 9 ; i++ ) {
map.put(i, new ArrayList<>());
mapCount.put(i, 0);
}
boolean notPopulated = true;
for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {
if ( isGapful(n) ) {
int index = (int) (n % 10);
if ( mapCount.get(index) < firstHowMany ) {
map.get(index).add(n);
mapCount.put(index, mapCount.get(index) + 1);
if ( map.get(index).size() > countReturned ) {
map.get(index).remove(0);
}
}
boolean finished = true;
for ( int i = 1 ; i <= 9 ; i++ ) {
if ( mapCount.get(i) < firstHowMany ) {
finished = false;
break;
}
}
if ( finished ) {
notPopulated = false;
}
}
}
return map;
}
public static boolean isGapful(long n) {
String s = Long.toString(n);
return n % Long.parseLong("" + s.charAt(0) + s.charAt(s.length()-1)) == 0;
}
public static int length(long n) {
int length = 0;
while ( n > 0 ) {
length += 1;
n /= 10;
}
return length;
}
public static long nextPalindrome(long n) {
int length = length(n);
if ( length % 2 == 0 ) {
length /= 2;
while ( length > 0 ) {
n /= 10;
length--;
}
n += 1;
if ( powerTen(n) ) {
return Long.parseLong(n + reverse(n/10));
}
return Long.parseLong(n + reverse(n));
}
length = (length - 1) / 2;
while ( length > 0 ) {
n /= 10;
length--;
}
n += 1;
if ( powerTen(n) ) {
return Long.parseLong(n + reverse(n/100));
}
return Long.parseLong(n + reverse(n/10));
}
private static boolean powerTen(long n) {
while ( n > 9 && n % 10 == 0 ) {
n /= 10;
}
return n == 1;
}
private static String reverse(long n) {
return (new StringBuilder(n + "")).reverse().toString();
}
}
| def palindromesgapful(digit, pow)
r1 = (10_u64**pow + 1) * digit
r2 = 10_u64**pow * (digit + 1)
nn = digit * 11
(r1...r2).select { |i| n = i.to_s; n == n.reverse && i.divisible_by?(nn) }
end
def digitscount(digit, count)
pow = 2
nums = [] of UInt64
while nums.size < count
nums += palindromesgapful(digit, pow)
pow += 1
end
nums[0...count]
end
count = 20
puts "First 20 palindromic gapful numbers ending with:"
(1..9).each { |digit| print "
count = 100
puts "\nLast 15 of first 100 palindromic gapful numbers ending in:"
(1..9).each { |digit| print "
count = 1000
puts "\nLast 10 of first 1000 palindromic gapful numbers ending in:"
(1..9).each { |digit| print "
|
Preserve the algorithm and functionality while converting the code from Java to Ruby. | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PalindromicGapfulNumbers {
public static void main(String[] args) {
System.out.println("First 20 palindromic gapful numbers ending in:");
displayMap(getPalindromicGapfulEnding(20, 20));
System.out.printf("%nLast 15 of first 100 palindromic gapful numbers ending in:%n");
displayMap(getPalindromicGapfulEnding(15, 100));
System.out.printf("%nLast 10 of first 1000 palindromic gapful numbers ending in:%n");
displayMap(getPalindromicGapfulEnding(10, 1000));
}
private static void displayMap(Map<Integer,List<Long>> map) {
for ( int key = 1 ; key <= 9 ; key++ ) {
System.out.println(key + " : " + map.get(key));
}
}
public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {
Map<Integer,List<Long>> map = new HashMap<>();
Map<Integer,Integer> mapCount = new HashMap<>();
for ( int i = 1 ; i <= 9 ; i++ ) {
map.put(i, new ArrayList<>());
mapCount.put(i, 0);
}
boolean notPopulated = true;
for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {
if ( isGapful(n) ) {
int index = (int) (n % 10);
if ( mapCount.get(index) < firstHowMany ) {
map.get(index).add(n);
mapCount.put(index, mapCount.get(index) + 1);
if ( map.get(index).size() > countReturned ) {
map.get(index).remove(0);
}
}
boolean finished = true;
for ( int i = 1 ; i <= 9 ; i++ ) {
if ( mapCount.get(i) < firstHowMany ) {
finished = false;
break;
}
}
if ( finished ) {
notPopulated = false;
}
}
}
return map;
}
public static boolean isGapful(long n) {
String s = Long.toString(n);
return n % Long.parseLong("" + s.charAt(0) + s.charAt(s.length()-1)) == 0;
}
public static int length(long n) {
int length = 0;
while ( n > 0 ) {
length += 1;
n /= 10;
}
return length;
}
public static long nextPalindrome(long n) {
int length = length(n);
if ( length % 2 == 0 ) {
length /= 2;
while ( length > 0 ) {
n /= 10;
length--;
}
n += 1;
if ( powerTen(n) ) {
return Long.parseLong(n + reverse(n/10));
}
return Long.parseLong(n + reverse(n));
}
length = (length - 1) / 2;
while ( length > 0 ) {
n /= 10;
length--;
}
n += 1;
if ( powerTen(n) ) {
return Long.parseLong(n + reverse(n/100));
}
return Long.parseLong(n + reverse(n/10));
}
private static boolean powerTen(long n) {
while ( n > 9 && n % 10 == 0 ) {
n /= 10;
}
return n == 1;
}
private static String reverse(long n) {
return (new StringBuilder(n + "")).reverse().toString();
}
}
| def palindromesgapful(digit, pow)
r1 = (10_u64**pow + 1) * digit
r2 = 10_u64**pow * (digit + 1)
nn = digit * 11
(r1...r2).select { |i| n = i.to_s; n == n.reverse && i.divisible_by?(nn) }
end
def digitscount(digit, count)
pow = 2
nums = [] of UInt64
while nums.size < count
nums += palindromesgapful(digit, pow)
pow += 1
end
nums[0...count]
end
count = 20
puts "First 20 palindromic gapful numbers ending with:"
(1..9).each { |digit| print "
count = 100
puts "\nLast 15 of first 100 palindromic gapful numbers ending in:"
(1..9).each { |digit| print "
count = 1000
puts "\nLast 10 of first 1000 palindromic gapful numbers ending in:"
(1..9).each { |digit| print "
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class ChernicksCarmichaelNumbers {
public static void main(String[] args) {
for ( long n = 3 ; n < 10 ; n++ ) {
long m = 0;
boolean foundComposite = true;
List<Long> factors = null;
while ( foundComposite ) {
m += (n <= 4 ? 1 : (long) Math.pow(2, n-4) * 5);
factors = U(n, m);
foundComposite = false;
for ( long factor : factors ) {
if ( ! isPrime(factor) ) {
foundComposite = true;
break;
}
}
}
System.out.printf("U(%d, %d) = %s = %s %n", n, m, display(factors), multiply(factors));
}
}
private static String display(List<Long> factors) {
return factors.toString().replace("[", "").replace("]", "").replaceAll(", ", " * ");
}
private static BigInteger multiply(List<Long> factors) {
BigInteger result = BigInteger.ONE;
for ( long factor : factors ) {
result = result.multiply(BigInteger.valueOf(factor));
}
return result;
}
private static List<Long> U(long n, long m) {
List<Long> factors = new ArrayList<>();
factors.add(6*m + 1);
factors.add(12*m + 1);
for ( int i = 1 ; i <= n-2 ; i++ ) {
factors.add(((long)Math.pow(2, i)) * 9 * m + 1);
}
return factors;
}
private static final int MAX = 100_000;
private static final boolean[] primes = new boolean[MAX];
private static boolean SIEVE_COMPLETE = false;
private static final boolean isPrimeTrivial(long test) {
if ( ! SIEVE_COMPLETE ) {
sieve();
SIEVE_COMPLETE = true;
}
return primes[(int) test];
}
private static final void sieve() {
for ( int i = 2 ; i < MAX ; i++ ) {
primes[i] = true;
}
for ( int i = 2 ; i < MAX ; i++ ) {
if ( primes[i] ) {
for ( int j = 2*i ; j < MAX ; j += i ) {
primes[j] = false;
}
}
}
}
public static final boolean isPrime(long testValue) {
if ( testValue == 2 ) return true;
if ( testValue % 2 == 0 ) return false;
if ( testValue <= MAX ) return isPrimeTrivial(testValue);
long d = testValue-1;
int s = 0;
while ( d % 2 == 0 ) {
s += 1;
d /= 2;
}
if ( testValue < 1373565L ) {
if ( ! aSrp(2, s, d, testValue) ) {
return false;
}
if ( ! aSrp(3, s, d, testValue) ) {
return false;
}
return true;
}
if ( testValue < 4759123141L ) {
if ( ! aSrp(2, s, d, testValue) ) {
return false;
}
if ( ! aSrp(7, s, d, testValue) ) {
return false;
}
if ( ! aSrp(61, s, d, testValue) ) {
return false;
}
return true;
}
if ( testValue < 10000000000000000L ) {
if ( ! aSrp(3, s, d, testValue) ) {
return false;
}
if ( ! aSrp(24251, s, d, testValue) ) {
return false;
}
return true;
}
if ( ! aSrp(37, s, d, testValue) ) {
return false;
}
if ( ! aSrp(47, s, d, testValue) ) {
return false;
}
if ( ! aSrp(61, s, d, testValue) ) {
return false;
}
if ( ! aSrp(73, s, d, testValue) ) {
return false;
}
if ( ! aSrp(83, s, d, testValue) ) {
return false;
}
return true;
}
private static final boolean aSrp(int a, int s, long d, long n) {
long modPow = modPow(a, d, n);
if ( modPow == 1 ) {
return true;
}
int twoExpR = 1;
for ( int r = 0 ; r < s ; r++ ) {
if ( modPow(modPow, twoExpR, n) == n-1 ) {
return true;
}
twoExpR *= 2;
}
return false;
}
private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);
public static final long modPow(long base, long exponent, long modulus) {
long result = 1;
while ( exponent > 0 ) {
if ( exponent % 2 == 1 ) {
if ( result > SQRT || base > SQRT ) {
result = multiply(result, base, modulus);
}
else {
result = (result * base) % modulus;
}
}
exponent >>= 1;
if ( base > SQRT ) {
base = multiply(base, base, modulus);
}
else {
base = (base * base) % modulus;
}
}
return result;
}
public static final long multiply(long a, long b, long modulus) {
long x = 0;
long y = a % modulus;
long t;
while ( b > 0 ) {
if ( b % 2 == 1 ) {
t = x + y;
x = (t > modulus ? t-modulus : t);
}
t = y << 1;
y = (t > modulus ? t-modulus : t);
b >>= 1;
}
return x % modulus;
}
}
| func chernick_carmichael_factors (n, m) {
[6*m + 1, 12*m + 1, {|i| 2**i * 9*m + 1 }.map(1 .. n-2)...]
}
func is_chernick_carmichael (n, m) {
(n == 2) ? (is_prime(6*m + 1) && is_prime(12*m + 1))
: (is_prime(2**(n-2) * 9*m + 1) && __FUNC__(n-1, m))
}
func chernick_carmichael_number(n, callback) {
var multiplier = (n>4 ? 2**(n-4) : 1)
var m = (1..Inf -> first {|m| is_chernick_carmichael(n, m * multiplier) })
var f = chernick_carmichael_factors(n, m * multiplier)
callback(f...)
}
for n in (3..9) {
chernick_carmichael_number(n, {|*f| say "a(
}
|
Port the following code from Java to Ruby with equivalent syntax and logic. | import java.math.BigInteger;
import java.util.*;
public class WilsonPrimes {
public static void main(String[] args) {
final int limit = 11000;
BigInteger[] f = new BigInteger[limit];
f[0] = BigInteger.ONE;
BigInteger factorial = BigInteger.ONE;
for (int i = 1; i < limit; ++i) {
factorial = factorial.multiply(BigInteger.valueOf(i));
f[i] = factorial;
}
List<Integer> primes = generatePrimes(limit);
System.out.printf(" n | Wilson primes\n--------------------\n");
BigInteger s = BigInteger.valueOf(-1);
for (int n = 1; n <= 11; ++n) {
System.out.printf("%2d |", n);
for (int p : primes) {
if (p >= n && f[n - 1].multiply(f[p - n]).subtract(s)
.mod(BigInteger.valueOf(p * p))
.equals(BigInteger.ZERO))
System.out.printf(" %d", p);
}
s = s.negate();
System.out.println();
}
}
private static List<Integer> generatePrimes(int limit) {
boolean[] sieve = new boolean[limit >> 1];
Arrays.fill(sieve, true);
for (int p = 3, s = 9; s < limit; p += 2) {
if (sieve[p >> 1]) {
for (int q = s; q < limit; q += p << 1)
sieve[q >> 1] = false;
}
s += (p + 1) << 2;
}
List<Integer> primes = new ArrayList<>();
if (limit > 2)
primes.add(2);
for (int i = 1; i < sieve.length; ++i) {
if (sieve[i])
primes.add((i << 1) + 1);
}
return primes;
}
}
| require "prime"
module Modulo
refine Integer do
def factorial_mod(m) = (1..self).inject(1){|prod, n| (prod *= n) % m }
end
end
using Modulo
primes = Prime.each(11000).to_a
(1..11).each do |n|
res = primes.select do |pr|
prpr = pr*pr
((n-1).factorial_mod(prpr) * (pr-n).factorial_mod(prpr) - (-1)**n) % (prpr) == 0
end
puts "
end
|
Produce a language-to-language conversion: from Java to Ruby, same semantics. | import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class SphenicNumbers {
public static void main(String[] args) {
final int limit = 1000000;
final int imax = limit / 6;
boolean[] sieve = primeSieve(imax + 1);
boolean[] sphenic = new boolean[limit + 1];
for (int i = 0; i <= imax; ++i) {
if (!sieve[i])
continue;
int jmax = Math.min(imax, limit / (i * i));
if (jmax <= i)
break;
for (int j = i + 1; j <= jmax; ++j) {
if (!sieve[j])
continue;
int p = i * j;
int kmax = Math.min(imax, limit / p);
if (kmax <= j)
break;
for (int k = j + 1; k <= kmax; ++k) {
if (!sieve[k])
continue;
assert(p * k <= limit);
sphenic[p * k] = true;
}
}
}
System.out.println("Sphenic numbers < 1000:");
for (int i = 0, n = 0; i < 1000; ++i) {
if (!sphenic[i])
continue;
++n;
System.out.printf("%3d%c", i, n % 15 == 0 ? '\n' : ' ');
}
System.out.println("\nSphenic triplets < 10,000:");
for (int i = 0, n = 0; i < 10000; ++i) {
if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {
++n;
System.out.printf("(%d, %d, %d)%c",
i - 2, i - 1, i, n % 3 == 0 ? '\n' : ' ');
}
}
int count = 0, triplets = 0, s200000 = 0, t5000 = 0;
for (int i = 0; i < limit; ++i) {
if (!sphenic[i])
continue;
++count;
if (count == 200000)
s200000 = i;
if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {
++triplets;
if (triplets == 5000)
t5000 = i;
}
}
System.out.printf("\nNumber of sphenic numbers < 1,000,000: %d\n", count);
System.out.printf("Number of sphenic triplets < 1,000,000: %d\n", triplets);
List<Integer> factors = primeFactors(s200000);
assert(factors.size() == 3);
System.out.printf("The 200,000th sphenic number: %d = %d * %d * %d\n",
s200000, factors.get(0), factors.get(1),
factors.get(2));
System.out.printf("The 5,000th sphenic triplet: (%d, %d, %d)\n",
t5000 - 2, t5000 - 1, t5000);
}
private static boolean[] primeSieve(int limit) {
boolean[] sieve = new boolean[limit];
Arrays.fill(sieve, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (sieve[p]) {
for (int q = sq; q < limit; q += p << 1)
sieve[q] = false;
}
sq += (p + 1) << 2;
}
return sieve;
}
private static List<Integer> primeFactors(int n) {
List<Integer> factors = new ArrayList<>();
if (n > 1 && (n & 1) == 0) {
factors.add(2);
while ((n & 1) == 0)
n >>= 1;
}
for (int p = 3; p * p <= n; p += 2) {
if (n % p == 0) {
factors.add(p);
while (n % p == 0)
n /= p;
}
}
if (n > 1)
factors.add(n);
return factors;
}
}
| require 'prime'
class Integer
def sphenic? = prime_division.map(&:last) == [1, 1, 1]
end
sphenics = (1..).lazy.select(&:sphenic?)
n = 1000
puts "Sphenic numbers less than
p sphenics.take_while{|s| s < n}.to_a
n = 10_000
puts "\nSphenic triplets less than
sps = sphenics.take_while{|s| s < n}.to_a
sps.each_cons(3).select{|a, b, c| a + 2 == c}.each{|ar| p ar}
n = 1_000_000
sphenics_below10E6 = sphenics.take_while{|s| s < n}.to_a
puts "\nThere are
target = sphenics_below10E6[200_000-1]
puts "\nThe 200000th sphenic number is
triplets = sphenics_below10E6.each_cons(3).select{|a,b,c|a+2 == c}
puts "\nThe 5000th sphenic triplet is
|
Generate an equivalent Ruby version of this Java code. | import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.ws.Holder;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class XmlValidation {
public static void main(String... args) throws MalformedURLException {
URL schemaLocation = new URL("http:
URL documentLocation = new URL("http:
if (validate(schemaLocation, documentLocation)) {
System.out.println("document is valid");
} else {
System.out.println("document is invalid");
}
}
public static boolean minimalValidate(URL schemaLocation, URL documentLocation) {
SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
try {
Validator validator = factory.newSchema(schemaLocation).newValidator();
validator.validate(new StreamSource(documentLocation.toString()));
return true;
} catch (Exception e) {
return false;
}
}
public static boolean validate(URL schemaLocation, URL documentLocation) {
SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
final Holder<Boolean> valid = new Holder<>(true);
try {
Validator validator = factory.newSchema(schemaLocation).newValidator();
validator.setErrorHandler(new ErrorHandler(){
@Override
public void warning(SAXParseException exception) {
System.out.println("warning: " + exception.getMessage());
}
@Override
public void error(SAXParseException exception) {
System.out.println("error: " + exception.getMessage());
valid.value = false;
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
System.out.println("fatal error: " + exception.getMessage());
throw exception;
}});
validator.validate(new StreamSource(documentLocation.toString()));
return valid.value;
} catch (SAXException e) {
return false;
} catch (Exception e) {
System.err.println(e);
return false;
}
}
}
| require('XML::LibXML')
func is_valid_xml(str, schema) {
var parser = %O<XML::LibXML>.new
var xmlschema = %O<XML::LibXML::Schema>.new(string => schema)
try {
xmlschema.validate(parser.parse_string(str))
true
} catch {
false
}
}
var good_xml = '<a>5</a>'
var bad_xml = '<a>5<b>foobar</b></a>'
var xmlschema_markup = <<'END'
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="a" type="xsd:integer"/>
</xsd:schema>
END
[good_xml, bad_xml].each { |xml|
say "is_valid_xml(
}
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.List;
public class MetallicRatios {
private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin", "Lead"};
public static void main(String[] args) {
int elements = 15;
for ( int b = 0 ; b < 10 ; b++ ) {
System.out.printf("Lucas sequence for %s ratio, where b = %d:%n", ratioDescription[b], b);
System.out.printf("First %d elements: %s%n", elements, lucasSequence(1, 1, b, elements));
int decimalPlaces = 32;
BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);
System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]);
System.out.printf("%n");
}
int b = 1;
int decimalPlaces = 256;
System.out.printf("%s ratio, where b = %d:%n", ratioDescription[b], b);
BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);
System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]);
}
private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {
BigDecimal x0Bi = BigDecimal.valueOf(x0);
BigDecimal x1Bi = BigDecimal.valueOf(x1);
BigDecimal bBi = BigDecimal.valueOf(b);
MathContext mc = new MathContext(digits);
BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);
int iterations = 0;
while ( true ) {
iterations++;
BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);
BigDecimal fractionCurrent = x.divide(x1Bi, mc);
if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {
break;
}
x0Bi = x1Bi;
x1Bi = x;
fractionPrior = fractionCurrent;
}
return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};
}
private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {
List<BigInteger> list = new ArrayList<>();
BigInteger x0Bi = BigInteger.valueOf(x0);
BigInteger x1Bi = BigInteger.valueOf(x1);
BigInteger bBi = BigInteger.valueOf(b);
if ( n > 0 ) {
list.add(x0Bi);
}
if ( n > 1 ) {
list.add(x1Bi);
}
while ( n > 2 ) {
BigInteger x = bBi.multiply(x1Bi).add(x0Bi);
list.add(x);
n--;
x0Bi = x1Bi;
x1Bi = x;
}
return list;
}
}
| require('bigdecimal')
require('bigdecimal/util')
def lucas(b)
Enumerator.new do |yielder|
xn2 = 1 ; yielder.yield(xn2)
xn1 = 1 ; yielder.yield(xn1)
loop { xn2, xn1 = xn1, b * xn1 + xn2 ; yielder.yield(xn1) }
end
end
def metallic_ratio(b, precision)
xn2 = xn1 = prev = this = 0
lucas(b).each.with_index do |xn, inx|
case inx
when 0
xn2 = BigDecimal(xn)
when 1
xn1 = BigDecimal(xn)
prev = xn1.div(xn2, 2 * precision).round(precision)
else
xn2, xn1 = xn1, BigDecimal(xn)
this = xn1.div(xn2, 2 * precision).round(precision)
return Struct.new(:ratio, :terms).new(prev, inx - 1) if prev == this
prev = this
end
end
end
NAMES = [ 'Platinum', 'Golden', 'Silver', 'Bronze', 'Copper',
'Nickel', 'Aluminum', 'Iron', 'Tin', 'Lead' ]
puts
puts('Lucas Sequences...')
puts('%1s %s' % ['b', 'sequence'])
(0..9).each do |b|
puts('%1d %s' % [b, lucas(b).first(15)])
end
puts
puts('Metallic Ratios to 32 places...')
puts('%-9s %1s %3s %s' % ['name', 'b', 'n', 'ratio'])
(0..9).each do |b|
rn = metallic_ratio(b, 32)
puts('%-9s %1d %3d %s' % [NAMES[b], b, rn.terms, rn.ratio.to_s('F')])
end
puts
puts('Golden Ratio to 256 places...')
puts('%-9s %1s %3s %s' % ['name', 'b', 'n', 'ratio'])
gold_rn = metallic_ratio(1, 256)
puts('%-9s %1d %3d %s' % [NAMES[1], 1, gold_rn.terms, gold_rn.ratio.to_s('F')])
|
Produce a language-to-language conversion: from Java to Ruby, same semantics. | import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.List;
public class MetallicRatios {
private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin", "Lead"};
public static void main(String[] args) {
int elements = 15;
for ( int b = 0 ; b < 10 ; b++ ) {
System.out.printf("Lucas sequence for %s ratio, where b = %d:%n", ratioDescription[b], b);
System.out.printf("First %d elements: %s%n", elements, lucasSequence(1, 1, b, elements));
int decimalPlaces = 32;
BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);
System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]);
System.out.printf("%n");
}
int b = 1;
int decimalPlaces = 256;
System.out.printf("%s ratio, where b = %d:%n", ratioDescription[b], b);
BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);
System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]);
}
private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {
BigDecimal x0Bi = BigDecimal.valueOf(x0);
BigDecimal x1Bi = BigDecimal.valueOf(x1);
BigDecimal bBi = BigDecimal.valueOf(b);
MathContext mc = new MathContext(digits);
BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);
int iterations = 0;
while ( true ) {
iterations++;
BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);
BigDecimal fractionCurrent = x.divide(x1Bi, mc);
if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {
break;
}
x0Bi = x1Bi;
x1Bi = x;
fractionPrior = fractionCurrent;
}
return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};
}
private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {
List<BigInteger> list = new ArrayList<>();
BigInteger x0Bi = BigInteger.valueOf(x0);
BigInteger x1Bi = BigInteger.valueOf(x1);
BigInteger bBi = BigInteger.valueOf(b);
if ( n > 0 ) {
list.add(x0Bi);
}
if ( n > 1 ) {
list.add(x1Bi);
}
while ( n > 2 ) {
BigInteger x = bBi.multiply(x1Bi).add(x0Bi);
list.add(x);
n--;
x0Bi = x1Bi;
x1Bi = x;
}
return list;
}
}
| require('bigdecimal')
require('bigdecimal/util')
def lucas(b)
Enumerator.new do |yielder|
xn2 = 1 ; yielder.yield(xn2)
xn1 = 1 ; yielder.yield(xn1)
loop { xn2, xn1 = xn1, b * xn1 + xn2 ; yielder.yield(xn1) }
end
end
def metallic_ratio(b, precision)
xn2 = xn1 = prev = this = 0
lucas(b).each.with_index do |xn, inx|
case inx
when 0
xn2 = BigDecimal(xn)
when 1
xn1 = BigDecimal(xn)
prev = xn1.div(xn2, 2 * precision).round(precision)
else
xn2, xn1 = xn1, BigDecimal(xn)
this = xn1.div(xn2, 2 * precision).round(precision)
return Struct.new(:ratio, :terms).new(prev, inx - 1) if prev == this
prev = this
end
end
end
NAMES = [ 'Platinum', 'Golden', 'Silver', 'Bronze', 'Copper',
'Nickel', 'Aluminum', 'Iron', 'Tin', 'Lead' ]
puts
puts('Lucas Sequences...')
puts('%1s %s' % ['b', 'sequence'])
(0..9).each do |b|
puts('%1d %s' % [b, lucas(b).first(15)])
end
puts
puts('Metallic Ratios to 32 places...')
puts('%-9s %1s %3s %s' % ['name', 'b', 'n', 'ratio'])
(0..9).each do |b|
rn = metallic_ratio(b, 32)
puts('%-9s %1d %3d %s' % [NAMES[b], b, rn.terms, rn.ratio.to_s('F')])
end
puts
puts('Golden Ratio to 256 places...')
puts('%-9s %1s %3s %s' % ['name', 'b', 'n', 'ratio'])
gold_rn = metallic_ratio(1, 256)
puts('%-9s %1d %3d %s' % [NAMES[1], 1, gold_rn.terms, gold_rn.ratio.to_s('F')])
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | import java.util.*;
public class ErdosSelfridge {
private int[] primes;
private int[] category;
public static void main(String[] args) {
ErdosSelfridge es = new ErdosSelfridge(1000000);
System.out.println("First 200 primes:");
for (var e : es.getPrimesByCategory(200).entrySet()) {
int category = e.getKey();
List<Integer> primes = e.getValue();
System.out.printf("Category %d:\n", category);
for (int i = 0, n = primes.size(); i != n; ++i)
System.out.printf("%4d%c", primes.get(i), (i + 1) % 15 == 0 ? '\n' : ' ');
System.out.printf("\n\n");
}
System.out.println("First 1,000,000 primes:");
for (var e : es.getPrimesByCategory(1000000).entrySet()) {
int category = e.getKey();
List<Integer> primes = e.getValue();
System.out.printf("Category %2d: first = %7d last = %8d count = %d\n", category,
primes.get(0), primes.get(primes.size() - 1), primes.size());
}
}
private ErdosSelfridge(int limit) {
PrimeGenerator primeGen = new PrimeGenerator(100000, 200000);
List<Integer> primeList = new ArrayList<>();
for (int i = 0; i < limit; ++i)
primeList.add(primeGen.nextPrime());
primes = new int[primeList.size()];
for (int i = 0; i < primes.length; ++i)
primes[i] = primeList.get(i);
category = new int[primes.length];
}
private Map<Integer, List<Integer>> getPrimesByCategory(int limit) {
Map<Integer, List<Integer>> result = new TreeMap<>();
for (int i = 0; i < limit; ++i) {
var p = result.computeIfAbsent(getCategory(i), k -> new ArrayList<Integer>());
p.add(primes[i]);
}
return result;
}
private int getCategory(int index) {
if (category[index] != 0)
return category[index];
int maxCategory = 0;
int n = primes[index] + 1;
for (int i = 0; n > 1; ++i) {
int p = primes[i];
if (p * p > n)
break;
int count = 0;
for (; n % p == 0; ++count)
n /= p;
if (count != 0) {
int category = (p <= 3) ? 1 : 1 + getCategory(i);
maxCategory = Math.max(maxCategory, category);
}
}
if (n > 1) {
int category = (n <= 3) ? 1 : 1 + getCategory(getIndex(n));
maxCategory = Math.max(maxCategory, category);
}
category[index] = maxCategory;
return maxCategory;
}
private int getIndex(int prime) {
return Arrays.binarySearch(primes, prime);
}
}
| func Erdös_Selfridge_class(n, s=1) is cached {
var f = factor_exp(n+s)
f.last.head > 3 || return 1
f.map {|p| __FUNC__(p.head, s) }.max + 1
}
say "First two hundred primes; Erdös-Selfridge categorized:"
200.pn_primes.group_by(Erdös_Selfridge_class).sort_by{.to_i}.each_2d {|k,v|
say "
}
say "\nSummary of first 10^6 primes; Erdös-Selfridge categorized:";
1e6.pn_primes.group_by(Erdös_Selfridge_class).sort_by{.to_i}.each_2d {|k,v|
printf("Category %2d: first: %9s last: %10s count: %s\n", k, v.first, v.last, v.len)
}
|
Convert this Java block to Ruby, preserving its control flow and logic. | import java.util.HashMap;
import java.util.Map;
public class PrimeGaps {
private Map<Integer, Integer> gapStarts = new HashMap<>();
private int lastPrime;
private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);
public static void main(String[] args) {
final int limit = 100000000;
PrimeGaps pg = new PrimeGaps();
for (int pm = 10, gap1 = 2;;) {
int start1 = pg.findGapStart(gap1);
int gap2 = gap1 + 2;
int start2 = pg.findGapStart(gap2);
int diff = start2 > start1 ? start2 - start1 : start1 - start2;
if (diff > pm) {
System.out.printf(
"Earliest difference > %,d between adjacent prime gap starting primes:\n"
+ "Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\n\n",
pm, gap1, start1, gap2, start2, diff);
if (pm == limit)
break;
pm *= 10;
} else {
gap1 = gap2;
}
}
}
private int findGapStart(int gap) {
Integer start = gapStarts.get(gap);
if (start != null)
return start;
for (;;) {
int prev = lastPrime;
lastPrime = primeGenerator.nextPrime();
int diff = lastPrime - prev;
gapStarts.putIfAbsent(diff, prev);
if (diff == gap)
return prev;
}
}
}
| func prime_gap_records(upto) {
var gaps = []
var p = 3
each_prime(p.next_prime, upto, {|q|
gaps[q-p] := p
p = q
})
gaps.grep { defined(_) }
}
var gaps = prime_gap_records(1e8)
for m in (1 .. gaps.max.len) {
gaps.each_cons(2, {|p,q|
if (abs(q-p) > 10**m) {
say "10^
p.next_prime-p},
break
}
})
}
|
Write the same algorithm in Ruby as shown in this Java implementation. | import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.stream.IntStream;
public class WordLadder {
private static int distance(String s1, String s2) {
assert s1.length() == s2.length();
return (int) IntStream.range(0, s1.length())
.filter(i -> s1.charAt(i) != s2.charAt(i))
.count();
}
private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {
wordLadder(words, fw, tw, 8);
}
private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {
if (fw.length() != tw.length()) {
throw new IllegalArgumentException("From word and to word must have the same length");
}
Set<String> ws = words.get(fw.length());
if (ws.contains(fw)) {
List<String> primeList = new ArrayList<>();
primeList.add(fw);
PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {
int cmp1 = Integer.compare(chain1.size(), chain2.size());
if (cmp1 == 0) {
String last1 = chain1.get(chain1.size() - 1);
int d1 = distance(last1, tw);
String last2 = chain2.get(chain2.size() - 1);
int d2 = distance(last2, tw);
return Integer.compare(d1, d2);
}
return cmp1;
});
queue.add(primeList);
while (queue.size() > 0) {
List<String> curr = queue.remove();
if (curr.size() > limit) {
continue;
}
String last = curr.get(curr.size() - 1);
for (String word : ws) {
if (distance(last, word) == 1) {
if (word.equals(tw)) {
curr.add(word);
System.out.println(String.join(" -> ", curr));
return;
}
if (!curr.contains(word)) {
List<String> cp = new ArrayList<>(curr);
cp.add(word);
queue.add(cp);
}
}
}
}
}
System.err.printf("Cannot turn `%s` into `%s`%n", fw, tw);
}
public static void main(String[] args) throws IOException {
Map<Integer, Set<String>> words = new HashMap<>();
for (String line : Files.readAllLines(Path.of("unixdict.txt"))) {
Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);
wl.add(line);
}
wordLadder(words, "boy", "man");
wordLadder(words, "girl", "lady");
wordLadder(words, "john", "jane");
wordLadder(words, "child", "adult");
wordLadder(words, "cat", "dog");
wordLadder(words, "lead", "gold");
wordLadder(words, "white", "black");
wordLadder(words, "bubble", "tickle", 12);
}
}
| require "set"
Words = File.open("unixdict.txt").read.split("\n").
group_by { |w| w.length }.map { |k, v| [k, Set.new(v)] }.
to_h
def word_ladder(from, to)
raise "Length mismatch" unless from.length == to.length
sized_words = Words[from.length]
work_queue = [[from]]
used = Set.new [from]
while work_queue.length > 0
new_q = []
work_queue.each do |words|
last_word = words[-1]
new_tails = Enumerator.new do |enum|
("a".."z").each do |replacement_letter|
last_word.length.times do |i|
new_word = last_word.clone
new_word[i] = replacement_letter
next unless sized_words.include? new_word and
not used.include? new_word
enum.yield new_word
used.add new_word
return words + [new_word] if new_word == to
end
end
end
new_tails.each do |t|
new_q.push(words + [t])
end
end
work_queue = new_q
end
end
[%w<boy man>, %w<girl lady>, %w<john jane>, %w<child adult>].each do |from, to|
if ladder = word_ladder(from, to)
puts ladder.join " → "
else
puts "
end
end
|
Produce a language-to-language conversion: from Java to Ruby, same semantics. |
import java.util.Random;
public class GaussJordan {
public static void main(String[] args) {
int rows = 5;
Matrix m = new Matrix(rows, rows);
Random r = new Random();
for (int row = 0; row < rows; ++row) {
for (int column = 0; column < rows; ++column)
m.set(row, column, r.nextDouble());
}
System.out.println("Matrix:");
m.print();
System.out.println("Inverse:");
Matrix inv = m.inverse();
inv.print();
System.out.println("Product of matrix and inverse:");
Matrix.product(m, inv).print();
}
}
| require 'matrix'
m = Matrix[[-1, -2, 3, 2],
[-4, -1, 6, 2],
[ 7, -8, 9, 1],
[ 1, -2, 1, 3]]
pp m.inv.row_vectors
|
Change the following Java code into Ruby without altering its purpose. |
import java.util.Random;
public class GaussJordan {
public static void main(String[] args) {
int rows = 5;
Matrix m = new Matrix(rows, rows);
Random r = new Random();
for (int row = 0; row < rows; ++row) {
for (int column = 0; column < rows; ++column)
m.set(row, column, r.nextDouble());
}
System.out.println("Matrix:");
m.print();
System.out.println("Inverse:");
Matrix inv = m.inverse();
inv.print();
System.out.println("Product of matrix and inverse:");
Matrix.product(m, inv).print();
}
}
| require 'matrix'
m = Matrix[[-1, -2, 3, 2],
[-4, -1, 6, 2],
[ 7, -8, 9, 1],
[ 1, -2, 1, 3]]
pp m.inv.row_vectors
|
Translate the given Java code snippet into Ruby without altering its behavior. | import java.util.function.Function;
public class NumericalIntegrationAdaptiveSimpsons {
public static void main(String[] args) {
Function<Double,Double> f = x -> sin(x);
System.out.printf("integrate sin(x), x = 0 .. Pi = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);
functionCount = 0;
System.out.printf("integrate sin(x), x = 0 .. 1 = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);
}
private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {
double fa = function.apply(a);
double fb = function.apply(b);
Triple t = quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);
return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);
}
private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {
Triple left = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);
Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);
double delta = left.s + right.s - whole;
if ( Math.abs(delta) <= 15*error ) {
return left.s + right.s + delta / 15;
}
return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +
quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);
}
private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {
double m = (a + b) / 2;
double fm = function.apply(m);
return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));
}
private static class Triple {
double x, fx, s;
private Triple(double m, double fm, double s) {
this.x = m;
this.fx = fm;
this.s = s;
}
}
private static int functionCount = 0;
private static double sin(double x) {
functionCount++;
return Math.sin(x);
}
}
| func adaptive_Simpson_quadrature(f, left, right, ε = 1e-9) {
func quadrature_mid(l, lf, r, rf) {
var mid = (l+r)/2
var midf = f(mid)
(mid, midf, abs(r-l)/6 * (lf + 4*midf + rf))
}
func recursive_asr(a, fa, b, fb, ε, whole, m, fm) {
var (lm, flm, left) = quadrature_mid(a, fa, m, fm)
var (rm, frm, right) = quadrature_mid(m, fm, b, fb)
var Δ = (left + right - whole)
abs(Δ) <= 15*ε
? (left + right + Δ/15)
: (__FUNC__(a, fa, m, fm, ε/2, left, lm, flm) +
__FUNC__(m, fm, b, fb, ε/2, right, rm, frm))
}
var (lf = f(left), rf = f(right))
var (mid, midf, whole) = quadrature_mid(left, lf, right, rf)
recursive_asr(left, lf, right, rf, ε, whole, mid, midf)
}
var (a = 0, b = 1)
var area = adaptive_Simpson_quadrature({ .sin }, a, b, 1e-15).round(-15)
say "Simpson's integration of sine from
|
Convert this Java block to Ruby, preserving its control flow and logic. | import java.util.function.Function;
public class NumericalIntegrationAdaptiveSimpsons {
public static void main(String[] args) {
Function<Double,Double> f = x -> sin(x);
System.out.printf("integrate sin(x), x = 0 .. Pi = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount);
functionCount = 0;
System.out.printf("integrate sin(x), x = 0 .. 1 = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount);
}
private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) {
double fa = function.apply(a);
double fb = function.apply(b);
Triple t = quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb);
return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx);
}
private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) {
Triple left = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm);
Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb);
double delta = left.s + right.s - whole;
if ( Math.abs(delta) <= 15*error ) {
return left.s + right.s + delta / 15;
}
return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) +
quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx);
}
private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) {
double m = (a + b) / 2;
double fm = function.apply(m);
return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb));
}
private static class Triple {
double x, fx, s;
private Triple(double m, double fm, double s) {
this.x = m;
this.fx = fm;
this.s = s;
}
}
private static int functionCount = 0;
private static double sin(double x) {
functionCount++;
return Math.sin(x);
}
}
| func adaptive_Simpson_quadrature(f, left, right, ε = 1e-9) {
func quadrature_mid(l, lf, r, rf) {
var mid = (l+r)/2
var midf = f(mid)
(mid, midf, abs(r-l)/6 * (lf + 4*midf + rf))
}
func recursive_asr(a, fa, b, fb, ε, whole, m, fm) {
var (lm, flm, left) = quadrature_mid(a, fa, m, fm)
var (rm, frm, right) = quadrature_mid(m, fm, b, fb)
var Δ = (left + right - whole)
abs(Δ) <= 15*ε
? (left + right + Δ/15)
: (__FUNC__(a, fa, m, fm, ε/2, left, lm, flm) +
__FUNC__(m, fm, b, fb, ε/2, right, rm, frm))
}
var (lf = f(left), rf = f(right))
var (mid, midf, whole) = quadrature_mid(left, lf, right, rf)
recursive_asr(left, lf, right, rf, ε, whole, mid, midf)
}
var (a = 0, b = 1)
var area = adaptive_Simpson_quadrature({ .sin }, a, b, 1e-15).round(-15)
say "Simpson's integration of sine from
|
Write the same algorithm in Ruby as shown in this Java implementation. | public class ColorfulNumbers {
private int count[] = new int[8];
private boolean used[] = new boolean[10];
private int largest = 0;
public static void main(String[] args) {
System.out.printf("Colorful numbers less than 100:\n");
for (int n = 0, count = 0; n < 100; ++n) {
if (isColorful(n))
System.out.printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
ColorfulNumbers c = new ColorfulNumbers();
System.out.printf("\n\nLargest colorful number: %,d\n", c.largest);
System.out.printf("\nCount of colorful numbers by number of digits:\n");
int total = 0;
for (int d = 0; d < 8; ++d) {
System.out.printf("%d %,d\n", d + 1, c.count[d]);
total += c.count[d];
}
System.out.printf("\nTotal: %,d\n", total);
}
private ColorfulNumbers() {
countColorful(0, 0, 0);
}
public static boolean isColorful(int n) {
if (n < 0 || n > 98765432)
return false;
int digit_count[] = new int[10];
int digits[] = new int[8];
int num_digits = 0;
for (int m = n; m > 0; m /= 10) {
int d = m % 10;
if (n > 9 && (d == 0 || d == 1))
return false;
if (++digit_count[d] > 1)
return false;
digits[num_digits++] = d;
}
int products[] = new int[36];
for (int i = 0, product_count = 0; i < num_digits; ++i) {
for (int j = i, p = 1; j < num_digits; ++j) {
p *= digits[j];
for (int k = 0; k < product_count; ++k) {
if (products[k] == p)
return false;
}
products[product_count++] = p;
}
}
return true;
}
private void countColorful(int taken, int n, int digits) {
if (taken == 0) {
for (int d = 0; d < 10; ++d) {
used[d] = true;
countColorful(d < 2 ? 9 : 1, d, 1);
used[d] = false;
}
} else {
if (isColorful(n)) {
++count[digits - 1];
if (n > largest)
largest = n;
}
if (taken < 9) {
for (int d = 2; d < 10; ++d) {
if (!used[d]) {
used[d] = true;
countColorful(taken + 1, n * 10 + d, digits + 1);
used[d] = false;
}
}
}
}
}
}
| def colorful?(ar)
products = []
(1..ar.size).all? do |chunk_size|
ar.each_cons(chunk_size) do |chunk|
product = chunk.inject(&:*)
return false if products.include?(product)
products << product
end
end
end
below100 = (0..100).select{|n| colorful?(n.digits)}
puts "The colorful numbers less than 100 are:", below100.join(" "), ""
puts "Largest colorful number:
total = 0
(1..8).each do |numdigs|
digits = (numdigs == 1 ? (0..9).to_a : (2..9).to_a)
count = digits.permutation(numdigs).count{|perm| colorful?(perm)}
puts "
total += count
end
puts "\nTotal colorful numbers:
|
Write a version of this Java function in Ruby with identical behavior. | public class ColorfulNumbers {
private int count[] = new int[8];
private boolean used[] = new boolean[10];
private int largest = 0;
public static void main(String[] args) {
System.out.printf("Colorful numbers less than 100:\n");
for (int n = 0, count = 0; n < 100; ++n) {
if (isColorful(n))
System.out.printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
ColorfulNumbers c = new ColorfulNumbers();
System.out.printf("\n\nLargest colorful number: %,d\n", c.largest);
System.out.printf("\nCount of colorful numbers by number of digits:\n");
int total = 0;
for (int d = 0; d < 8; ++d) {
System.out.printf("%d %,d\n", d + 1, c.count[d]);
total += c.count[d];
}
System.out.printf("\nTotal: %,d\n", total);
}
private ColorfulNumbers() {
countColorful(0, 0, 0);
}
public static boolean isColorful(int n) {
if (n < 0 || n > 98765432)
return false;
int digit_count[] = new int[10];
int digits[] = new int[8];
int num_digits = 0;
for (int m = n; m > 0; m /= 10) {
int d = m % 10;
if (n > 9 && (d == 0 || d == 1))
return false;
if (++digit_count[d] > 1)
return false;
digits[num_digits++] = d;
}
int products[] = new int[36];
for (int i = 0, product_count = 0; i < num_digits; ++i) {
for (int j = i, p = 1; j < num_digits; ++j) {
p *= digits[j];
for (int k = 0; k < product_count; ++k) {
if (products[k] == p)
return false;
}
products[product_count++] = p;
}
}
return true;
}
private void countColorful(int taken, int n, int digits) {
if (taken == 0) {
for (int d = 0; d < 10; ++d) {
used[d] = true;
countColorful(d < 2 ? 9 : 1, d, 1);
used[d] = false;
}
} else {
if (isColorful(n)) {
++count[digits - 1];
if (n > largest)
largest = n;
}
if (taken < 9) {
for (int d = 2; d < 10; ++d) {
if (!used[d]) {
used[d] = true;
countColorful(taken + 1, n * 10 + d, digits + 1);
used[d] = false;
}
}
}
}
}
}
| def colorful?(ar)
products = []
(1..ar.size).all? do |chunk_size|
ar.each_cons(chunk_size) do |chunk|
product = chunk.inject(&:*)
return false if products.include?(product)
products << product
end
end
end
below100 = (0..100).select{|n| colorful?(n.digits)}
puts "The colorful numbers less than 100 are:", below100.join(" "), ""
puts "Largest colorful number:
total = 0
(1..8).each do |numdigs|
digits = (numdigs == 1 ? (0..9).to_a : (2..9).to_a)
count = digits.permutation(numdigs).count{|perm| colorful?(perm)}
puts "
total += count
end
puts "\nTotal colorful numbers:
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | import static java.lang.Math.abs;
import java.util.Random;
public class Fen {
static Random rand = new Random();
public static void main(String[] args) {
System.out.println(createFen());
}
static String createFen() {
char[][] grid = new char[8][8];
placeKings(grid);
placePieces(grid, "PPPPPPPP", true);
placePieces(grid, "pppppppp", true);
placePieces(grid, "RNBQBNR", false);
placePieces(grid, "rnbqbnr", false);
return toFen(grid);
}
static void placeKings(char[][] grid) {
int r1, c1, r2, c2;
while (true) {
r1 = rand.nextInt(8);
c1 = rand.nextInt(8);
r2 = rand.nextInt(8);
c2 = rand.nextInt(8);
if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1)
break;
}
grid[r1][c1] = 'K';
grid[r2][c2] = 'k';
}
static void placePieces(char[][] grid, String pieces, boolean isPawn) {
int numToPlace = rand.nextInt(pieces.length());
for (int n = 0; n < numToPlace; n++) {
int r, c;
do {
r = rand.nextInt(8);
c = rand.nextInt(8);
} while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));
grid[r][c] = pieces.charAt(n);
}
}
static String toFen(char[][] grid) {
StringBuilder fen = new StringBuilder();
int countEmpty = 0;
for (int r = 0; r < 8; r++) {
for (int c = 0; c < 8; c++) {
char ch = grid[r][c];
System.out.printf("%2c ", ch == 0 ? '.' : ch);
if (ch == 0) {
countEmpty++;
} else {
if (countEmpty > 0) {
fen.append(countEmpty);
countEmpty = 0;
}
fen.append(ch);
}
}
if (countEmpty > 0) {
fen.append(countEmpty);
countEmpty = 0;
}
fen.append("/");
System.out.println();
}
return fen.append(" w - - 0 1").toString();
}
}
| def hasNK(board, a, b)
(-1..1).each do |g|
(-1..1).each do |f|
aa = a + f; bb = b + g
if (0..7).includes?(aa) && (0..7).includes?(bb)
p = board[aa + 8 * bb]
return true if p == "K" || p == "k"
end
end
end
return false
end
def generateBoard(board, pieces)
pieces.each_char do |p|
while true
a = rand(8); b = rand(8)
next if ( (b == 0 || b == 7) && (p == "P" || p == "p") ) ||
( (p == "k" || p == "K") && hasNK(board, a, b) )
break if board[a + b * 8] == '.'
end
board[a + b * 8] = p
end
end
pieces = "ppppppppkqrrbbnnPPPPPPPPKQRRBBNN"
11.times do
e = pieces.size - 1
while e > 0
p = rand(e); t = pieces[e]
pieces = pieces.sub(e, pieces[p])
pieces = pieces.sub(p, t); e -= 1
end
end
board = Array.new(64, '.'); generateBoard(board, pieces)
puts
e = 0
8.times do |j| row_j = j * 8
8.times do |i|
board[row_j + i ] == '.' ? (e += 1) :
( (print(e); e = 0) if e > 0
print board[row_j + i] )
end
(print(e); e = 0) if e > 0
print("/") if j < 7
end
print(" w - - 0 1\n")
8.times do |j| row_j = j * 8
8.times { |i| board[row_j + i] == '.' ? print(".") : print(board[row_j + i]) }
puts
end
8.times{ |row| puts board[row*8..row*8 + 7].join("") }
|
Produce a functionally identical Ruby code for the snippet given in Java. | import java.io.*;
public class SierpinskiSquareCurve {
public static void main(final String[] args) {
try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_square.svg"))) {
SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);
int size = 635, length = 5;
s.currentAngle = 0;
s.currentX = (size - length)/2;
s.currentY = length;
s.lineLength = length;
s.begin(size);
s.execute(rewrite(5));
s.end();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private SierpinskiSquareCurve(final Writer writer) {
this.writer = writer;
}
private void begin(final int size) throws IOException {
write("<svg xmlns='http:
write("<rect width='100%%' height='100%%' fill='white'/>\n");
write("<path stroke-width='1' stroke='black' fill='none' d='");
}
private void end() throws IOException {
write("'/>\n</svg>\n");
}
private void execute(final String s) throws IOException {
write("M%g,%g\n", currentX, currentY);
for (int i = 0, n = s.length(); i < n; ++i) {
switch (s.charAt(i)) {
case 'F':
line(lineLength);
break;
case '+':
turn(ANGLE);
break;
case '-':
turn(-ANGLE);
break;
}
}
}
private void line(final double length) throws IOException {
final double theta = (Math.PI * currentAngle) / 180.0;
currentX += length * Math.cos(theta);
currentY += length * Math.sin(theta);
write("L%g,%g\n", currentX, currentY);
}
private void turn(final int angle) {
currentAngle = (currentAngle + angle) % 360;
}
private void write(final String format, final Object... args) throws IOException {
writer.write(String.format(format, args));
}
private static String rewrite(final int order) {
String s = AXIOM;
for (int i = 0; i < order; ++i) {
final StringBuilder sb = new StringBuilder();
for (int j = 0, n = s.length(); j < n; ++j) {
final char ch = s.charAt(j);
if (ch == 'X')
sb.append(PRODUCTION);
else
sb.append(ch);
}
s = sb.toString();
}
return s;
}
private final Writer writer;
private double lineLength;
private double currentX;
private double currentY;
private int currentAngle;
private static final String AXIOM = "F+XF+F+XF";
private static final String PRODUCTION = "XF-F+F-XF+F+XF-F+F-X";
private static final int ANGLE = 90;
}
| var rules = Hash(
x => 'xF-F+F-xF+F+xF-F+F-x',
)
var lsys = LSystem(
width: 510,
height: 510,
xoff: -505,
yoff: -254,
len: 4,
angle: 90,
color: 'dark green',
)
lsys.execute('F+xF+F+xF', 5, "sierpiński_square_curve.png", rules)
|
Convert this Java block to Ruby, preserving its control flow and logic. | public class RhondaNumbers {
public static void main(String[] args) {
final int limit = 15;
for (int base = 2; base <= 36; ++base) {
if (isPrime(base))
continue;
System.out.printf("First %d Rhonda numbers to base %d:\n", limit, base);
int numbers[] = new int[limit];
for (int n = 1, count = 0; count < limit; ++n) {
if (isRhonda(base, n))
numbers[count++] = n;
}
System.out.printf("In base 10:");
for (int i = 0; i < limit; ++i)
System.out.printf(" %d", numbers[i]);
System.out.printf("\nIn base %d:", base);
for (int i = 0; i < limit; ++i)
System.out.printf(" %s", Integer.toString(numbers[i], base));
System.out.printf("\n\n");
}
}
private static int digitProduct(int base, int n) {
int product = 1;
for (; n != 0; n /= base)
product *= n % base;
return product;
}
private static int primeFactorSum(int n) {
int sum = 0;
for (; (n & 1) == 0; n >>= 1)
sum += 2;
for (int p = 3; p * p <= n; p += 2)
for (; n % p == 0; n /= p)
sum += p;
if (n > 1)
sum += n;
return sum;
}
private static boolean isPrime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
private static boolean isRhonda(int base, int n) {
return digitProduct(base, n) == base * primeFactorSum(n);
}
}
| func is_rhonda_number(n, base = 10) {
base.is_composite || return false
n > 0 || return false
n.digits(base).prod == base*n.factor.sum
}
for b in (2..16 -> grep { .is_composite }) {
say ("First 10 Rhonda numbers to base
10.by { is_rhonda_number(_, b) })
}
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class PisanoPeriod {
public static void main(String[] args) {
System.out.printf("Print pisano(p^2) for every prime p lower than 15%n");
for ( long i = 2 ; i < 15 ; i++ ) {
if ( isPrime(i) ) {
long n = i*i;
System.out.printf("pisano(%d) = %d%n", n, pisano(n));
}
}
System.out.printf("%nPrint pisano(p) for every prime p lower than 180%n");
for ( long n = 2 ; n < 180 ; n++ ) {
if ( isPrime(n) ) {
System.out.printf("pisano(%d) = %d%n", n, pisano(n));
}
}
System.out.printf("%nPrint pisano(n) for every integer from 1 to 180%n");
for ( long n = 1 ; n <= 180 ; n++ ) {
System.out.printf("%3d ", pisano(n));
if ( n % 10 == 0 ) {
System.out.printf("%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 Map<Long,Long> PERIOD_MEMO = new HashMap<>();
static {
PERIOD_MEMO.put(2L, 3L);
PERIOD_MEMO.put(3L, 8L);
PERIOD_MEMO.put(5L, 20L);
}
private static long pisano(long n) {
if ( PERIOD_MEMO.containsKey(n) ) {
return PERIOD_MEMO.get(n);
}
if ( n == 1 ) {
return 1;
}
Map<Long,Long> factors = getFactors(n);
if ( factors.size() == 1 & factors.get(2L) != null && factors.get(2L) > 0 ) {
long result = 3 * n / 2;
PERIOD_MEMO.put(n, result);
return result;
}
if ( factors.size() == 1 & factors.get(5L) != null && factors.get(5L) > 0 ) {
long result = 4*n;
PERIOD_MEMO.put(n, result);
return result;
}
if ( factors.size() == 2 & factors.get(2L) != null && factors.get(2L) == 1 && factors.get(5L) != null && factors.get(5L) > 0 ) {
long result = 6*n;
PERIOD_MEMO.put(n, result);
return result;
}
List<Long> primes = new ArrayList<>(factors.keySet());
long prime = primes.get(0);
if ( factors.size() == 1 && factors.get(prime) == 1 ) {
List<Long> divisors = new ArrayList<>();
if ( n % 10 == 1 || n % 10 == 9 ) {
for ( long divisor : getDivisors(prime-1) ) {
if ( divisor % 2 == 0 ) {
divisors.add(divisor);
}
}
}
else {
List<Long> pPlus1Divisors = getDivisors(prime+1);
for ( long divisor : getDivisors(2*prime+2) ) {
if ( ! pPlus1Divisors.contains(divisor) ) {
divisors.add(divisor);
}
}
}
Collections.sort(divisors);
for ( long divisor : divisors ) {
if ( fibModIdentity(divisor, prime) ) {
PERIOD_MEMO.put(prime, divisor);
return divisor;
}
}
throw new RuntimeException("ERROR 144: Divisor not found.");
}
long period = (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime);
for ( int i = 1 ; i < primes.size() ; i++ ) {
prime = primes.get(i);
period = lcm(period, (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime));
}
PERIOD_MEMO.put(n, period);
return period;
}
private static boolean fibModIdentity(long n, long mod) {
long aRes = 0;
long bRes = 1;
long cRes = 1;
long aBase = 0;
long bBase = 1;
long cBase = 1;
while ( n > 0 ) {
if ( n % 2 == 1 ) {
long temp1 = 0, temp2 = 0, temp3 = 0;
if ( aRes > SQRT || aBase > SQRT || bRes > SQRT || bBase > SQRT || cBase > SQRT || cRes > SQRT ) {
temp1 = (multiply(aRes, aBase, mod) + multiply(bRes, bBase, mod)) % mod;
temp2 = (multiply(aBase, bRes, mod) + multiply(bBase, cRes, mod)) % mod;
temp3 = (multiply(bBase, bRes, mod) + multiply(cBase, cRes, mod)) % mod;
}
else {
temp1 = ((aRes*aBase % mod) + (bRes*bBase % mod)) % mod;
temp2 = ((aBase*bRes % mod) + (bBase*cRes % mod)) % mod;
temp3 = ((bBase*bRes % mod) + (cBase*cRes % mod)) % mod;
}
aRes = temp1;
bRes = temp2;
cRes = temp3;
}
n >>= 1L;
long temp1 = 0, temp2 = 0, temp3 = 0;
if ( aBase > SQRT || bBase > SQRT || cBase > SQRT ) {
temp1 = (multiply(aBase, aBase, mod) + multiply(bBase, bBase, mod)) % mod;
temp2 = (multiply(aBase, bBase, mod) + multiply(bBase, cBase, mod)) % mod;
temp3 = (multiply(bBase, bBase, mod) + multiply(cBase, cBase, mod)) % mod;
}
else {
temp1 = ((aBase*aBase % mod) + (bBase*bBase % mod)) % mod;
temp2 = ((aBase*bBase % mod) + (bBase*cBase % mod)) % mod;
temp3 = ((bBase*bBase % mod) + (cBase*cBase % mod)) % mod;
}
aBase = temp1;
bBase = temp2;
cBase = temp3;
}
return aRes % mod == 0 && bRes % mod == 1 && cRes % mod == 1;
}
private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);
public static final long multiply(long a, long b, long modulus) {
long x = 0;
long y = a % modulus;
long t;
while ( b > 0 ) {
if ( b % 2 == 1 ) {
t = x + y;
x = (t > modulus ? t-modulus : t);
}
t = y << 1;
y = (t > modulus ? t-modulus : t);
b >>= 1;
}
return x % modulus;
}
private static final List<Long> getDivisors(long number) {
List<Long> divisors = new ArrayList<>();
long sqrt = (long) Math.sqrt(number);
for ( long i = 1 ; i <= sqrt ; i++ ) {
if ( number % i == 0 ) {
divisors.add(i);
long div = number / i;
if ( div != i ) {
divisors.add(div);
}
}
}
return divisors;
}
public static long lcm(long a, long b) {
return a*b/gcd(a,b);
}
public static long gcd(long a, long b) {
if ( b == 0 ) {
return a;
}
return gcd(b, a%b);
}
private static final Map<Long,Map<Long,Long>> allFactors = new TreeMap<Long,Map<Long,Long>>();
static {
Map<Long,Long> factors = new TreeMap<Long,Long>();
factors.put(2L, 1L);
allFactors.put(2L, factors);
}
public static Long MAX_ALL_FACTORS = 100000L;
public static final Map<Long,Long> getFactors(Long number) {
if ( allFactors.containsKey(number) ) {
return allFactors.get(number);
}
Map<Long,Long> factors = new TreeMap<Long,Long>();
if ( number % 2 == 0 ) {
Map<Long,Long> factorsdDivTwo = getFactors(number/2);
factors.putAll(factorsdDivTwo);
factors.merge(2L, 1L, (v1, v2) -> v1 + v2);
if ( number < MAX_ALL_FACTORS ) {
allFactors.put(number, factors);
}
return factors;
}
boolean prime = true;
long sqrt = (long) Math.sqrt(number);
for ( long i = 3 ; i <= sqrt ; i += 2 ) {
if ( number % i == 0 ) {
prime = false;
factors.putAll(getFactors(number/i));
factors.merge(i, 1L, (v1, v2) -> v1 + v2);
if ( number < MAX_ALL_FACTORS ) {
allFactors.put(number, factors);
}
return factors;
}
}
if ( prime ) {
factors.put(number, 1L);
if ( number < MAX_ALL_FACTORS ) {
allFactors.put(number, factors);
}
}
return factors;
}
}
| func pisano_period_pp(p,k) is cached {
assert(k.is_pos, "k =
assert(p.is_prime, "p =
var (a, b, n) = (0, 1, p**k)
1..Inf -> first_by {
(a, b) = (b, (a+b) % n)
(a == 0) && (b == 1)
}
}
func pisano_period(n) {
n.factor_map {|p,k| pisano_period_pp(p, k) }.lcm
}
say "Pisano periods for squares of primes p <= 15:"
say 15.primes.map {|p| pisano_period_pp(p, 2) }
say "\nPisano periods for primes p <= 180:"
say 180.primes.map {|p| pisano_period_pp(p, 1) }
say "\nPisano periods for integers n from 1 to 180:"
say pisano_period.map(1..180)
|
Produce a language-to-language conversion: from Java to Ruby, same semantics. | import org.apache.commons.math3.distribution.TDistribution;
public class WelchTTest {
public static double[] meanvar(double[] a) {
double m = 0.0, v = 0.0;
int n = a.length;
for (double x: a) {
m += x;
}
m /= n;
for (double x: a) {
v += (x - m) * (x - m);
}
v /= (n - 1);
return new double[] {m, v};
}
public static double[] welch_ttest(double[] x, double[] y) {
double mx, my, vx, vy, t, df, p;
double[] res;
int nx = x.length, ny = y.length;
res = meanvar(x);
mx = res[0];
vx = res[1];
res = meanvar(y);
my = res[0];
vy = res[1];
t = (mx-my)/Math.sqrt(vx/nx+vy/ny);
df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));
TDistribution dist = new TDistribution(df);
p = 2.0*dist.cumulativeProbability(-Math.abs(t));
return new double[] {t, df, p};
}
public static void main(String[] args) {
double x[] = {3.0, 4.0, 1.0, 2.1};
double y[] = {490.2, 340.0, 433.9};
double res[] = welch_ttest(x, y);
System.out.println("t = " + res[0]);
System.out.println("df = " + res[1]);
System.out.println("p = " + res[2]);
}
}
| def calculate_p_value(array1, array2)
return 1.0 if array1.size <= 1
return 1.0 if array2.size <= 1
mean1 = array1.sum / array1.size
mean2 = array2.sum / array2.size
return 1.0 if mean1 == mean2
variance1 = 0.0
variance2 = 0.0
array1.each do |x|
variance1 += (mean1 - x)**2
end
array2.each do |x|
variance2 += (mean2 - x)**2
end
return 1.0 if variance1 == 0.0 && variance2 == 0.0
variance1 /= (array1.size - 1)
variance2 /= (array2.size - 1)
welch_t_statistic = (mean1 - mean2) / Math.sqrt(variance1 / array1.size + variance2 / array2.size)
degrees_of_freedom = ((variance1 / array1.size + variance2 / array2.size)**2) / (
(variance1 * variance1) / (array1.size * array1.size * (array1.size - 1)) +
(variance2 * variance2) / (array2.size * array2.size * (array2.size - 1)))
a = degrees_of_freedom / 2
value = degrees_of_freedom / (welch_t_statistic**2 + degrees_of_freedom)
beta = Math.lgamma(a)[0] + 0.57236494292470009 - Math.lgamma(a + 0.5)[0]
acu = 10**-15
return value if a <= 0
return value if value < 0.0 || value > 1.0
return value if (value == 0) || (value == 1.0)
psq = a + 0.5
cx = 1.0 - value
if a < psq * value
xx = cx
cx = value
pp = 0.5
qq = a
indx = 1
else
xx = value
pp = a
qq = 0.5
indx = 0
end
term = 1.0
ai = 1.0
value = 1.0
ns = (qq + cx * psq).to_i
rx = xx / cx
temp = qq - ai
loop do
term = term * temp * rx / (pp + ai)
value += term
temp = term.abs
if temp <= acu && temp <= acu * value
value = value * Math.exp(pp * Math.log(xx) + (qq - 1.0) * Math.log(cx) - beta) / pp
value = 1.0 - value
value = 1.0 - value if indx == 0
break
end
ai += 1.0
ns -= 1
if ns >= 0
temp = qq - ai
rx = xx if ns == 0
else
temp = psq
psq += 1.0
end
end
value
end
d1 = [27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6, 23.1, 19.6, 19.0, 21.7, 21.4]
d2 = [27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2, 21.9, 22.1, 22.9, 20.5, 24.4]
d3 = [17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8]
d4 = [21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8, 20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8]
d5 = [19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0]
d6 = [28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7, 23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2]
d7 = [30.02, 29.99, 30.11, 29.97, 30.01, 29.99]
d8 = [29.89, 29.93, 29.72, 29.98, 30.02, 29.98]
x = [3.0, 4.0, 1.0, 2.1]
y = [490.2, 340.0, 433.9]
s1 = [1.0 / 15, 10.0 / 62.0]
s2 = [1.0 / 10, 2 / 50.0]
v1 = [0.010268, 0.000167, 0.000167]
v2 = [0.159258, 0.136278, 0.122389]
z1 = [9 / 23.0, 21 / 45.0, 0 / 38.0]
z2 = [0 / 44.0, 42 / 94.0, 0 / 22.0]
CORRECT_ANSWERS = [0.021378001462867, 0.148841696605327, 0.0359722710297968,
0.090773324285671, 0.0107515611497845, 0.00339907162713746, 0.52726574965384, 0.545266866977794].freeze
pvalue = calculate_p_value(d1, d2)
error = (pvalue - CORRECT_ANSWERS[0]).abs
printf("Test sets 1 p-value = %.14g\n", pvalue)
pvalue = calculate_p_value(d3, d4)
error += (pvalue - CORRECT_ANSWERS[1]).abs
printf("Test sets 2 p-value = %.14g\n", pvalue)
pvalue = calculate_p_value(d5, d6)
error += (pvalue - CORRECT_ANSWERS[2]).abs
printf("Test sets 3 p-value = %.14g\n", pvalue)
pvalue = calculate_p_value(d7, d8)
error += (pvalue - CORRECT_ANSWERS[3]).abs
printf("Test sets 4 p-value = %.14g\n", pvalue)
pvalue = calculate_p_value(x, y)
error += (pvalue - CORRECT_ANSWERS[4]).abs
printf("Test sets 5 p-value = %.14g\n", pvalue)
pvalue = calculate_p_value(v1, v2)
error += (pvalue - CORRECT_ANSWERS[5]).abs
printf("Test sets 6 p-value = %.14g\n", pvalue)
pvalue = calculate_p_value(s1, s2)
error += (pvalue - CORRECT_ANSWERS[6]).abs
printf("Test sets 7 p-value = %.14g\n", pvalue)
pvalue = calculate_p_value(z1, z2)
error += (pvalue - CORRECT_ANSWERS[7]).abs
printf("Test sets z p-value = %.14g\n", pvalue)
printf("the cumulative error is %g\n", error)
|
Translate the given Java code snippet into Ruby without altering its behavior. | import org.apache.commons.math3.distribution.TDistribution;
public class WelchTTest {
public static double[] meanvar(double[] a) {
double m = 0.0, v = 0.0;
int n = a.length;
for (double x: a) {
m += x;
}
m /= n;
for (double x: a) {
v += (x - m) * (x - m);
}
v /= (n - 1);
return new double[] {m, v};
}
public static double[] welch_ttest(double[] x, double[] y) {
double mx, my, vx, vy, t, df, p;
double[] res;
int nx = x.length, ny = y.length;
res = meanvar(x);
mx = res[0];
vx = res[1];
res = meanvar(y);
my = res[0];
vy = res[1];
t = (mx-my)/Math.sqrt(vx/nx+vy/ny);
df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));
TDistribution dist = new TDistribution(df);
p = 2.0*dist.cumulativeProbability(-Math.abs(t));
return new double[] {t, df, p};
}
public static void main(String[] args) {
double x[] = {3.0, 4.0, 1.0, 2.1};
double y[] = {490.2, 340.0, 433.9};
double res[] = welch_ttest(x, y);
System.out.println("t = " + res[0]);
System.out.println("df = " + res[1]);
System.out.println("p = " + res[2]);
}
}
| def calculate_p_value(array1, array2)
return 1.0 if array1.size <= 1
return 1.0 if array2.size <= 1
mean1 = array1.sum / array1.size
mean2 = array2.sum / array2.size
return 1.0 if mean1 == mean2
variance1 = 0.0
variance2 = 0.0
array1.each do |x|
variance1 += (mean1 - x)**2
end
array2.each do |x|
variance2 += (mean2 - x)**2
end
return 1.0 if variance1 == 0.0 && variance2 == 0.0
variance1 /= (array1.size - 1)
variance2 /= (array2.size - 1)
welch_t_statistic = (mean1 - mean2) / Math.sqrt(variance1 / array1.size + variance2 / array2.size)
degrees_of_freedom = ((variance1 / array1.size + variance2 / array2.size)**2) / (
(variance1 * variance1) / (array1.size * array1.size * (array1.size - 1)) +
(variance2 * variance2) / (array2.size * array2.size * (array2.size - 1)))
a = degrees_of_freedom / 2
value = degrees_of_freedom / (welch_t_statistic**2 + degrees_of_freedom)
beta = Math.lgamma(a)[0] + 0.57236494292470009 - Math.lgamma(a + 0.5)[0]
acu = 10**-15
return value if a <= 0
return value if value < 0.0 || value > 1.0
return value if (value == 0) || (value == 1.0)
psq = a + 0.5
cx = 1.0 - value
if a < psq * value
xx = cx
cx = value
pp = 0.5
qq = a
indx = 1
else
xx = value
pp = a
qq = 0.5
indx = 0
end
term = 1.0
ai = 1.0
value = 1.0
ns = (qq + cx * psq).to_i
rx = xx / cx
temp = qq - ai
loop do
term = term * temp * rx / (pp + ai)
value += term
temp = term.abs
if temp <= acu && temp <= acu * value
value = value * Math.exp(pp * Math.log(xx) + (qq - 1.0) * Math.log(cx) - beta) / pp
value = 1.0 - value
value = 1.0 - value if indx == 0
break
end
ai += 1.0
ns -= 1
if ns >= 0
temp = qq - ai
rx = xx if ns == 0
else
temp = psq
psq += 1.0
end
end
value
end
d1 = [27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6, 23.1, 19.6, 19.0, 21.7, 21.4]
d2 = [27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2, 21.9, 22.1, 22.9, 20.5, 24.4]
d3 = [17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8]
d4 = [21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8, 20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8]
d5 = [19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0]
d6 = [28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7, 23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2]
d7 = [30.02, 29.99, 30.11, 29.97, 30.01, 29.99]
d8 = [29.89, 29.93, 29.72, 29.98, 30.02, 29.98]
x = [3.0, 4.0, 1.0, 2.1]
y = [490.2, 340.0, 433.9]
s1 = [1.0 / 15, 10.0 / 62.0]
s2 = [1.0 / 10, 2 / 50.0]
v1 = [0.010268, 0.000167, 0.000167]
v2 = [0.159258, 0.136278, 0.122389]
z1 = [9 / 23.0, 21 / 45.0, 0 / 38.0]
z2 = [0 / 44.0, 42 / 94.0, 0 / 22.0]
CORRECT_ANSWERS = [0.021378001462867, 0.148841696605327, 0.0359722710297968,
0.090773324285671, 0.0107515611497845, 0.00339907162713746, 0.52726574965384, 0.545266866977794].freeze
pvalue = calculate_p_value(d1, d2)
error = (pvalue - CORRECT_ANSWERS[0]).abs
printf("Test sets 1 p-value = %.14g\n", pvalue)
pvalue = calculate_p_value(d3, d4)
error += (pvalue - CORRECT_ANSWERS[1]).abs
printf("Test sets 2 p-value = %.14g\n", pvalue)
pvalue = calculate_p_value(d5, d6)
error += (pvalue - CORRECT_ANSWERS[2]).abs
printf("Test sets 3 p-value = %.14g\n", pvalue)
pvalue = calculate_p_value(d7, d8)
error += (pvalue - CORRECT_ANSWERS[3]).abs
printf("Test sets 4 p-value = %.14g\n", pvalue)
pvalue = calculate_p_value(x, y)
error += (pvalue - CORRECT_ANSWERS[4]).abs
printf("Test sets 5 p-value = %.14g\n", pvalue)
pvalue = calculate_p_value(v1, v2)
error += (pvalue - CORRECT_ANSWERS[5]).abs
printf("Test sets 6 p-value = %.14g\n", pvalue)
pvalue = calculate_p_value(s1, s2)
error += (pvalue - CORRECT_ANSWERS[6]).abs
printf("Test sets 7 p-value = %.14g\n", pvalue)
pvalue = calculate_p_value(z1, z2)
error += (pvalue - CORRECT_ANSWERS[7]).abs
printf("Test sets z p-value = %.14g\n", pvalue)
printf("the cumulative error is %g\n", error)
|
Keep all operations the same but rewrite the snippet in Ruby. | import java.math.BigInteger;
import java.util.Arrays;
public class FibonacciMatrixExponentiation {
public static void main(String[] args) {
BigInteger mod = BigInteger.TEN.pow(20);
for ( int exp : Arrays.asList(32, 64) ) {
System.out.printf("Last 20 digits of fib(2^%d) = %s%n", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));
}
for ( int i = 1 ; i <= 7 ; i++ ) {
BigInteger n = BigInteger.TEN.pow(i);
System.out.printf("fib(%,d) = %s%n", n, displayFib(fib(n)));
}
}
private static String displayFib(BigInteger fib) {
String s = fib.toString();
if ( s.length() <= 40 ) {
return s;
}
return s.substring(0, 20) + " ... " + s.subSequence(s.length()-20, s.length());
}
private static BigInteger fib(BigInteger k) {
BigInteger aRes = BigInteger.ZERO;
BigInteger bRes = BigInteger.ONE;
BigInteger cRes = BigInteger.ONE;
BigInteger aBase = BigInteger.ZERO;
BigInteger bBase = BigInteger.ONE;
BigInteger cBase = BigInteger.ONE;
while ( k.compareTo(BigInteger.ZERO) > 0 ) {
if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {
BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));
BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));
BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));
aRes = temp1;
bRes = temp2;
cRes = temp3;
}
k = k.shiftRight(1);
BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));
BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));
BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));
aBase = temp1;
bBase = temp2;
cBase = temp3;
}
return aRes;
}
private static BigInteger fibMod(BigInteger k, BigInteger mod) {
BigInteger aRes = BigInteger.ZERO;
BigInteger bRes = BigInteger.ONE;
BigInteger cRes = BigInteger.ONE;
BigInteger aBase = BigInteger.ZERO;
BigInteger bBase = BigInteger.ONE;
BigInteger cBase = BigInteger.ONE;
while ( k.compareTo(BigInteger.ZERO) > 0 ) {
if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {
BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);
BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);
BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);
aRes = temp1;
bRes = temp2;
cRes = temp3;
}
k = k.shiftRight(1);
BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);
BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);
BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);
aBase = temp1;
bBase = temp2;
cBase = temp3;
}
return aRes.mod(mod);
}
}
| func fibonacci(n) {
([[1,1],[1,0]]**n)[0][1]
}
say 15.of(fibonacci)
|
Generate an equivalent Ruby version of this Java code. | import java.math.BigInteger;
import java.util.Arrays;
public class FibonacciMatrixExponentiation {
public static void main(String[] args) {
BigInteger mod = BigInteger.TEN.pow(20);
for ( int exp : Arrays.asList(32, 64) ) {
System.out.printf("Last 20 digits of fib(2^%d) = %s%n", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));
}
for ( int i = 1 ; i <= 7 ; i++ ) {
BigInteger n = BigInteger.TEN.pow(i);
System.out.printf("fib(%,d) = %s%n", n, displayFib(fib(n)));
}
}
private static String displayFib(BigInteger fib) {
String s = fib.toString();
if ( s.length() <= 40 ) {
return s;
}
return s.substring(0, 20) + " ... " + s.subSequence(s.length()-20, s.length());
}
private static BigInteger fib(BigInteger k) {
BigInteger aRes = BigInteger.ZERO;
BigInteger bRes = BigInteger.ONE;
BigInteger cRes = BigInteger.ONE;
BigInteger aBase = BigInteger.ZERO;
BigInteger bBase = BigInteger.ONE;
BigInteger cBase = BigInteger.ONE;
while ( k.compareTo(BigInteger.ZERO) > 0 ) {
if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {
BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));
BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));
BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));
aRes = temp1;
bRes = temp2;
cRes = temp3;
}
k = k.shiftRight(1);
BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));
BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));
BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));
aBase = temp1;
bBase = temp2;
cBase = temp3;
}
return aRes;
}
private static BigInteger fibMod(BigInteger k, BigInteger mod) {
BigInteger aRes = BigInteger.ZERO;
BigInteger bRes = BigInteger.ONE;
BigInteger cRes = BigInteger.ONE;
BigInteger aBase = BigInteger.ZERO;
BigInteger bBase = BigInteger.ONE;
BigInteger cBase = BigInteger.ONE;
while ( k.compareTo(BigInteger.ZERO) > 0 ) {
if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {
BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);
BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);
BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);
aRes = temp1;
bRes = temp2;
cRes = temp3;
}
k = k.shiftRight(1);
BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);
BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);
BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);
aBase = temp1;
bBase = temp2;
cBase = temp3;
}
return aRes.mod(mod);
}
}
| func fibonacci(n) {
([[1,1],[1,0]]**n)[0][1]
}
say 15.of(fibonacci)
|
Generate a Ruby translation of this Java snippet without changing its computational steps. | import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Arrays;
import java.util.List;
public class RamanujanConstant {
public static void main(String[] args) {
System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100));
System.out.printf("Heegner numbers yielding 'almost' integers:%n");
List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);
List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);
for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {
int heegnerNumber = heegnerNumbers.get(i);
int heegnerVal = heegnerVals.get(i);
BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));
BigDecimal compute = ramanujanConstant(heegnerNumber, 50);
System.out.printf("%3d : %50s ~ %18s (diff ~ %s)%n", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());
}
}
public static BigDecimal ramanujanConstant(int sqrt, int digits) {
MathContext mc = new MathContext(digits + 5);
return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));
}
public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {
BigDecimal e = BigDecimal.ONE;
BigDecimal ak = e;
int k = 0;
BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));
while ( true ) {
k++;
ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);
e = e.add(ak, mc);
if ( ak.compareTo(min) < 0 ) {
break;
}
}
return e;
}
public static BigDecimal bigPi(MathContext mc) {
int k = 0;
BigDecimal ak = BigDecimal.ONE;
BigDecimal a = ak;
BigDecimal b = BigDecimal.ZERO;
BigDecimal c = BigDecimal.valueOf(640320);
BigDecimal c3 = c.pow(3);
double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);
double digits = 0;
while ( digits < mc.getPrecision() ) {
k++;
digits += digitePerTerm;
BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));
BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);
ak = ak.multiply(term, mc);
a = a.add(ak, mc);
b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);
}
BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);
return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);
}
public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {
double sqrt = Math.sqrt(squareDecimal.doubleValue());
BigDecimal x0 = new BigDecimal(sqrt, mc);
BigDecimal two = BigDecimal.valueOf(2);
while ( true ) {
BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);
String x1String = x1.toPlainString();
String x0String = x0.toPlainString();
if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {
break;
}
x0 = x1;
}
return x0;
}
}
| require "bigdecimal/math"
include BigMath
e, pi = E(200), PI(200)
[19, 43, 67, 163].each do |x|
puts "
end
|
Convert this Java snippet to Ruby and keep its semantics consistent. | import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Arrays;
import java.util.List;
public class RamanujanConstant {
public static void main(String[] args) {
System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100));
System.out.printf("Heegner numbers yielding 'almost' integers:%n");
List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);
List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);
for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {
int heegnerNumber = heegnerNumbers.get(i);
int heegnerVal = heegnerVals.get(i);
BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));
BigDecimal compute = ramanujanConstant(heegnerNumber, 50);
System.out.printf("%3d : %50s ~ %18s (diff ~ %s)%n", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());
}
}
public static BigDecimal ramanujanConstant(int sqrt, int digits) {
MathContext mc = new MathContext(digits + 5);
return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));
}
public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {
BigDecimal e = BigDecimal.ONE;
BigDecimal ak = e;
int k = 0;
BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));
while ( true ) {
k++;
ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);
e = e.add(ak, mc);
if ( ak.compareTo(min) < 0 ) {
break;
}
}
return e;
}
public static BigDecimal bigPi(MathContext mc) {
int k = 0;
BigDecimal ak = BigDecimal.ONE;
BigDecimal a = ak;
BigDecimal b = BigDecimal.ZERO;
BigDecimal c = BigDecimal.valueOf(640320);
BigDecimal c3 = c.pow(3);
double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);
double digits = 0;
while ( digits < mc.getPrecision() ) {
k++;
digits += digitePerTerm;
BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));
BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);
ak = ak.multiply(term, mc);
a = a.add(ak, mc);
b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);
}
BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);
return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);
}
public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {
double sqrt = Math.sqrt(squareDecimal.doubleValue());
BigDecimal x0 = new BigDecimal(sqrt, mc);
BigDecimal two = BigDecimal.valueOf(2);
while ( true ) {
BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);
String x1String = x1.toPlainString();
String x0String = x0.toPlainString();
if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {
break;
}
x0 = x1;
}
return x0;
}
}
| require "bigdecimal/math"
include BigMath
e, pi = E(200), PI(200)
[19, 43, 67, 163].each do |x|
puts "
end
|
Write a version of this Java function in Ruby with identical behavior. | import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class SDF {
public static HashMap<Character, Integer> countElementOcurrences(char[] array) {
HashMap<Character, Integer> countMap = new HashMap<Character, Integer>();
for (char element : array) {
Integer count = countMap.get(element);
count = (count == null) ? 1 : count + 1;
countMap.put(element, count);
}
return countMap;
}
private static <K, V extends Comparable<? super V>>
HashMap<K, V> descendingSortByValues(HashMap<K, V> map) {
List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
HashMap<K, V> sortedHashMap = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
sortedHashMap.put(entry.getKey(), entry.getValue());
}
return sortedHashMap;
}
public static String mostOcurrencesElement(char[] array, int k) {
HashMap<Character, Integer> countMap = countElementOcurrences(array);
System.out.println(countMap);
Map<Character, Integer> map = descendingSortByValues(countMap);
System.out.println(map);
int i = 0;
String output = "";
for (Map.Entry<Character, Integer> pairs : map.entrySet()) {
if (i++ >= k)
break;
output += "" + pairs.getKey() + pairs.getValue();
}
return output;
}
public static int getDiff(String str1, String str2, int limit) {
int similarity = 0;
int k = 0;
for (int i = 0; i < str1.length() ; i = k) {
k ++;
if (Character.isLetter(str1.charAt(i))) {
int pos = str2.indexOf(str1.charAt(i));
if (pos >= 0) {
String digitStr1 = "";
while ( k < str1.length() && !Character.isLetter(str1.charAt(k))) {
digitStr1 += str1.charAt(k);
k++;
}
int k2 = pos+1;
String digitStr2 = "";
while (k2 < str2.length() && !Character.isLetter(str2.charAt(k2)) ) {
digitStr2 += str2.charAt(k2);
k2++;
}
similarity += Integer.parseInt(digitStr2)
+ Integer.parseInt(digitStr1);
}
}
}
return Math.abs(limit - similarity);
}
public static int SDFfunc(String str1, String str2, int limit) {
return getDiff(mostOcurrencesElement(str1.toCharArray(), 2), mostOcurrencesElement(str2.toCharArray(), 2), limit);
}
public static void main(String[] args) {
String input1 = "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV";
String input2 = "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG";
System.out.println(SDF.SDFfunc(input1,input2,100));
}
}
| func _MostFreqKHashing(string, k) {
var seen = Hash()
var chars = string.chars
var freq = chars.freq
var schars = freq.keys.sort_by {|c| -freq{c} }
var mfkh = []
for i in ^k {
chars.each { |c|
seen{c} && next
if (freq{c} == freq{schars[i]}) {
seen{c} = true
mfkh << Hash(c => c, f => freq{c})
break
}
}
}
mfkh << (k-seen.len -> of { Hash(c => :NULL, f => 0) }...)
mfkh
}
func MostFreqKSDF(a, b, k, d) {
var mfkh_a = _MostFreqKHashing(a, k);
var mfkh_b = _MostFreqKHashing(b, k);
d - gather {
mfkh_a.each { |s|
s{:c} == :NULL && next
mfkh_b.each { |t|
s{:c} == t{:c} &&
take(s{:f} + (s{:f} == t{:f} ? 0 : t{:f}))
}
}
}.sum
}
func MostFreqKHashing(string, k) {
gather {
_MostFreqKHashing(string, k).each { |h|
take("%s%d" % (h{:c}, h{:f}))
}
}.join
}
var str1 = "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV"
var str2 = "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG"
say "str1 =
say "str2 =
say ''
say("MostFreqKHashing(str1, 2) = ", MostFreqKHashing(str1, 2))
say("MostFreqKHashing(str2, 2) = ", MostFreqKHashing(str2, 2))
say("MostFreqKSDF(str1, str2, 2, 100) = ", MostFreqKSDF(str1, str2, 2, 100))
say ''
var arr = [
%w(night nacht),
%w(my a),
%w(research research),
%w(aaaaabbbb ababababa),
%w(significant capabilities),
]
var k = 2
var limit = 10
for s,t in arr {
"mfkh(%s, %s,
s.dump, t.dump,
MostFreqKHashing(s, k).dump,
MostFreqKHashing(t, k).dump,
MostFreqKSDF(s, t, k, limit),
)
}
|
Produce a language-to-language conversion: from Java to Ruby, same semantics. |
package distanceAndBearing;
public class Airport {
private String airport;
private String country;
private String icao;
private double lat;
private double lon;
public String getAirportName() { return this.airport; }
public void setAirportName(String airport) { this.airport = airport; }
public String getCountry() { return this.country; }
public void setCountry(String country) { this.country = country; }
public String getIcao() { return this.icao; }
public void setIcao(String icao) { this.icao = icao; }
public double getLat() { return this.lat; }
public void setLat(double lat) { this.lat = lat; }
public double getLon() { return this.lon; }
public void setLon(double lon) { this.lon = lon; }
@Override
public String toString() {return "Airport: " + getAirportName() + ": ICAO: " + getIcao();}
}
package distanceAndBearing;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
public class DistanceAndBearing {
private final double earthRadius = 6371;
private File datFile;
private List<Airport> airports;
public DistanceAndBearing() { this.airports = new ArrayList<Airport>(); }
public boolean readFile(String filename) {
this.datFile = new File(filename);
try {
Scanner fileScanner = new Scanner(datFile);
String line;
while (fileScanner.hasNextLine()) {
line = fileScanner.nextLine();
line = line.replace(", ", "; ");
line = line.replace(",\",\"", "\",\"");
String[] parts = line.split(",");
Airport airport = new Airport();
airport.setAirportName(parts[1].replace("\"", ""));
airport.setCountry(parts[3].replace("\"", ""));
airport.setIcao(parts[5].replace("\"", ""));
airport.setLat(Double.valueOf(parts[6]));
airport.setLon(Double.valueOf(parts[7]));
this.airports.add(airport);
}
fileScanner.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}}
public double[] calculate(double lat1, double lon1, double lat2, double lon2) {
double[] results = new double[2];
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double rlat1 = Math.toRadians(lat1);
double rlat2 = Math.toRadians(lat2);
double a = Math.pow(Math.sin(dLat / 2), 2)
+ Math.pow(Math.sin(dLon / 2), 2) * Math.cos(rlat1) * Math.cos(rlat2);
double c = 2 * Math.asin(Math.sqrt(a));
double distance = earthRadius * c;
DecimalFormat df = new DecimalFormat("#0.00");
distance = Double.valueOf(df.format(distance));
results[0] = distance;
double X = Math.cos(rlat2) * Math.sin(dLon);
double Y = Math.cos(rlat1) * Math.sin(rlat2) - Math.sin(rlat1) * Math.cos(rlat2) * Math.cos(dLon);
double heading = Math.atan2(X, Y);
heading = Math.toDegrees(heading);
results[1] = heading;
return results;
}
public Airport searchByName(final String name) {
Airport airport = new Airport();
List<Airport> results = this.airports.stream().filter(ap -> ap.getAirportName().contains(name))
.collect(Collectors.toList());
airport = results.get(0);
return airport;
}
public List<Airport> findClosestAirports(double lat, double lon) {
Map<Double, Airport> airportDistances = new HashMap<>();
Map<Double, Airport> airportHeading = new HashMap<>();
List<Airport> closestAirports = new ArrayList<Airport>();
for (Airport ap : this.airports) {
double[] result = calculate(lat, lon, ap.getLat(), ap.getLon());
airportDistances.put(result[0], ap);
airportHeading.put(result[1], ap);
}
ArrayList<Double> distances = new ArrayList<>(airportDistances.keySet());
Collections.sort(distances);
for (int i = 0; i < 20; i++) { closestAirports.add(searchByName((airportDistances.get(distances.get(i)).getAirportName())));}
Map<String, Double> distanceMap = new HashMap<>();
for (Double d : airportDistances.keySet()) { distanceMap.put(airportDistances.get(d).getAirportName(), d);}
Map<String, Double> headingMap = new HashMap<>();
for (Double d : airportHeading.keySet()) {
double d2 = d;
if(d2<0){d2+=360'}
headingMap.put(airportHeading.get(d).getAirportName(), d2); }
System.out.printf("%-4s %-40s %-25s %-6s %12s %15s\n", "Num", "Airport", "Country", "ICAO", "Distance", "Bearing");
System.out.println("-----------------------------------------------------------------------------------------------------------");
int i = 0;
for (Airport a : closestAirports) {
System.out.printf("%-4s %-40s %-25s %-6s %12.1f %15.0f\n", ++i, a.getAirportName(), a.getCountry(), a.getIcao(), distanceMap.get(a.getAirportName())*0.5399568, headingMap.get(a.getAirportName()));
}
return closestAirports;
}
}
| require 'open-uri'
require 'csv'
include Math
RADIUS = 6372.8
def spherical_distance(start_coords, end_coords)
lat1, long1 = deg2rad(*start_coords)
lat2, long2 = deg2rad(*end_coords)
2 * RADIUS * asin(sqrt(sin((lat2-lat1)/2)**2 + cos(lat1) * cos(lat2) * sin((long2 - long1)/2)**2))
end
def bearing(start_coords, end_coords)
lat1, long1 = deg2rad(*start_coords)
lat2, long2 = deg2rad(*end_coords)
dlon = long2 - long1
atan2(sin(dlon) * cos(lat2), cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon))
end
def deg2rad(lat, long)
[lat * PI / 180, long * PI / 180]
end
uri = "https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat"
headers = %i(airportID
name
city
country
iata
icao
latitude
longitude
altitude
timezone
dst
tzOlson
type
source)
data = CSV.parse(URI.open(uri), headers: headers, converters: :numeric)
position = [51.514669, 2.198581]
data.each{|r| r[:dist] = (spherical_distance(position, [r[:latitude], r[:longitude]])/1.852).round(1)}
closest = data.min_by(20){|row| row[:dist] }
closest.each do |r|
bearing = (bearing(position,[r[:latitude], r[:longitude]])*180/PI).round % 360
puts "%-40s %-25s %-6s %12.1f %15.0f" % (r.values_at(:name, :country, :ICAO, :dist) << bearing)
end
|
Convert the following code from Java to Ruby, ensuring the logic remains intact. |
package distanceAndBearing;
public class Airport {
private String airport;
private String country;
private String icao;
private double lat;
private double lon;
public String getAirportName() { return this.airport; }
public void setAirportName(String airport) { this.airport = airport; }
public String getCountry() { return this.country; }
public void setCountry(String country) { this.country = country; }
public String getIcao() { return this.icao; }
public void setIcao(String icao) { this.icao = icao; }
public double getLat() { return this.lat; }
public void setLat(double lat) { this.lat = lat; }
public double getLon() { return this.lon; }
public void setLon(double lon) { this.lon = lon; }
@Override
public String toString() {return "Airport: " + getAirportName() + ": ICAO: " + getIcao();}
}
package distanceAndBearing;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
public class DistanceAndBearing {
private final double earthRadius = 6371;
private File datFile;
private List<Airport> airports;
public DistanceAndBearing() { this.airports = new ArrayList<Airport>(); }
public boolean readFile(String filename) {
this.datFile = new File(filename);
try {
Scanner fileScanner = new Scanner(datFile);
String line;
while (fileScanner.hasNextLine()) {
line = fileScanner.nextLine();
line = line.replace(", ", "; ");
line = line.replace(",\",\"", "\",\"");
String[] parts = line.split(",");
Airport airport = new Airport();
airport.setAirportName(parts[1].replace("\"", ""));
airport.setCountry(parts[3].replace("\"", ""));
airport.setIcao(parts[5].replace("\"", ""));
airport.setLat(Double.valueOf(parts[6]));
airport.setLon(Double.valueOf(parts[7]));
this.airports.add(airport);
}
fileScanner.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}}
public double[] calculate(double lat1, double lon1, double lat2, double lon2) {
double[] results = new double[2];
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double rlat1 = Math.toRadians(lat1);
double rlat2 = Math.toRadians(lat2);
double a = Math.pow(Math.sin(dLat / 2), 2)
+ Math.pow(Math.sin(dLon / 2), 2) * Math.cos(rlat1) * Math.cos(rlat2);
double c = 2 * Math.asin(Math.sqrt(a));
double distance = earthRadius * c;
DecimalFormat df = new DecimalFormat("#0.00");
distance = Double.valueOf(df.format(distance));
results[0] = distance;
double X = Math.cos(rlat2) * Math.sin(dLon);
double Y = Math.cos(rlat1) * Math.sin(rlat2) - Math.sin(rlat1) * Math.cos(rlat2) * Math.cos(dLon);
double heading = Math.atan2(X, Y);
heading = Math.toDegrees(heading);
results[1] = heading;
return results;
}
public Airport searchByName(final String name) {
Airport airport = new Airport();
List<Airport> results = this.airports.stream().filter(ap -> ap.getAirportName().contains(name))
.collect(Collectors.toList());
airport = results.get(0);
return airport;
}
public List<Airport> findClosestAirports(double lat, double lon) {
Map<Double, Airport> airportDistances = new HashMap<>();
Map<Double, Airport> airportHeading = new HashMap<>();
List<Airport> closestAirports = new ArrayList<Airport>();
for (Airport ap : this.airports) {
double[] result = calculate(lat, lon, ap.getLat(), ap.getLon());
airportDistances.put(result[0], ap);
airportHeading.put(result[1], ap);
}
ArrayList<Double> distances = new ArrayList<>(airportDistances.keySet());
Collections.sort(distances);
for (int i = 0; i < 20; i++) { closestAirports.add(searchByName((airportDistances.get(distances.get(i)).getAirportName())));}
Map<String, Double> distanceMap = new HashMap<>();
for (Double d : airportDistances.keySet()) { distanceMap.put(airportDistances.get(d).getAirportName(), d);}
Map<String, Double> headingMap = new HashMap<>();
for (Double d : airportHeading.keySet()) {
double d2 = d;
if(d2<0){d2+=360'}
headingMap.put(airportHeading.get(d).getAirportName(), d2); }
System.out.printf("%-4s %-40s %-25s %-6s %12s %15s\n", "Num", "Airport", "Country", "ICAO", "Distance", "Bearing");
System.out.println("-----------------------------------------------------------------------------------------------------------");
int i = 0;
for (Airport a : closestAirports) {
System.out.printf("%-4s %-40s %-25s %-6s %12.1f %15.0f\n", ++i, a.getAirportName(), a.getCountry(), a.getIcao(), distanceMap.get(a.getAirportName())*0.5399568, headingMap.get(a.getAirportName()));
}
return closestAirports;
}
}
| require 'open-uri'
require 'csv'
include Math
RADIUS = 6372.8
def spherical_distance(start_coords, end_coords)
lat1, long1 = deg2rad(*start_coords)
lat2, long2 = deg2rad(*end_coords)
2 * RADIUS * asin(sqrt(sin((lat2-lat1)/2)**2 + cos(lat1) * cos(lat2) * sin((long2 - long1)/2)**2))
end
def bearing(start_coords, end_coords)
lat1, long1 = deg2rad(*start_coords)
lat2, long2 = deg2rad(*end_coords)
dlon = long2 - long1
atan2(sin(dlon) * cos(lat2), cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon))
end
def deg2rad(lat, long)
[lat * PI / 180, long * PI / 180]
end
uri = "https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat"
headers = %i(airportID
name
city
country
iata
icao
latitude
longitude
altitude
timezone
dst
tzOlson
type
source)
data = CSV.parse(URI.open(uri), headers: headers, converters: :numeric)
position = [51.514669, 2.198581]
data.each{|r| r[:dist] = (spherical_distance(position, [r[:latitude], r[:longitude]])/1.852).round(1)}
closest = data.min_by(20){|row| row[:dist] }
closest.each do |r|
bearing = (bearing(position,[r[:latitude], r[:longitude]])*180/PI).round % 360
puts "%-40s %-25s %-6s %12.1f %15.0f" % (r.values_at(:name, :country, :ICAO, :dist) << bearing)
end
|
Generate an equivalent Ruby version of this Java code. | public class PanBaseNonPrimes {
public static void main(String[] args) {
System.out.printf("First 50 prime pan-base composites:\n");
int count = 0;
for (long n = 2; count < 50; ++n) {
if (isPanBaseNonPrime(n)) {
++count;
System.out.printf("%3d%c", n, count % 10 == 0 ? '\n' : ' ');
}
}
System.out.printf("\nFirst 20 odd prime pan-base composites:\n");
count = 0;
for (long n = 3; count < 20; n += 2) {
if (isPanBaseNonPrime(n)) {
++count;
System.out.printf("%3d%c", n, count % 10 == 0 ? '\n' : ' ');
}
}
final long limit = 10000;
count = 0;
int odd = 0;
for (long n = 2; n <= limit; ++n) {
if (isPanBaseNonPrime(n)) {
++count;
if (n % 2 == 1)
++odd;
}
}
System.out.printf("\nCount of pan-base composites up to and including %d: %d\n",
limit, count);
double percent = 100.0 * odd / count;
System.out.printf("Percent odd up to and including %d: %f\n",
limit, percent);
System.out.printf("Percent even up to and including %d: %f\n",
limit, 100.0 - percent);
}
private static boolean isPanBaseNonPrime(long n) {
if (n < 10)
return !isPrime(n);
if (n > 10 && n % 10 == 0)
return true;
byte[] d = new byte[20];
int count = digits(n, d);
byte max_digit = 0;
for (int i = 0; i < count; ++i) {
if (max_digit < d[i])
max_digit = d[i];
}
for (long base = max_digit + 1; base <= n; ++base) {
if (isPrime(fromDigits(d, count, base)))
return false;
}
return true;
}
private static final long[] WHEEL = {4, 2, 4, 2, 4, 6, 2, 6};
private static boolean isPrime(long n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
if (n % 5 == 0)
return n == 5;
for (long p = 7;;) {
for (int i = 0; i < 8; ++i) {
if (p * p > n)
return true;
if (n % p == 0)
return false;
p += WHEEL[i];
}
}
}
private static int digits(long n, byte[] d) {
int count = 0;
for (; n > 0 && count < d.length; n /= 10, ++count)
d[count] = (byte)(n % 10);
return count;
}
private static long fromDigits(byte[] a, int count, long base) {
long n = 0;
while (count-- > 0)
n = n * base + a[count];
return n;
}
}
| require 'prime'
def int_from_digits(ar, base=10)
raise ArgumentError, "
ar.each_with_index.sum {|d, i| d*base**i }
end
limit = 2500
a121719 = (2..limit).lazy.select do |n|
next false if (n < 10 && n.prime?)
digits = n.digits
from = digits.max + 1
(from..n).none?{|base| int_from_digits(digits, base).prime? }
end
n = 50
puts "First
a121719.take(n).each_slice(10){|s| puts "%4s"*s.size % s}
n = 20
puts "\nFirst
a121719.select(&:odd?).take(n).each_slice(10){|s| puts "%4s"*s.size % s }
tally = a121719.map(&:odd?).tally
total = tally.values.sum
puts "\nCount of pan-base composites up to and including
puts "Number of odds is
puts "Number of evens is
|
Maintain the same structure and functionality when rewriting this code in Ruby. | import java.util.*;
public class PracticalNumbers {
public static void main(String[] args) {
final int from = 1;
final int to = 333;
List<Integer> practical = new ArrayList<>();
for (int i = from; i <= to; ++i) {
if (isPractical(i))
practical.add(i);
}
System.out.printf("Found %d practical numbers between %d and %d:\n%s\n",
practical.size(), from, to, shorten(practical, 10));
printPractical(666);
printPractical(6666);
printPractical(66666);
printPractical(672);
printPractical(720);
printPractical(222222);
}
private static void printPractical(int n) {
if (isPractical(n))
System.out.printf("%d is a practical number.\n", n);
else
System.out.printf("%d is not a practical number.\n", n);
}
private static boolean isPractical(int n) {
int[] divisors = properDivisors(n);
for (int i = 1; i < n; ++i) {
if (!sumOfAnySubset(i, divisors, divisors.length))
return false;
}
return true;
}
private static boolean sumOfAnySubset(int n, int[] f, int len) {
if (len == 0)
return false;
int total = 0;
for (int i = 0; i < len; ++i) {
if (n == f[i])
return true;
total += f[i];
}
if (n == total)
return true;
if (n > total)
return false;
--len;
int d = n - f[len];
return (d > 0 && sumOfAnySubset(d, f, len)) || sumOfAnySubset(n, f, len);
}
private static int[] properDivisors(int n) {
List<Integer> divisors = new ArrayList<>();
divisors.add(1);
for (int i = 2;; ++i) {
int i2 = i * i;
if (i2 > n)
break;
if (n % i == 0) {
divisors.add(i);
if (i2 != n)
divisors.add(n / i);
}
}
int[] result = new int[divisors.size()];
for (int i = 0; i < result.length; ++i)
result[i] = divisors.get(i);
Arrays.sort(result);
return result;
}
private static String shorten(List<Integer> list, int n) {
StringBuilder str = new StringBuilder();
int len = list.size(), i = 0;
if (n > 0 && len > 0)
str.append(list.get(i++));
for (; i < n && i < len; ++i) {
str.append(", ");
str.append(list.get(i));
}
if (len > i + n) {
if (n > 0)
str.append(", ...");
i = len - n;
}
for (; i < len; ++i) {
str.append(", ");
str.append(list.get(i));
}
return str.toString();
}
}
| say is_practical(2**128 + 1)
say is_practical(2**128 + 4)
|
Convert this Java snippet to Ruby and keep its semantics consistent. | import java.awt.*;
import java.util.List;
import java.awt.geom.Path2D;
import java.util.*;
import javax.swing.*;
import static java.lang.Math.*;
import static java.util.stream.Collectors.toList;
public class PenroseTiling extends JPanel {
class Tile {
double x, y, angle, size;
Type type;
Tile(Type t, double x, double y, double a, double s) {
type = t;
this.x = x;
this.y = y;
angle = a;
size = s;
}
@Override
public boolean equals(Object o) {
if (o instanceof Tile) {
Tile t = (Tile) o;
return type == t.type && x == t.x && y == t.y && angle == t.angle;
}
return false;
}
}
enum Type {
Kite, Dart
}
static final double G = (1 + sqrt(5)) / 2;
static final double T = toRadians(36);
List<Tile> tiles = new ArrayList<>();
public PenroseTiling() {
int w = 700, h = 450;
setPreferredSize(new Dimension(w, h));
setBackground(Color.white);
tiles = deflateTiles(setupPrototiles(w, h), 5);
}
List<Tile> setupPrototiles(int w, int h) {
List<Tile> proto = new ArrayList<>();
for (double a = PI / 2 + T; a < 3 * PI; a += 2 * T)
proto.add(new Tile(Type.Kite, w / 2, h / 2, a, w / 2.5));
return proto;
}
List<Tile> deflateTiles(List<Tile> tls, int generation) {
if (generation <= 0)
return tls;
List<Tile> next = new ArrayList<>();
for (Tile tile : tls) {
double x = tile.x, y = tile.y, a = tile.angle, nx, ny;
double size = tile.size / G;
if (tile.type == Type.Dart) {
next.add(new Tile(Type.Kite, x, y, a + 5 * T, size));
for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {
nx = x + cos(a - 4 * T * sign) * G * tile.size;
ny = y - sin(a - 4 * T * sign) * G * tile.size;
next.add(new Tile(Type.Dart, nx, ny, a - 4 * T * sign, size));
}
} else {
for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {
next.add(new Tile(Type.Dart, x, y, a - 4 * T * sign, size));
nx = x + cos(a - T * sign) * G * tile.size;
ny = y - sin(a - T * sign) * G * tile.size;
next.add(new Tile(Type.Kite, nx, ny, a + 3 * T * sign, size));
}
}
}
tls = next.stream().distinct().collect(toList());
return deflateTiles(tls, generation - 1);
}
void drawTiles(Graphics2D g) {
double[][] dist = {{G, G, G}, {-G, -1, -G}};
for (Tile tile : tiles) {
double angle = tile.angle - T;
Path2D path = new Path2D.Double();
path.moveTo(tile.x, tile.y);
int ord = tile.type.ordinal();
for (int i = 0; i < 3; i++) {
double x = tile.x + dist[ord][i] * tile.size * cos(angle);
double y = tile.y - dist[ord][i] * tile.size * sin(angle);
path.lineTo(x, y);
angle += T;
}
path.closePath();
g.setColor(ord == 0 ? Color.orange : Color.yellow);
g.fill(path);
g.setColor(Color.darkGray);
g.draw(path);
}
}
@Override
public void paintComponent(Graphics og) {
super.paintComponent(og);
Graphics2D g = (Graphics2D) og;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawTiles(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Penrose Tiling");
f.setResizable(false);
f.add(new PenroseTiling(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
| var rules = Hash(
a => 'cE++dE----bE[-cE----aE]++',
b => '+cE--dE[---aE--bE]+',
c => '-aE++bE[+++cE++dE]-',
d => '--cE++++aE[+dE++++bE]--bE',
E => '',
)
var lsys = LSystem(
width: 1000,
height: 1000,
scale: 1,
xoff: -500,
yoff: -500,
len: 40,
angle: 36,
color: 'dark blue',
)
lsys.execute('[b]++[b]++[b]++[b]++[b]', 5, "penrose_tiling.png", rules)
|
Translate the given Java code snippet into Ruby without altering its behavior. | import java.math.BigDecimal;
public class GeneralisedFloatingPointAddition {
public static void main(String[] args) {
BigDecimal oneExp72 = new BigDecimal("1E72");
for ( int i = 0 ; i <= 21+7 ; i++ ) {
String s = "12345679";
for ( int j = 0 ; j < i ; j++ ) {
s += "012345679";
}
int exp = 63 - 9*i;
s += "E" + exp;
BigDecimal num = new BigDecimal(s).multiply(BigDecimal.valueOf(81)).add(new BigDecimal("1E" + exp));
System.out.printf("Test value (%s) equals computed value: %b. Computed = %s%n", oneExp72, num.compareTo(oneExp72) == 0 , num);
}
}
}
| p 12345679e63 * 81 + 1e63
p 12345679012345679e54 * 81 + 1e54
p 12345679012345679012345679e45 * 81 + 1e45
p 12345679012345679012345679012345679e36 * 81 + 1e36
|
Ensure the translated Ruby code behaves exactly like the original Java snippet. | import java.math.BigDecimal;
public class GeneralisedFloatingPointAddition {
public static void main(String[] args) {
BigDecimal oneExp72 = new BigDecimal("1E72");
for ( int i = 0 ; i <= 21+7 ; i++ ) {
String s = "12345679";
for ( int j = 0 ; j < i ; j++ ) {
s += "012345679";
}
int exp = 63 - 9*i;
s += "E" + exp;
BigDecimal num = new BigDecimal(s).multiply(BigDecimal.valueOf(81)).add(new BigDecimal("1E" + exp));
System.out.printf("Test value (%s) equals computed value: %b. Computed = %s%n", oneExp72, num.compareTo(oneExp72) == 0 , num);
}
}
}
| p 12345679e63 * 81 + 1e63
p 12345679012345679e54 * 81 + 1e54
p 12345679012345679012345679e45 * 81 + 1e45
p 12345679012345679012345679012345679e36 * 81 + 1e36
|
Keep all operations the same but rewrite the snippet in Ruby. | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PowerfulNumbers {
public static void main(String[] args) {
System.out.printf("Task: For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
BigInteger max = BigInteger.valueOf(10).pow(k);
List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);
System.out.printf("There are %d %d-powerful numbers between 1 and %d. %nList: %s%n", powerfulNumbers.size(), k, max, getList(powerfulNumbers));
}
System.out.printf("%nTask: For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
List<Integer> powCount = new ArrayList<>();
for ( int j = 0 ; j < k+10 ; j++ ) {
BigInteger max = BigInteger.valueOf(10).pow(j);
powCount.add(countPowerFulNumbers(max, k));
}
System.out.printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n", k, k+9, powCount);
}
}
private static String getList(List<BigInteger> list) {
StringBuilder sb = new StringBuilder();
sb.append(list.subList(0, 5).toString().replace("]", ""));
sb.append(" ... ");
sb.append(list.subList(list.size()-5, list.size()).toString().replace("[", ""));
return sb.toString();
}
private static int countPowerFulNumbers(BigInteger max, int k) {
return potentialPowerful(max, k).size();
}
private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {
List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));
Collections.sort(powerfulNumbers);
return powerfulNumbers;
}
private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {
int[] indexes = new int[k];
for ( int i = 0 ; i < k ; i++ ) {
indexes[i] = 1;
}
Set<BigInteger> powerful = new HashSet<>();
boolean foundPower = true;
while ( foundPower ) {
boolean genPowerful = false;
for ( int index = 0 ; index < k ; index++ ) {
BigInteger power = BigInteger.ONE;
for ( int i = 0 ; i < k ; i++ ) {
power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));
}
if ( power.compareTo(max) <= 0 ) {
powerful.add(power);
indexes[0] += 1;
genPowerful = true;
break;
}
else {
indexes[index] = 1;
if ( index < k-1 ) {
indexes[index+1] += 1;
}
}
}
if ( ! genPowerful ) {
foundPower = false;
}
}
return powerful;
}
}
| func powerful(n, k=2) {
var list = []
func (m,r) {
if (r < k) {
list << m
return nil
}
for a in (1 .. iroot(idiv(n,m), r)) {
if (r > k) {
a.is_coprime(m) || next
a.is_squarefree || next
}
__FUNC__(m * a**r, r-1)
}
}(1, 2*k - 1)
return list.sort
}
for k in (2..10) {
var a = powerful(10**k, k)
var h = a.head(5).join(', ')
var t = a.tail(5).join(', ')
printf("For k=%-2d there are %d k-powerful numbers <= 10^k: [%s, ..., %s]\n", k, a.len, h, t)
}
|
Convert the following code from Java to Ruby, ensuring the logic remains intact. | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PowerfulNumbers {
public static void main(String[] args) {
System.out.printf("Task: For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
BigInteger max = BigInteger.valueOf(10).pow(k);
List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);
System.out.printf("There are %d %d-powerful numbers between 1 and %d. %nList: %s%n", powerfulNumbers.size(), k, max, getList(powerfulNumbers));
}
System.out.printf("%nTask: For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
List<Integer> powCount = new ArrayList<>();
for ( int j = 0 ; j < k+10 ; j++ ) {
BigInteger max = BigInteger.valueOf(10).pow(j);
powCount.add(countPowerFulNumbers(max, k));
}
System.out.printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n", k, k+9, powCount);
}
}
private static String getList(List<BigInteger> list) {
StringBuilder sb = new StringBuilder();
sb.append(list.subList(0, 5).toString().replace("]", ""));
sb.append(" ... ");
sb.append(list.subList(list.size()-5, list.size()).toString().replace("[", ""));
return sb.toString();
}
private static int countPowerFulNumbers(BigInteger max, int k) {
return potentialPowerful(max, k).size();
}
private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {
List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));
Collections.sort(powerfulNumbers);
return powerfulNumbers;
}
private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {
int[] indexes = new int[k];
for ( int i = 0 ; i < k ; i++ ) {
indexes[i] = 1;
}
Set<BigInteger> powerful = new HashSet<>();
boolean foundPower = true;
while ( foundPower ) {
boolean genPowerful = false;
for ( int index = 0 ; index < k ; index++ ) {
BigInteger power = BigInteger.ONE;
for ( int i = 0 ; i < k ; i++ ) {
power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));
}
if ( power.compareTo(max) <= 0 ) {
powerful.add(power);
indexes[0] += 1;
genPowerful = true;
break;
}
else {
indexes[index] = 1;
if ( index < k-1 ) {
indexes[index+1] += 1;
}
}
}
if ( ! genPowerful ) {
foundPower = false;
}
}
return powerful;
}
}
| func powerful(n, k=2) {
var list = []
func (m,r) {
if (r < k) {
list << m
return nil
}
for a in (1 .. iroot(idiv(n,m), r)) {
if (r > k) {
a.is_coprime(m) || next
a.is_squarefree || next
}
__FUNC__(m * a**r, r-1)
}
}(1, 2*k - 1)
return list.sort
}
for k in (2..10) {
var a = powerful(10**k, k)
var h = a.head(5).join(', ')
var t = a.tail(5).join(', ')
printf("For k=%-2d there are %d k-powerful numbers <= 10^k: [%s, ..., %s]\n", k, a.len, h, t)
}
|
Write the same algorithm in AWK as shown in this VB implementation. | Sub BenfordLaw()
Dim BenResult(1 To 9) As Long
BENref = "30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%"
For Each c In Selection.Cells
If InStr(1, "-0123456789", Left(c, 1)) > 0 Then
For i = 1 To 9
If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For
Next
End If
Next
Total= Application.Sum(BenResult)
biggest= Len(CStr(BenResult(1)))
txt = "# | Values | Real | Expected " & vbCrLf
For i = 1 To 9
If BenResult(i) > 0 Then
txt = txt & "#" & i & " | " & vbTab
txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, " ") & Format(BenResult(i), "0") & " | " & vbTab
txt = txt & String((Len(CStr(Format(BenResult(1) / Total, "##0.0%"))) - Len(CStr(Format(BenResult(i) / Total, "##0.0%")))) * 2, " ") & Format(BenResult(i) / Total, "##0.0%") & " | " & vbTab
txt = txt & Format(Split(BENref, "|")(i - 1), " ##0.0%") & vbCrLf
End If
Next
MsgBox txt, vbOKOnly, "Finish"
End Sub
}
|
BEGIN {
n = 1000
for (i=1; i<=n; i++) {
arr[substr(fibonacci(i),1,1)]++
}
print("digit expected observed deviation")
for (i=1; i<=9; i++) {
expected = log10(i+1) - log10(i)
actual = arr[i] / n
deviation = expected - actual
printf("%5d %8.4f %8.4f %9.4f\n",i,expected*100,actual*100,abs(deviation*100))
}
exit(0)
}
function fibonacci(n, a,b,c,i) {
a = 0
b = 1
for (i=1; i<=n; i++) {
c = a + b
a = b
b = c
}
return(c)
}
function abs(x) { if (x >= 0) { return x } else { return -x } }
function log10(x) { return log(x)/log(10) }
|
Rewrite the snippet below in AWK so it works the same as the original VB code. | type TSettings extends QObject
FullName as string
FavouriteFruit as string
NeedSpelling as integer
SeedsRemoved as integer
OtherFamily as QStringlist
Constructor
FullName = ""
FavouriteFruit = ""
NeedSpelling = 0
SeedsRemoved = 0
OtherFamily.clear
end constructor
end type
Dim Settings as TSettings
dim ConfigList as QStringList
dim x as integer
dim StrLine as string
dim StrPara as string
dim StrData as string
function Trim$(Expr as string) as string
Result = Rtrim$(Ltrim$(Expr))
end function
Sub ConfigOption(PData as string)
dim x as integer
for x = 1 to tally(PData, ",") +1
Settings.OtherFamily.AddItems Trim$(field$(PData, "," ,x))
next
end sub
Function ConfigBoolean(PData as string) as integer
PData = Trim$(PData)
Result = iif(lcase$(PData)="true" or PData="1" or PData="", 1, 0)
end function
sub ReadSettings
ConfigList.LoadFromFile("Rosetta.cfg")
ConfigList.text = REPLACESUBSTR$(ConfigList.text,"="," ")
for x = 0 to ConfigList.ItemCount -1
StrLine = Trim$(ConfigList.item(x))
StrPara = Trim$(field$(StrLine," ",1))
StrData = Trim$(lTrim$(StrLine - StrPara))
Select case UCase$(StrPara)
case "FULLNAME" : Settings.FullName = StrData
case "FAVOURITEFRUIT" : Settings.FavouriteFruit = StrData
case "NEEDSPEELING" : Settings.NeedSpelling = ConfigBoolean(StrData)
case "SEEDSREMOVED" : Settings.SeedsRemoved = ConfigBoolean(StrData)
case "OTHERFAMILY" : Call ConfigOption(StrData)
end select
next
end sub
Call ReadSettings
|
BEGIN {
fullname = favouritefruit = ""
needspeeling = seedsremoved = "false"
fn = "READ_A_CONFIGURATION_FILE.INI"
while (getline rec <fn > 0) {
tmp = tolower(rec)
if (tmp ~ /^ *fullname/) { fullname = extract(rec) }
else if (tmp ~ /^ *favouritefruit/) { favouritefruit = extract(rec) }
else if (tmp ~ /^ *needspeeling/) { needspeeling = "true" }
else if (tmp ~ /^ *seedsremoved/) { seedsremoved = "true" }
else if (tmp ~ /^ *otherfamily/) { split(extract(rec),otherfamily,",") }
}
close(fn)
printf("fullname=%s\n",fullname)
printf("favouritefruit=%s\n",favouritefruit)
printf("needspeeling=%s\n",needspeeling)
printf("seedsremoved=%s\n",seedsremoved)
for (i=1; i<=length(otherfamily); i++) {
sub(/^ +/,"",otherfamily[i])
sub(/ +$/,"",otherfamily[i])
printf("otherfamily(%d)=%s\n",i,otherfamily[i])
}
exit(0)
}
function extract(rec, pos,str) {
sub(/^ +/,"",rec)
pos = match(rec,/[= ]/)
str = substr(rec,pos)
gsub(/^[= ]+/,"",str)
sub(/ +$/,"",str)
return(str)
}
|
Translate the given VB code snippet into AWK without altering its behavior. | Public Sub case_sensitivity()
Dim DOG As String
DOG = "Benjamin"
DOG = "Samba"
DOG = "Bernie"
Debug.Print "There is just one dog named " & DOG
End Sub
| BEGIN {
dog = "Benjamin"
Dog = "Samba"
DOG = "Bernie"
printf "The three dogs are named %s, %s and %s.\n", dog, Dog, DOG
}
|
Port the following code from VB to AWK with equivalent syntax and logic. | Private Function ValidateUserWords(userstring As String) As String
Dim s As String
Dim user_words() As String
Dim command_table As Scripting.Dictionary
Set command_table = New Scripting.Dictionary
Dim abbreviations As Scripting.Dictionary
Set abbreviations = New Scripting.Dictionary
abbreviations.CompareMode = TextCompare
Dim commandtable() As String
Dim commands As String
s = s & "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
s = s & "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
s = s & "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
s = s & "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
s = s & "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
s = s & "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
s = s & "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up "
commandtable = Split(s, " ")
Dim i As Integer
For Each word In commandtable
If Len(word) > 0 Then
i = 1
Do While Mid(word, i, 1) >= "A" And Mid(word, i, 1) <= "Z"
i = i + 1
Loop
command_table.Add Key:=word, Item:=i - 1
End If
Next word
For Each word In command_table
For i = command_table(word) To Len(word)
On Error Resume Next
abbreviations.Add Key:=Left(word, i), Item:=UCase(word)
Next i
Next word
user_words() = Split(userstring, " ")
For Each word In user_words
If Len(word) > 0 Then
If abbreviations.exists(word) Then
commands = commands & abbreviations(word) & " "
Else
commands = commands & "*error* "
End If
End If
Next word
ValidateUserWords = commands
End Function
Public Sub program()
Dim guserstring As String
guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin"
Debug.Print "user words:", guserstring
Debug.Print "full words:", ValidateUserWords(guserstring)
End Sub
|
BEGIN {
FS=" ";
split(" Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy" \
" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find" \
" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput" \
" Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO" \
" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT" \
" READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT" \
" RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up" \
, CMD);
for (k=1; k <= length(CMD); k++) {
cmd[k] = CMD[k];
sub(/[a-z]*$/,"",cmd[k]);
}
}
function GET_ABBR(input) {
for (k2=1; k2<=length(CMD); k2++) {
if (index(toupper(CMD[k2]),input)==1) {
if (index(input,toupper(cmd[k2]))==1) {
return toupper(CMD[k2]);
}
}
}
return "*error*";
}
{
R="";
for (k1=1; k1 <= NF; k1++) {
R=R" "GET_ABBR(toupper($k1))
}
print R;
}
|
Transform the following VB implementation into AWK, maintaining the same output and logic. | Private Function ValidateUserWords(userstring As String) As String
Dim s As String
Dim user_words() As String
Dim command_table As Scripting.Dictionary
Set command_table = New Scripting.Dictionary
Dim abbreviations As Scripting.Dictionary
Set abbreviations = New Scripting.Dictionary
abbreviations.CompareMode = TextCompare
Dim commandtable() As String
Dim commands As String
s = s & "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
s = s & "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
s = s & "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
s = s & "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
s = s & "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
s = s & "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
s = s & "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up "
commandtable = Split(s, " ")
Dim i As Integer
For Each word In commandtable
If Len(word) > 0 Then
i = 1
Do While Mid(word, i, 1) >= "A" And Mid(word, i, 1) <= "Z"
i = i + 1
Loop
command_table.Add Key:=word, Item:=i - 1
End If
Next word
For Each word In command_table
For i = command_table(word) To Len(word)
On Error Resume Next
abbreviations.Add Key:=Left(word, i), Item:=UCase(word)
Next i
Next word
user_words() = Split(userstring, " ")
For Each word In user_words
If Len(word) > 0 Then
If abbreviations.exists(word) Then
commands = commands & abbreviations(word) & " "
Else
commands = commands & "*error* "
End If
End If
Next word
ValidateUserWords = commands
End Function
Public Sub program()
Dim guserstring As String
guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin"
Debug.Print "user words:", guserstring
Debug.Print "full words:", ValidateUserWords(guserstring)
End Sub
|
BEGIN {
FS=" ";
split(" Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy" \
" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find" \
" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput" \
" Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO" \
" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT" \
" READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT" \
" RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up" \
, CMD);
for (k=1; k <= length(CMD); k++) {
cmd[k] = CMD[k];
sub(/[a-z]*$/,"",cmd[k]);
}
}
function GET_ABBR(input) {
for (k2=1; k2<=length(CMD); k2++) {
if (index(toupper(CMD[k2]),input)==1) {
if (index(input,toupper(cmd[k2]))==1) {
return toupper(CMD[k2]);
}
}
}
return "*error*";
}
{
R="";
for (k1=1; k1 <= NF; k1++) {
R=R" "GET_ABBR(toupper($k1))
}
print R;
}
|
Write the same code in AWK as shown below in VB. | Sub truncate(fpath,n)
Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FileExists(fpath) = False Then
WScript.Echo fpath & " does not exist"
Exit Sub
End If
content = ""
Set objinstream = CreateObject("Adodb.Stream")
With objinstream
.Type = 1
.Open
.LoadFromFile(fpath)
If n <= .Size Then
content = .Read(n)
Else
WScript.Echo "The specified size is larger than the file content"
Exit Sub
End If
.Close
End With
Set objoutstream = CreateObject("Adodb.Stream")
With objoutstream
.Type = 1
.Open
.Write content
.SaveToFile fpath,2
.Close
End With
Set objinstream = Nothing
Set objoutstream = Nothing
Set objfso = Nothing
End Sub
Call truncate("C:\temp\test.txt",30)
|
BEGIN {
main("NOTHERE",100)
main("FILENAME.TMP",-1)
main("FILENAME.TMP",500)
exit(0)
}
function main(filename,size, ret) {
ret = truncate_file(filename,size)
if (ret != "") {
printf("error: FILENAME=%s, %s\n",filename,ret)
}
}
function truncate_file(filename,size, cmd,fnr,msg,old_BINMODE,old_RS,rec) {
cmd = sprintf("ls --full-time -o %s",filename)
if (size < 0) {
return("size cannot be negative")
}
old_BINMODE = BINMODE
old_RS = RS
BINMODE = 3
RS = "[^\x00-\xFF]"
while (getline rec <filename > 0) {
fnr++
}
close(filename)
if (fnr == 0) {
msg = "file not found"
}
if (fnr > 1) {
msg = "choose a different RecordSeparator"
}
if (msg == "") {
system(cmd)
if (length(rec) > size) {
rec = substr(rec,1,size)
}
printf("%s",rec) >filename
close(filename)
system(cmd)
}
BINMODE = old_BINMODE
RS = old_RS
return(msg)
}
|
Port the provided VB code into AWK while preserving the original functionality. | Sub truncate(fpath,n)
Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FileExists(fpath) = False Then
WScript.Echo fpath & " does not exist"
Exit Sub
End If
content = ""
Set objinstream = CreateObject("Adodb.Stream")
With objinstream
.Type = 1
.Open
.LoadFromFile(fpath)
If n <= .Size Then
content = .Read(n)
Else
WScript.Echo "The specified size is larger than the file content"
Exit Sub
End If
.Close
End With
Set objoutstream = CreateObject("Adodb.Stream")
With objoutstream
.Type = 1
.Open
.Write content
.SaveToFile fpath,2
.Close
End With
Set objinstream = Nothing
Set objoutstream = Nothing
Set objfso = Nothing
End Sub
Call truncate("C:\temp\test.txt",30)
|
BEGIN {
main("NOTHERE",100)
main("FILENAME.TMP",-1)
main("FILENAME.TMP",500)
exit(0)
}
function main(filename,size, ret) {
ret = truncate_file(filename,size)
if (ret != "") {
printf("error: FILENAME=%s, %s\n",filename,ret)
}
}
function truncate_file(filename,size, cmd,fnr,msg,old_BINMODE,old_RS,rec) {
cmd = sprintf("ls --full-time -o %s",filename)
if (size < 0) {
return("size cannot be negative")
}
old_BINMODE = BINMODE
old_RS = RS
BINMODE = 3
RS = "[^\x00-\xFF]"
while (getline rec <filename > 0) {
fnr++
}
close(filename)
if (fnr == 0) {
msg = "file not found"
}
if (fnr > 1) {
msg = "choose a different RecordSeparator"
}
if (msg == "") {
system(cmd)
if (length(rec) > size) {
rec = substr(rec,1,size)
}
printf("%s",rec) >filename
close(filename)
system(cmd)
}
BINMODE = old_BINMODE
RS = old_RS
return(msg)
}
|
Generate a AWK translation of this VB snippet without changing its computational steps. | Sub arrShellSort(ByVal arrData As Variant)
Dim lngHold, lngGap As Long
Dim lngCount, lngMin, lngMax As Long
Dim varItem As Variant
lngMin = LBound(arrData)
lngMax = UBound(arrData)
lngGap = lngMin
Do While (lngGap < lngMax)
lngGap = 3 * lngGap + 1
Loop
Do While (lngGap > 1)
lngGap = lngGap \ 3
For lngCount = lngGap + lngMin To lngMax
varItem = arrData(lngCount)
lngHold = lngCount
Do While ((arrData(lngHold - lngGap) > varItem))
arrData(lngHold) = arrData(lngHold - lngGap)
lngHold = lngHold - lngGap
If (lngHold < lngMin + lngGap) Then Exit Do
Loop
arrData(lngHold) = varItem
Next
Loop
arrShellSort = arrData
End Sub
| {
line[NR] = $0
}
END {
increment = int(NR / 2)
while ( increment > 0 ) {
for(i=increment+1; i <= NR; i++) {
j = i
temp = line[i]
while ( (j >= increment+1) && (line[j-increment] > temp) ) {
line[j] = line[j-increment]
j -= increment
}
line[j] = temp
}
if ( increment == 2 )
increment = 1
else
increment = int(increment*5/11)
}
for(i=1; i <= NR; i++) {
print line[i]
}
}
|
Change the programming language of this snippet from VB to AWK without modifying what it does. | Function read_line(filepath,n)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(filepath,1)
arrLines = Split(objFile.ReadAll,vbCrLf)
If UBound(arrLines) >= n-1 Then
If arrLines(n-1) <> "" Then
read_line = arrLines(n-1)
Else
read_line = "Line " & n & " is null."
End If
Else
read_line = "Line " & n & " does not exist."
End If
objFile.Close
Set objFSO = Nothing
End Function
WScript.Echo read_line("c:\temp\input.txt",7)
|
FNR==lineno { storedline=$0; found++ }
END {
if (found < 1) {
print "ERROR: Line", lineno, "not found"
exit 1
}
print storedline
}
|
Change the programming language of this snippet from VB to AWK without modifying what it does. | Function read_line(filepath,n)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(filepath,1)
arrLines = Split(objFile.ReadAll,vbCrLf)
If UBound(arrLines) >= n-1 Then
If arrLines(n-1) <> "" Then
read_line = arrLines(n-1)
Else
read_line = "Line " & n & " is null."
End If
Else
read_line = "Line " & n & " does not exist."
End If
objFile.Close
Set objFSO = Nothing
End Function
WScript.Echo read_line("c:\temp\input.txt",7)
|
FNR==lineno { storedline=$0; found++ }
END {
if (found < 1) {
print "ERROR: Line", lineno, "not found"
exit 1
}
print storedline
}
|
Write a version of this VB function in AWK with identical behavior. | Dim URL As String = "http://foo bar/"
URL = EncodeURLComponent(URL)
Print(URL)
| BEGIN {
for (i = 0; i <= 255; i++)
ord[sprintf("%c", i)] = i
}
function escape(str, c, len, res) {
len = length(str)
res = ""
for (i = 1; i <= len; i++) {
c = substr(str, i, 1);
if (c ~ /[0-9A-Za-z]/)
res = res c
else
res = res "%" sprintf("%02X", ord[c])
}
return res
}
{ print escape($0) }
|
Produce a language-to-language conversion: from VB to AWK, same semantics. | Dim URL As String = "http://foo bar/"
URL = EncodeURLComponent(URL)
Print(URL)
| BEGIN {
for (i = 0; i <= 255; i++)
ord[sprintf("%c", i)] = i
}
function escape(str, c, len, res) {
len = length(str)
res = ""
for (i = 1; i <= len; i++) {
c = substr(str, i, 1);
if (c ~ /[0-9A-Za-z]/)
res = res c
else
res = res "%" sprintf("%02X", ord[c])
}
return res
}
{ print escape($0) }
|
Can you help me rewrite this code in AWK instead of VB, keeping it the same logically? | dim s(10)
print "Enter 11 numbers."
for i = 0 to 10
print i +1;
input " => "; s(i)
next i
print
for i = 10 to 0 step -1
print "f("; s(i); ") = ";
r = f(s(i))
if r > 400 then
print "-=< overflow >=-"
else
print r
end if
next i
end
function f(n)
f = sqr(abs(n)) + 5 * n * n * n
end function
|
BEGIN {
printf("enter 11 numbers: ")
getline S
n = split(S,arr," ")
if (n != 11) {
printf("%d numbers entered; S/B 11\n",n)
exit(1)
}
for (i=n; i>0; i--) {
x = f(arr[i])
printf("f(%s) = %s\n",arr[i],(x>400) ? "too large" : x)
}
exit(0)
}
function abs(x) { if (x >= 0) { return x } else { return -x } }
function f(x) { return sqrt(abs(x)) + 5 * x ^ 3 }
|
Ensure the translated AWK code behaves exactly like the original VB snippet. | for j = asc("a") to asc("z")
print chr(j);
next j
print
for j= asc("A") to Asc("Z")
print chr(j);
next j
end
|
BEGIN {
for (i=0; i<=255; i++) {
c = sprintf("%c",i)
if (c ~ /[[:lower:]]/) {
lower_chars = lower_chars c
}
if (c ~ /[[:upper:]]/) {
upper_chars = upper_chars c
}
}
printf("%s\n",ARGV[0])
printf("lowercase %d: %s\n",length(lower_chars),lower_chars)
printf("uppercase %d: %s\n",length(upper_chars),upper_chars)
exit(0)
}
|
Rewrite the snippet below in AWK so it works the same as the original VB code. | Option Explicit
Function JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double
Dim dummyChar, match1, match2 As String
Dim i, f, t, j, m, l, s1, s2, limit As Integer
i = 1
Do
dummyChar = Chr(i)
i = i + 1
Loop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0
s1 = Len(text1)
s2 = Len(text2)
limit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)
match1 = String(s1, dummyChar)
match2 = String(s2, dummyChar)
For l = 1 To WorksheetFunction.Min(4, s1, s2)
If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For
Next l
l = l - 1
For i = 1 To s1
f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)
t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)
j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)
If j > 0 Then
m = m + 1
text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)
match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)
match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)
End If
Next i
match1 = Replace(match1, dummyChar, "", 1, -1, vbTextCompare)
match2 = Replace(match2, dummyChar, "", 1, -1, vbTextCompare)
t = 0
For i = 1 To m
If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1
Next i
JaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3
JaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)
End Function
|
BEGIN {
main("DWAYNE","DUANE")
main("MARTHA","MARHTA")
main("DIXON","DICKSONX")
main("JELLYFISH","SMELLYFISH")
exit(0)
}
function main(str1,str2) {
printf("%9.7f '%s' '%s'\n",jaro(str1,str2),str1,str2)
}
function jaro(str1,str2, begin,end,i,j,k,leng1,leng2,match_distance,matches,str1_arr,str2_arr,transpositions) {
leng1 = length(str1)
leng2 = length(str2)
if (leng1 == 0 && leng2 == 0) {
return(1)
}
if (leng1 == 0 || leng2 == 0) {
return(0)
}
match_distance = int(max(leng1,leng2)/2-1)
for (i=1; i<=leng1; i++) {
begin = int(max(0,i-match_distance))
end = int(min(i+match_distance+1,leng2))
for (j=begin; j<=end; j++) {
if (str2_arr[j]) { continue }
if (substr(str1,i,1) != substr(str2,j,1)) { continue }
str1_arr[i] = 1
str2_arr[j] = 1
matches++
break
}
}
if (matches == 0) {
return(0)
}
k = 0
for (i=1; i<=leng1; i++) {
if (!str1_arr[i]) { continue }
while (!str2_arr[k]) {
k++
}
if (substr(str1,i,1) != substr(str2,k,1)) {
transpositions++
}
k++
}
transpositions /= 2
return((matches/leng1)+(matches/leng2)+((matches-transpositions)/matches))/3
}
function max(x,y) { return((x > y) ? x : y) }
function min(x,y) { return((x < y) ? x : y) }
|
Produce a functionally identical AWK code for the snippet given in VB. | Function IsSelfDescribing(n)
IsSelfDescribing = False
Set digit = CreateObject("Scripting.Dictionary")
For i = 1 To Len(n)
k = Mid(n,i,1)
If digit.Exists(k) Then
digit.Item(k) = digit.Item(k) + 1
Else
digit.Add k,1
End If
Next
c = 0
For j = 0 To Len(n)-1
l = Mid(n,j+1,1)
If digit.Exists(CStr(j)) Then
If digit.Item(CStr(j)) = CInt(l) Then
c = c + 1
End If
ElseIf l = 0 Then
c = c + 1
Else
Exit For
End If
Next
If c = Len(n) Then
IsSelfDescribing = True
End If
End Function
start_time = Now
s = ""
For m = 1 To 100000000
If IsSelfDescribing(m) Then
WScript.StdOut.WriteLine m
End If
Next
end_time = Now
WScript.StdOut.WriteLine "Elapse Time: " & DateDiff("s",start_time,end_time) & " seconds"
|
BEGIN {
for (n=1; n<=100000000; n++) {
if (is_self_describing(n)) {
print(n)
}
}
exit(0)
}
function is_self_describing(n, i) {
for (i=1; i<=length(n); i++) {
if (substr(n,i,1) != gsub(i-1,"&",n)) {
return(0)
}
}
return(1)
}
|
Ensure the translated AWK code behaves exactly like the original VB snippet. | Sub Main_Contain()
Dim ListeWords() As String, Book As String, i As Long, out() As String, count As Integer
Book = Read_File("C:\Users\" & Environ("Username") & "\Desktop\unixdict.txt")
ListeWords = Split(Book, vbNewLine)
For i = LBound(ListeWords) To UBound(ListeWords)
If Len(ListeWords(i)) > 11 Then
If InStr(ListeWords(i), "the") > 0 Then
ReDim Preserve out(count)
out(count) = ListeWords(i)
count = count + 1
End If
End If
Next
Debug.Print "Found : " & count & " words : " & Join(out, ", ")
End Sub
Private Function Read_File(Fic As String) As String
Dim Nb As Integer
Nb = FreeFile
Open Fic For Input As #Nb
Read_File = Input(LOF(Nb), #Nb)
Close #Nb
End Function
| /Code$ awk '/the/ && length($1) > 11' unixdict.txt
authenticate
chemotherapy
chrysanthemum
clothesbrush
clotheshorse
eratosthenes
featherbedding
featherbrain
featherweight
gaithersburg
hydrothermal
lighthearted
mathematician
neurasthenic
nevertheless
northeastern
northernmost
otherworldly
parasympathetic
physiotherapist
physiotherapy
psychotherapeutic
psychotherapist
psychotherapy
radiotherapy
southeastern
southernmost
theoretician
weatherbeaten
weatherproof
weatherstrip
weatherstripping
/Code$
|
Maintain the same structure and functionality when rewriting this code in AWK. | Public Sub Main()
For i As Integer = 1 To 500
If needs_af(i) Then Print i; " ";
Next
End
Function needs_af(n As Integer) As Boolean
While n > 0
If n Mod 16 > 9 Then Return True
n \= 16
Wend
Return False
End Function
|
BEGIN {
start = 1
stop = 500
for (i=start; i<=stop; i++) {
if (sprintf("%X",i) ~ /[A-F]/) {
printf("%4d%1s",i,++count%20?"":"\n")
}
}
printf("\nIntegers when displayed in hex require an A-F, %d-%d: %d\n",start,stop,count)
exit(0)
}
|
Write a version of this VB function in AWK with identical behavior. | Public Sub Main()
For i As Integer = 1 To 500
If needs_af(i) Then Print i; " ";
Next
End
Function needs_af(n As Integer) As Boolean
While n > 0
If n Mod 16 > 9 Then Return True
n \= 16
Wend
Return False
End Function
|
BEGIN {
start = 1
stop = 500
for (i=start; i<=stop; i++) {
if (sprintf("%X",i) ~ /[A-F]/) {
printf("%4d%1s",i,++count%20?"":"\n")
}
}
printf("\nIntegers when displayed in hex require an A-F, %d-%d: %d\n",start,stop,count)
exit(0)
}
|
Ensure the translated AWK code behaves exactly like the original VB snippet. | with createobject("ADODB.Stream")
.charset ="UTF-8"
.open
.loadfromfile("unixdict.txt")
s=.readtext
end with
a=split (s,vblf)
set d= createobject("Scripting.Dictionary")
for each aa in a
x=trim(aa)
l=len(x)
if l>5 then
d.removeall
for i=1 to 3
m=mid(x,i,1)
if not d.exists(m) then d.add m,null
next
res=true
for i=l-2 to l
m=mid(x,i,1)
if not d.exists(m) then
res=false:exit for
else
d.remove(m)
end if
next
if res then
wscript.stdout.write left(x & space(15),15)
if left(x,3)=right(x,3) then wscript.stdout.write "*"
wscript.stdout.writeline
end if
end if
next
|
(length($0) >= 6 && substr($0,1,3) == substr($0,length($0)-2,3))
END {
exit(0)
}
|
Rewrite the snippet below in AWK so it works the same as the original VB code. | with createobject("ADODB.Stream")
.charset ="UTF-8"
.open
.loadfromfile("unixdict.txt")
s=.readtext
end with
a=split (s,vblf)
dim b(25)
dim c(128)
with new regexp
.pattern="([^aeiou])"
.global=true
for each i in a
if len(trim(i))>10 then
set matches= .execute(i)
rep=false
for each m in matches
x=asc(m)
c(x)=c(x)+1
if c(x)>1 then rep=true :exit for
next
erase c
if not rep then
x1=matches.count
b(x1)=b(x1)&" "&i
end if
end if
next
end with
for i=25 to 0 step -1
if b(i)<>"" then wscript.echo i & " "& b(i) & vbcrlf
next
|
BEGIN {
a2z = "abcdefghijklmnopqrstuvwxyz"
gsub(/[aeiou]/,"",a2z)
leng = length(a2z)
}
{ if (length($0) <= 10) {
next
}
consonants = 0
for (i=1; i<=leng; i++) {
c = substr(a2z,i,1)
if (gsub(c,"&",$0) > 1) {
next
}
if (gsub(c,"&",$0) == 1) {
consonants++
}
}
arr[consonants][$0] = ""
words++
}
END {
show = 4
PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1
for (i in arr) {
printf("%1d %3d ",i,length(arr[i]))
shown = 0
for (j in arr[i]) {
if (++shown <= show) {
printf("%s ",j)
}
}
printf("%s\n",(length(arr[i])>show)?(" ... "j):"")
}
printf("%5d words\n",words)
exit(0)
}
|
Port the following code from VB to AWK with equivalent syntax and logic. | Function Multiply(a As Integer, b As Integer) As Integer
Return a * b
End Function
| function multiply(a, b)
{
return a*b
}
BEGIN {
print multiply(5, 6)
}
|
Please provide an equivalent version of this VB code in AWK. | Imports System.Text
Module Module1
Function Sieve(limit As Integer) As Integer()
Dim primes As New List(Of Integer) From {2}
Dim c(limit + 1) As Boolean REM composite = true
REM no need to process even numbers > 2
Dim p = 3
While True
Dim p2 = p * p
If p2 > limit Then
Exit While
End If
For i = p2 To limit Step 2 * p
c(i) = True
Next
Do
p += 2
Loop While c(p)
End While
For i = 3 To limit Step 2
If Not c(i) Then
primes.Add(i)
End If
Next
Return primes.ToArray
End Function
Function SuccessivePrimes(primes() As Integer, diffs() As Integer) As List(Of List(Of Integer))
Dim results As New List(Of List(Of Integer))
Dim dl = diffs.Length
Dim i = 0
While i < primes.Length - dl
Dim group(dl) As Integer
group(0) = primes(i)
Dim j = i
While j < i + dl
If primes(j + 1) - primes(j) <> diffs(j - i) Then
GoTo outer REM continue the outermost loop
End If
group(j - i + 1) = primes(j + 1)
j += 1
End While
results.Add(group.ToList)
outer:
i += 1
End While
Return results
End Function
Function CollectionToString(Of T)(c As IEnumerable(Of T)) As String
Dim builder As New StringBuilder
builder.Append("[")
Dim it = c.GetEnumerator()
If it.MoveNext() Then
builder.Append(it.Current)
End If
While it.MoveNext()
builder.Append(", ")
builder.Append(it.Current)
End While
builder.Append("]")
Return builder.ToString
End Function
Sub Main()
Dim primes = Sieve(999999)
Dim diffsList = {({2}), ({1}), ({2, 2}), ({2, 4}), ({4, 2}), ({6, 4, 2})}
Console.WriteLine("For primes less than 1,000,000:-")
Console.WriteLine()
For Each diffs In diffsList
Console.WriteLine(" For differences of {0} ->", CollectionToString(diffs))
Dim sp = SuccessivePrimes(primes, diffs)
If sp.Count = 0 Then
Console.WriteLine(" No groups found")
Continue For
End If
Console.WriteLine(" First group = {0}", CollectionToString(sp(0)))
Console.WriteLine(" Last group = {0}", CollectionToString(sp(sp.Count - 1)))
Console.WriteLine(" Number found = {0}", sp.Count)
Console.WriteLine()
Next
End Sub
End Module
|
BEGIN {
for (i=lo=0; i<=hi=1000000; i++) {
if (is_prime(i)) {
p_arr[++p] = i
}
}
printf("there are %d primes between %d - %d\n",p,lo,hi)
fmt = "%-11s %5s %-15s %s\n"
printf(fmt,"differences","count","first group","last group")
for (a=1; a<=split("2;1;2,2;2,4;4,2;6,4,2;2,4,6;100;112",diff_arr,";"); a++) {
diff_leng = split(diff_arr[a],tmp_arr,",")
first_set = last_set = ""
count = 0
for (b=1; b<=p; b++) {
str = ""
for (c=1; c<=diff_leng; c++) {
if (p_arr[b+c-1] + tmp_arr[c] == p_arr[b+c]) {
str = (str == "") ? (p_arr[b+c-1] "," p_arr[b+c]) : (str "," p_arr[b+c])
}
}
if (gsub(/,/,"&",str) == diff_leng) {
count++
if (first_set == "") {
first_set = str
}
last_set = str
}
}
printf(fmt,diff_arr[a],count,first_set,last_set)
}
exit(0)
}
function is_prime(x, i) {
if (x <= 1) {
return(0)
}
for (i=2; i<=int(sqrt(x)); i++) {
if (x % i == 0) {
return(0)
}
}
return(1)
}
|
Translate the given VB code snippet into AWK without altering its behavior. |
s=7*8*9
m=9876432
for i=(m\s)*s to 1 step -s
if instr(i,"5")=0 and instr(i,"0")=0 then
b=false: j=1
while j<=len(i)-1 and not b
if instr(j+1,i,mid(i,j,1))<>0 then b=true
j=j+1
wend
if not b then
j=1
while j<=len(i) and not b
if (i mod mid(i,j,1))<>0 then b=true
j=j+1
wend
if not b then exit for
end if
end if
next
wscript.echo i
|
BEGIN {
base = 10
comdiv = 12
startn = 9876543
stopn = 1000000
solve(startn, stopn)
}
function solve(startn, stopn, n, d) {
for (n = startn - startn % comdiv; n > stopn; n -= comdiv) {
if (hasuniqedigits(n)) {
for (d = 2; d < base; d++) {
if ((dcount[d]) && (n % d)) {
break
}
}
if (d == base) {
printf("%d\n", n)
return
}
}
}
}
function hasuniqedigits(n, d) {
for (d = 1; d < base; d++)
dcount[d] = 0
while (n) {
d = n % base
if ((d == 0) || (++dcount[d] > 1))
return 0
n = int(n / base)
}
return 1
}
|
Translate the given VB code snippet into AWK without altering its behavior. |
s=7*8*9
m=9876432
for i=(m\s)*s to 1 step -s
if instr(i,"5")=0 and instr(i,"0")=0 then
b=false: j=1
while j<=len(i)-1 and not b
if instr(j+1,i,mid(i,j,1))<>0 then b=true
j=j+1
wend
if not b then
j=1
while j<=len(i) and not b
if (i mod mid(i,j,1))<>0 then b=true
j=j+1
wend
if not b then exit for
end if
end if
next
wscript.echo i
|
BEGIN {
base = 10
comdiv = 12
startn = 9876543
stopn = 1000000
solve(startn, stopn)
}
function solve(startn, stopn, n, d) {
for (n = startn - startn % comdiv; n > stopn; n -= comdiv) {
if (hasuniqedigits(n)) {
for (d = 2; d < base; d++) {
if ((dcount[d]) && (n % d)) {
break
}
}
if (d == base) {
printf("%d\n", n)
return
}
}
}
}
function hasuniqedigits(n, d) {
for (d = 1; d < base; d++)
dcount[d] = 0
while (n) {
d = n % base
if ((d == 0) || (++dcount[d] > 1))
return 0
n = int(n / base)
}
return 1
}
|
Produce a functionally identical AWK code for the snippet given in VB. | Option Explicit
Dim objFSO, DBSource
Set objFSO = CreateObject("Scripting.FileSystemObject")
DBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\postal_address.accdb"
With CreateObject("ADODB.Connection")
.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBSource
.Execute "CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL," &_
"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)"
.Close
End With
|
awk '
BEGIN {
print "Creating table..."
dbExec("address.db", "create table address (street, city, state, zip);")
print "Done."
exit
}
function dbExec(db, qry, result) {
dbMakeQuery(db, qry) | getline result
dbErrorCheck(result)
}
function dbMakeQuery(db, qry, q) {
q = dbEscapeQuery(qry) ";"
return "echo \"" q "\" | sqlite3 " db
}
function dbEscapeQuery(qry, q) {
q = qry
gsub(/"/, "\\\"", q)
return q
}
function dbErrorCheck(res) {
if (res ~ "SQL error") {
print res
exit
}
}
'
|
Write the same algorithm in AWK as shown in this VB implementation. | Function IsPrime(x As Long) As Boolean
Dim i As Long
If x Mod 2 = 0 Then
Exit Function
Else
For i = 3 To Int(Sqr(x)) Step 2
If x Mod i = 0 Then Exit Function
Next i
End If
IsPrime = True
End Function
Function TwinPrimePairs(max As Long) As Long
Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long
p2 = True
For i = 5 To max Step 2
p1 = p2
p2 = IsPrime(i)
If p1 And p2 Then count = count + 1
Next i
TwinPrimePairs = count
End Function
Sub Test(x As Long)
Debug.Print "Twin prime pairs below" + Str(x) + ":" + Str(TwinPrimePairs(x))
End Sub
Sub Main()
Test 10
Test 100
Test 1000
Test 10000
Test 100000
Test 1000000
Test 10000000
End Sub
|
BEGIN {
n = 1
for (i=1; i<=6; i++) {
n *= 10
printf("twin prime pairs < %8s : %d\n",n,count_twin_primes(n))
}
exit(0)
}
function count_twin_primes(limit, count,i,p1,p2,p3) {
p1 = 0
p2 = p3 = 1
for (i=5; i<=limit; i++) {
p3 = p2
p2 = p1
p1 = is_prime(i)
if (p3 && p1) {
count++
}
}
return(count)
}
function is_prime(x, i) {
if (x <= 1) {
return(0)
}
for (i=2; i<=int(sqrt(x)); i++) {
if (x % i == 0) {
return(0)
}
}
return(1)
}
|
Convert this VB block to AWK, preserving its control flow and logic. | Module Module1
Function sameDigits(ByVal n As Integer, ByVal b As Integer) As Boolean
Dim f As Integer = n Mod b : n \= b : While n > 0
If n Mod b <> f Then Return False Else n \= b
End While : Return True
End Function
Function isBrazilian(ByVal n As Integer) As Boolean
If n < 7 Then Return False
If n Mod 2 = 0 Then Return True
For b As Integer = 2 To n - 2
If sameDigits(n, b) Then Return True
Next : Return False
End Function
Function isPrime(ByVal n As Integer) As Boolean
If n < 2 Then Return False
If n Mod 2 = 0 Then Return n = 2
If n Mod 3 = 0 Then Return n = 3
Dim d As Integer = 5
While d * d <= n
If n Mod d = 0 Then Return False Else d += 2
If n Mod d = 0 Then Return False Else d += 4
End While : Return True
End Function
Sub Main(args As String())
For Each kind As String In {" ", " odd ", " prime "}
Console.WriteLine("First 20{0}Brazilian numbers:", kind)
Dim Limit As Integer = 20, n As Integer = 7
Do
If isBrazilian(n) Then Console.Write("{0} ", n) : Limit -= 1
Select Case kind
Case " " : n += 1
Case " odd " : n += 2
Case " prime " : Do : n += 2 : Loop Until isPrime(n)
End Select
Loop While Limit > 0
Console.Write(vbLf & vbLf)
Next
End Sub
End Module
|
BEGIN {
split(",odd ,prime ",kinds,",")
for (i=1; i<=3; ++i) {
printf("first 20 %sBrazilian numbers:",kinds[i])
c = 0
n = 7
while (1) {
if (is_brazilian(n)) {
printf(" %d",n)
if (++c == 20) {
printf("\n")
break
}
}
switch (i) {
case 1:
n++
break
case 2:
n += 2
break
case 3:
do {
n += 2
} while (!is_prime(n))
break
}
}
}
exit(0)
}
function is_brazilian(n, b) {
if (n < 7) { return(0) }
if (!(n % 2) && n >= 8) { return(1) }
for (b=2; b<n-1; ++b) {
if (same_digits(n,b)) { return(1) }
}
return(0)
}
function is_prime(n, d) {
d = 5
if (n < 2) { return(0) }
if (!(n % 2)) { return(n == 2) }
if (!(n % 3)) { return(n == 3) }
while (d*d <= n) {
if (!(n % d)) { return(0) }
d += 2
if (!(n % d)) { return(0) }
d += 4
}
return(1)
}
function same_digits(n,b, f) {
f = n % b
n = int(n/b)
while (n > 0) {
if (n % b != f) { return(0) }
n = int(n/b)
}
return(1)
}
|
Convert the following code from VB to AWK, ensuring the logic remains intact. | Module Module1
Function sameDigits(ByVal n As Integer, ByVal b As Integer) As Boolean
Dim f As Integer = n Mod b : n \= b : While n > 0
If n Mod b <> f Then Return False Else n \= b
End While : Return True
End Function
Function isBrazilian(ByVal n As Integer) As Boolean
If n < 7 Then Return False
If n Mod 2 = 0 Then Return True
For b As Integer = 2 To n - 2
If sameDigits(n, b) Then Return True
Next : Return False
End Function
Function isPrime(ByVal n As Integer) As Boolean
If n < 2 Then Return False
If n Mod 2 = 0 Then Return n = 2
If n Mod 3 = 0 Then Return n = 3
Dim d As Integer = 5
While d * d <= n
If n Mod d = 0 Then Return False Else d += 2
If n Mod d = 0 Then Return False Else d += 4
End While : Return True
End Function
Sub Main(args As String())
For Each kind As String In {" ", " odd ", " prime "}
Console.WriteLine("First 20{0}Brazilian numbers:", kind)
Dim Limit As Integer = 20, n As Integer = 7
Do
If isBrazilian(n) Then Console.Write("{0} ", n) : Limit -= 1
Select Case kind
Case " " : n += 1
Case " odd " : n += 2
Case " prime " : Do : n += 2 : Loop Until isPrime(n)
End Select
Loop While Limit > 0
Console.Write(vbLf & vbLf)
Next
End Sub
End Module
|
BEGIN {
split(",odd ,prime ",kinds,",")
for (i=1; i<=3; ++i) {
printf("first 20 %sBrazilian numbers:",kinds[i])
c = 0
n = 7
while (1) {
if (is_brazilian(n)) {
printf(" %d",n)
if (++c == 20) {
printf("\n")
break
}
}
switch (i) {
case 1:
n++
break
case 2:
n += 2
break
case 3:
do {
n += 2
} while (!is_prime(n))
break
}
}
}
exit(0)
}
function is_brazilian(n, b) {
if (n < 7) { return(0) }
if (!(n % 2) && n >= 8) { return(1) }
for (b=2; b<n-1; ++b) {
if (same_digits(n,b)) { return(1) }
}
return(0)
}
function is_prime(n, d) {
d = 5
if (n < 2) { return(0) }
if (!(n % 2)) { return(n == 2) }
if (!(n % 3)) { return(n == 3) }
while (d*d <= n) {
if (!(n % d)) { return(0) }
d += 2
if (!(n % d)) { return(0) }
d += 4
}
return(1)
}
function same_digits(n,b, f) {
f = n % b
n = int(n/b)
while (n > 0) {
if (n % b != f) { return(0) }
n = int(n/b)
}
return(1)
}
|
Preserve the algorithm and functionality while converting the code from VB to AWK. |
nx=15
h=1000
Wscript.StdOut.WriteLine "Recaman
Wscript.StdOut.WriteLine recaman("seq",nx)
Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0)
Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h)
Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine()
function recaman(op,nn)
Dim b,d,h
Set b = CreateObject("Scripting.Dictionary")
Set d = CreateObject("Scripting.Dictionary")
list="0" : firstdup=0
if op="firstdup" then
nn=1000 : firstdup=1
end if
if op="numterm" then
h=nn : nn=10000000 : numterm=1
end if
ax=0
b.Add 0,1
s=0
for n=1 to nn-1
an=ax-n
if an<=0 then
an=ax+n
elseif b.Exists(an) then
an=ax+n
end if
ax=an
if not b.Exists(an) then b.Add an,1
if op="seq" then
list=list&" "&an
end if
if firstdup then
if d.Exists(an) then
recaman="a("&n&")="&an
exit function
else
d.Add an,1
end if
end if
if numterm then
if an<=h then
if not d.Exists(an) then
s=s+1
d.Add an,1
end if
if s>=h then
recaman=n
exit function
end if
end if
end if
next
recaman=list
end function
|
BEGIN {
found_dup = 0
n = -1
do {
n++
ap = a[n-1] + n
if (a[n-1] <= n) {
a[n] = ap
b[ap] = 1
}
else {
am = a[n-1] - n
if (b[am] == 1) {
a[n] = ap
b[ap] = 1
}
else {
a[n] = am
b[am] = 1
}
}
if (n <= 14) {
terms = sprintf("%s%s ",terms,a[n])
if (n == 14) {
printf("first %d terms: %s\n",n+1,terms)
}
}
if (!found_dup) {
if (dup[a[n]] == 1) {
printf("first duplicated term: a[%d]=%d\n",n,a[n])
found_dup = 1
}
dup[a[n]] = 1
}
if (a[n] <= 1000) {
arr[a[n]] = ""
}
} while (n <= 15 || !found_dup || length(arr) < 1001)
printf("terms needed to generate integers 0 - 1000: %d\n",n)
exit(0)
}
|
Change the following VB code into AWK without altering its purpose. |
nx=15
h=1000
Wscript.StdOut.WriteLine "Recaman
Wscript.StdOut.WriteLine recaman("seq",nx)
Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0)
Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h)
Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine()
function recaman(op,nn)
Dim b,d,h
Set b = CreateObject("Scripting.Dictionary")
Set d = CreateObject("Scripting.Dictionary")
list="0" : firstdup=0
if op="firstdup" then
nn=1000 : firstdup=1
end if
if op="numterm" then
h=nn : nn=10000000 : numterm=1
end if
ax=0
b.Add 0,1
s=0
for n=1 to nn-1
an=ax-n
if an<=0 then
an=ax+n
elseif b.Exists(an) then
an=ax+n
end if
ax=an
if not b.Exists(an) then b.Add an,1
if op="seq" then
list=list&" "&an
end if
if firstdup then
if d.Exists(an) then
recaman="a("&n&")="&an
exit function
else
d.Add an,1
end if
end if
if numterm then
if an<=h then
if not d.Exists(an) then
s=s+1
d.Add an,1
end if
if s>=h then
recaman=n
exit function
end if
end if
end if
next
recaman=list
end function
|
BEGIN {
found_dup = 0
n = -1
do {
n++
ap = a[n-1] + n
if (a[n-1] <= n) {
a[n] = ap
b[ap] = 1
}
else {
am = a[n-1] - n
if (b[am] == 1) {
a[n] = ap
b[ap] = 1
}
else {
a[n] = am
b[am] = 1
}
}
if (n <= 14) {
terms = sprintf("%s%s ",terms,a[n])
if (n == 14) {
printf("first %d terms: %s\n",n+1,terms)
}
}
if (!found_dup) {
if (dup[a[n]] == 1) {
printf("first duplicated term: a[%d]=%d\n",n,a[n])
found_dup = 1
}
dup[a[n]] = 1
}
if (a[n] <= 1000) {
arr[a[n]] = ""
}
} while (n <= 15 || !found_dup || length(arr) < 1001)
printf("terms needed to generate integers 0 - 1000: %d\n",n)
exit(0)
}
|
Write a version of this VB function in AWK with identical behavior. |
Dim fact()
nn1=9 : nn2=12
lim=1499999
ReDim fact(nn2)
fact(0)=1
For i=1 To nn2
fact(i)=fact(i-1)*i
Next
For base=nn1 To nn2
list=""
For i=1 To lim
s=0
t=i
Do While t<>0
d=t Mod base
s=s+fact(d)
t=t\base
Loop
If s=i Then list=list &" "& i
Next
Wscript.Echo "the factorions for base "& right(" "& base,2) &" are: "& list
Next
|
BEGIN {
fact[0] = 1
for (n=1; n<12; ++n) {
fact[n] = fact[n-1] * n
}
for (b=9; b<=12; ++b) {
printf("base %d factorions:",b)
for (i=1; i<1500000; ++i) {
sum = 0
j = i
while (j > 0) {
d = j % b
sum += fact[d]
j = int(j/b)
}
if (sum == i) {
printf(" %d",i)
}
}
printf("\n")
}
exit(0)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.