Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write a version of this Java function in Ruby with identical behavior. | import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class Eval {
private static final String CLASS_NAME = "TempPleaseDeleteMe";
private static class StringCompiler
extends SimpleJavaFileObject {
final String m_sourceCode;
private StringCompiler( final String sourceCode ) {
super( URI.create( "string:
m_sourceCode = sourceCode;
}
@Override
public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {
return m_sourceCode;
}
private boolean compile() {
final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
return javac.getTask( null, javac.getStandardFileManager( null, null, null ),
null, null, null, Arrays.asList( this )
).call();
}
private double callEval( final double x )
throws Exception {
final Class<?> clarse = Class.forName( CLASS_NAME );
final Method eval = clarse.getMethod( "eval", double.class );
return ( Double ) eval.invoke( null, x );
}
}
public static double evalWithX( final String code, final double x )
throws Exception {
final StringCompiler sc = new StringCompiler(
"class "
+ CLASS_NAME
+ "{public static double eval(double x){return ("
+ code
+ ");}}"
);
if ( ! sc.compile() ) throw new RuntimeException( "Compiler error" );
return sc.callEval( x );
}
public static void main( final String [] args )
throws Exception {
final String expression = args [ 0 ];
final double x1 = Double.parseDouble( args [ 1 ] );
final double x2 = Double.parseDouble( args [ 2 ] );
System.out.println(
evalWithX( expression, x1 )
- evalWithX( expression, x2 )
);
}
}
| def bind_x_to_value(x)
binding
end
def eval_with_x(code, a, b)
eval(code, bind_x_to_value(b)) - eval(code, bind_x_to_value(a))
end
puts eval_with_x('2 ** x', 3, 5)
|
Maintain the same structure and functionality when rewriting this code in Ruby. | public class ReallyLameTranslationOfJ {
public static void main(String[] args) {
String s = "She was a soul stripper. She took my heart!";
System.out.println(cheapTrick(s));
System.out.println(cheapTrick(cheapTrick(s)));
}
static String cheapTrick(String s) {
if (s.contains("She"))
return s.replaceAll("She", "He");
else if(s.contains("He"))
return s.replaceAll("He", "She");
return s;
}
}
| var male2female = <<'EOD'
maleS femaleS, maleness femaleness, him her, himself herself, his her, his
hers, he she, Mr Mrs, Mister Missus, Ms Mr, Master Miss, MasterS MistressES,
uncleS auntS, nephewS nieceS, sonS daughterS, grandsonS granddaughterS,
brotherS sisterS, man woman, men women, boyS girlS, paternal maternal,
grandfatherS grandmotherS, GodfatherS GodmotherS, GodsonS GoddaughterS,
fiancéS fiancéeS, husband wife, husbands wives, fatherS motherS, bachelorS
spinsterS, bridegroomS brideS, widowerS widowS, KnightS DameS, Sir DameS,
KingS QueenS, DukeS DuchessES, PrinceS PrincessES, Lord Lady, Lords Ladies,
MarquessES MarchionessES, EarlS CountessES, ViscountS ViscountessES, ladS
lassES, sir madam, gentleman lady, gentlemen ladies, BaronS BaronessES,
stallionS mareS, ramS eweS, coltS fillieS, billy nanny, billies nannies,
bullS cowS, godS goddessES, heroS heroineS, shirtS blouseS, undies nickers,
sweat glow, jackarooS jillarooS, gigoloS hookerS, landlord landlady,
landlords landladies, manservantS maidservantS, actorS actressES, CountS
CountessES, EmperorS EmpressES, giantS giantessES, heirS heiressES, hostS
hostessES, lionS lionessES, managerS manageressES, murdererS murderessES,
priestS priestessES, poetS poetessES, shepherdS shepherdessES, stewardS
stewardessES, tigerS tigressES, waiterS waitressES, cockS henS, dogS bitchES,
drakeS henS, dogS vixenS, tomS tibS, boarS sowS, buckS roeS, peacockS
peahenS, gander goose, ganders geese, friarS nunS, monkS nunS
EOD
var m2f = male2female.split(/,\s*/).map { |tok| tok.words}
var re_plural = /E?S\z/
var re_ES = /ES\z/
func gen_pluralize(m, f) {
[
[m - re_plural, f - re_plural],
[m.sub(re_ES, 'es'), f.sub(re_ES, 'es')],
[m.sub(re_plural, 's'), f.sub(re_plural, 's')],
]
}
var dict = Hash()
for m,f in m2f {
for x,y in gen_pluralize(m, f).map{.map{.lc}} {
if (x ~~ dict) {
dict{y} = x
} else {
dict{x, y} = (y, x)
}
}
}
var gen_re = Regex.new('\b(' + dict.keys.join('|') + ')\b', 'i')
func copy_case(orig, repl) {
var a = orig.chars
var b = repl.chars
var uc = 0
var min = [a, b].map{.len}.min
for i in ^min {
if (a[i] ~~ /^[[:upper:]]/) {
b[i].uc!
++uc
}
}
uc == min ? repl.uc : b.join('')
}
func reverse_gender(text) {
text.gsub(gen_re, { |a| copy_case(a, dict{a.lc}) })
}
|
Write the same code in Ruby as shown below in Java. | public class ReallyLameTranslationOfJ {
public static void main(String[] args) {
String s = "She was a soul stripper. She took my heart!";
System.out.println(cheapTrick(s));
System.out.println(cheapTrick(cheapTrick(s)));
}
static String cheapTrick(String s) {
if (s.contains("She"))
return s.replaceAll("She", "He");
else if(s.contains("He"))
return s.replaceAll("He", "She");
return s;
}
}
| var male2female = <<'EOD'
maleS femaleS, maleness femaleness, him her, himself herself, his her, his
hers, he she, Mr Mrs, Mister Missus, Ms Mr, Master Miss, MasterS MistressES,
uncleS auntS, nephewS nieceS, sonS daughterS, grandsonS granddaughterS,
brotherS sisterS, man woman, men women, boyS girlS, paternal maternal,
grandfatherS grandmotherS, GodfatherS GodmotherS, GodsonS GoddaughterS,
fiancéS fiancéeS, husband wife, husbands wives, fatherS motherS, bachelorS
spinsterS, bridegroomS brideS, widowerS widowS, KnightS DameS, Sir DameS,
KingS QueenS, DukeS DuchessES, PrinceS PrincessES, Lord Lady, Lords Ladies,
MarquessES MarchionessES, EarlS CountessES, ViscountS ViscountessES, ladS
lassES, sir madam, gentleman lady, gentlemen ladies, BaronS BaronessES,
stallionS mareS, ramS eweS, coltS fillieS, billy nanny, billies nannies,
bullS cowS, godS goddessES, heroS heroineS, shirtS blouseS, undies nickers,
sweat glow, jackarooS jillarooS, gigoloS hookerS, landlord landlady,
landlords landladies, manservantS maidservantS, actorS actressES, CountS
CountessES, EmperorS EmpressES, giantS giantessES, heirS heiressES, hostS
hostessES, lionS lionessES, managerS manageressES, murdererS murderessES,
priestS priestessES, poetS poetessES, shepherdS shepherdessES, stewardS
stewardessES, tigerS tigressES, waiterS waitressES, cockS henS, dogS bitchES,
drakeS henS, dogS vixenS, tomS tibS, boarS sowS, buckS roeS, peacockS
peahenS, gander goose, ganders geese, friarS nunS, monkS nunS
EOD
var m2f = male2female.split(/,\s*/).map { |tok| tok.words}
var re_plural = /E?S\z/
var re_ES = /ES\z/
func gen_pluralize(m, f) {
[
[m - re_plural, f - re_plural],
[m.sub(re_ES, 'es'), f.sub(re_ES, 'es')],
[m.sub(re_plural, 's'), f.sub(re_plural, 's')],
]
}
var dict = Hash()
for m,f in m2f {
for x,y in gen_pluralize(m, f).map{.map{.lc}} {
if (x ~~ dict) {
dict{y} = x
} else {
dict{x, y} = (y, x)
}
}
}
var gen_re = Regex.new('\b(' + dict.keys.join('|') + ')\b', 'i')
func copy_case(orig, repl) {
var a = orig.chars
var b = repl.chars
var uc = 0
var min = [a, b].map{.len}.min
for i in ^min {
if (a[i] ~~ /^[[:upper:]]/) {
b[i].uc!
++uc
}
}
uc == min ? repl.uc : b.join('')
}
func reverse_gender(text) {
text.gsub(gen_re, { |a| copy_case(a, dict{a.lc}) })
}
|
Change the following Java code into Ruby without altering its purpose. | import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
public class Evaluator{
public static void main(String[] args){
new Evaluator().eval(
"SayHello",
"public class SayHello{public void speak(){System.out.println(\"Hello world\");}}",
"speak"
);
}
void eval(String className, String classCode, String methodName){
Map<String, ByteArrayOutputStream> classCache = new HashMap<>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if ( null == compiler )
throw new RuntimeException("Could not get a compiler.");
StandardJavaFileManager sfm = compiler.getStandardFileManager(null, null, null);
ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)
throws IOException{
if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)
return new SimpleJavaFileObject(URI.create("mem:
@Override
public OutputStream openOutputStream()
throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
classCache.put(className, baos);
return baos;
}
};
else
throw new IllegalArgumentException("Unexpected output file requested: " + location + ", " + className + ", " + kind);
}
};
List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{
add(
new SimpleJavaFileObject(URI.create("string:
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors){
return classCode;
}
}
);
}};
compiler.getTask(null, fjfm, null, null, null, files).call();
try{
Class<?> clarse = new ClassLoader(){
@Override
public Class<?> findClass(String name){
if (! name.startsWith(className))
throw new IllegalArgumentException("This class loader is for " + className + " - could not handle \"" + name + '"');
byte[] bytes = classCache.get(name).toByteArray();
return defineClass(name, bytes, 0, bytes.length);
}
}.loadClass(className);
clarse.getMethod(methodName).invoke(clarse.newInstance());
}catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){
throw new RuntimeException("Run failed: " + x, x);
}
}
}
| a, b = 5, -7
ans = eval "(a * b).abs"
|
Change the programming language of this snippet from Java to Ruby without modifying what it does. | import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
public class Evaluator{
public static void main(String[] args){
new Evaluator().eval(
"SayHello",
"public class SayHello{public void speak(){System.out.println(\"Hello world\");}}",
"speak"
);
}
void eval(String className, String classCode, String methodName){
Map<String, ByteArrayOutputStream> classCache = new HashMap<>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if ( null == compiler )
throw new RuntimeException("Could not get a compiler.");
StandardJavaFileManager sfm = compiler.getStandardFileManager(null, null, null);
ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)
throws IOException{
if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)
return new SimpleJavaFileObject(URI.create("mem:
@Override
public OutputStream openOutputStream()
throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
classCache.put(className, baos);
return baos;
}
};
else
throw new IllegalArgumentException("Unexpected output file requested: " + location + ", " + className + ", " + kind);
}
};
List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{
add(
new SimpleJavaFileObject(URI.create("string:
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors){
return classCode;
}
}
);
}};
compiler.getTask(null, fjfm, null, null, null, files).call();
try{
Class<?> clarse = new ClassLoader(){
@Override
public Class<?> findClass(String name){
if (! name.startsWith(className))
throw new IllegalArgumentException("This class loader is for " + className + " - could not handle \"" + name + '"');
byte[] bytes = classCache.get(name).toByteArray();
return defineClass(name, bytes, 0, bytes.length);
}
}.loadClass(className);
clarse.getMethod(methodName).invoke(clarse.newInstance());
}catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){
throw new RuntimeException("Run failed: " + x, x);
}
}
}
| a, b = 5, -7
ans = eval "(a * b).abs"
|
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version. | import java.math.BigInteger;
import static java.util.Arrays.stream;
import java.util.*;
import static java.util.stream.Collectors.*;
public class Test3 {
static BigInteger rank(int[] x) {
String s = stream(x).mapToObj(String::valueOf).collect(joining("F"));
return new BigInteger(s, 16);
}
static List<BigInteger> unrank(BigInteger n) {
BigInteger sixteen = BigInteger.valueOf(16);
String s = "";
while (!n.equals(BigInteger.ZERO)) {
s = "0123456789ABCDEF".charAt(n.mod(sixteen).intValue()) + s;
n = n.divide(sixteen);
}
return stream(s.split("F")).map(x -> new BigInteger(x)).collect(toList());
}
public static void main(String[] args) {
int[] s = {1, 2, 3, 10, 100, 987654321};
System.out.println(Arrays.toString(s));
System.out.println(rank(s));
System.out.println(unrank(rank(s)));
}
}
| def rank(arr)
arr.join('a').to_i(11)
end
def unrank(n)
n.to_s(11).split('a').map(&:to_i)
end
l = [1, 2, 3, 10, 100, 987654321]
p l
n = rank(l)
p n
l = unrank(n)
p l
|
Preserve the algorithm and functionality while converting the code from Java to Ruby. | import java.util.*;
public class RandomShuffle {
public static void main(String[] args) {
Random rand = new Random();
List<Integer> list = new ArrayList<>();
for (int j = 1; j <= 20; ++j)
list.add(j);
Collections.shuffle(list, rand);
System.out.println(list);
}
}
| nums = (1..20).to_a
5.times{ puts nums.shuffle.join(" ") }
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws IOException {
final int endOfFile = -1;
try ( FileReader reader = new FileReader("input.txt", StandardCharsets.UTF_8) ) {
while ( true ) {
int ch = reader.read();
if ( ch == endOfFile ) {
break;
}
System.out.print(Character.toChars(ch));
}
}
}
}
| File.open("input.txt") do |file|
file.each_char { |c| p c }
end
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | import java.util.Random;
import java.util.List;
import java.util.ArrayList;
public class GaltonBox {
public static void main( final String[] args ) {
new GaltonBox( 8, 200 ).run();
}
private final int m_pinRows;
private final int m_startRow;
private final Position[] m_balls;
private final Random m_random = new Random();
public GaltonBox( final int pinRows, final int ballCount ) {
m_pinRows = pinRows;
m_startRow = pinRows + 1;
m_balls = new Position[ ballCount ];
for ( int ball = 0; ball < ballCount; ball++ )
m_balls[ ball ] = new Position( m_startRow, 0, 'o' );
}
private static class Position {
int m_row;
int m_col;
char m_char;
Position( final int row, final int col, final char ch ) {
m_row = row;
m_col = col;
m_char = ch;
}
}
public void run() {
for ( int ballsInPlay = m_balls.length; ballsInPlay > 0; ) {
ballsInPlay = dropBalls();
print();
}
}
private int dropBalls() {
int ballsInPlay = 0;
int ballToStart = -1;
for ( int ball = 0; ball < m_balls.length; ball++ )
if ( m_balls[ ball ].m_row == m_startRow )
ballToStart = ball;
for ( int ball = 0; ball < m_balls.length; ball++ )
if ( ball == ballToStart ) {
m_balls[ ball ].m_row = m_pinRows;
ballsInPlay++;
}
else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) {
m_balls[ ball ].m_row -= 1;
m_balls[ ball ].m_col += m_random.nextInt( 2 );
if ( 0 != m_balls[ ball ].m_row )
ballsInPlay++;
}
return ballsInPlay;
}
private void print() {
for ( int row = m_startRow; row --> 1; ) {
for ( int ball = 0; ball < m_balls.length; ball++ )
if ( m_balls[ ball ].m_row == row )
printBall( m_balls[ ball ] );
System.out.println();
printPins( row );
}
printCollectors();
System.out.println();
}
private static void printBall( final Position pos ) {
for ( int col = pos.m_row + 1; col --> 0; )
System.out.print( ' ' );
for ( int col = 0; col < pos.m_col; col++ )
System.out.print( " " );
System.out.print( pos.m_char );
}
private void printPins( final int row ) {
for ( int col = row + 1; col --> 0; )
System.out.print( ' ' );
for ( int col = m_startRow - row; col --> 0; )
System.out.print( ". " );
System.out.println();
}
private void printCollectors() {
final List<List<Position>> collectors = new ArrayList<List<Position>>();
for ( int col = 0; col < m_startRow; col++ ) {
final List<Position> collector = new ArrayList<Position>();
collectors.add( collector );
for ( int ball = 0; ball < m_balls.length; ball++ )
if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col )
collector.add( m_balls[ ball ] );
}
for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) {
for ( int col = 0; col < m_startRow; col++ ) {
final List<Position> collector = collectors.get( col );
final int pos = row + collector.size() - rows;
System.out.print( '|' );
if ( pos >= 0 )
System.out.print( collector.get( pos ).m_char );
else
System.out.print( ' ' );
}
System.out.println( '|' );
}
}
private static final int longest( final List<List<Position>> collectors ) {
int result = 0;
for ( final List<Position> collector : collectors )
result = Math.max( collector.size(), result );
return result;
}
}
| $rows_of_pins = 12
$width = $rows_of_pins * 10 + ($rows_of_pins+1)*14
Shoes.app(
:width => $width + 14,
:title => "Galton Box"
) do
@bins = Array.new($rows_of_pins+1, 0)
@x_coords = Array.new($rows_of_pins) {Array.new}
@y_coords = Array.new($rows_of_pins)
stack(:width => $width) do
stroke gray
fill gray
1.upto($rows_of_pins) do |row|
y = 14 + 24*row
@y_coords[row-1] = y
row.times do |i|
x = $width / 2 + (i - 0.5*row)*24 + 14
@x_coords[row-1] << x
oval x+2, y, 6
end
end
end
@y_coords << @y_coords[-1] + 24
@x_coords << @x_coords[-1].map {|x| x-12} + [@x_coords[-1][-1]+12]
@balls = stack(:width => $width) do
stroke red
fill red
end.move(0,0)
@histogram = stack(:width => $width) do
nostroke
fill black
end.move(0, @y_coords[-1] + 10)
@paused = false
keypress do |key|
case key
when "\x11", :control_q
exit
when "\x10", :control_p
@paused = !@paused
end
end
@ball_row = 0
@ball_col = 0
animate(2*$rows_of_pins) do
if not @paused
y = @y_coords[@ball_row] - 12
x = @x_coords[@ball_row][@ball_col]
@balls.clear {oval x, y, 10}
@ball_row += 1
if @ball_row <= $rows_of_pins
@ball_col += 1 if rand >= 0.5
else
@bins[@ball_col] += 1
@ball_row = @ball_col = 0
update_histogram
end
end
end
def update_histogram
y = @y_coords[-1] + 10
@histogram.clear do
@bins.each_with_index do |num, i|
if num > 0
x = @x_coords[-1][i]
rect x-6, 0, 24, num
end
end
end
end
end
|
Produce a functionally identical Ruby code for the snippet given in Java. | import java.io.*;
import java.util.*;
public class PrimeDescendants {
public static void main(String[] args) {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) {
printPrimeDesc(writer, 100);
} catch (IOException ex) {
ex.printStackTrace();
}
}
private static void printPrimeDesc(Writer writer, int limit) throws IOException {
List<Long> primes = findPrimes(limit);
List<Long> ancestor = new ArrayList<>(limit);
List<List<Long>> descendants = new ArrayList<>(limit);
for (int i = 0; i < limit; ++i) {
ancestor.add(Long.valueOf(0));
descendants.add(new ArrayList<Long>());
}
for (Long prime : primes) {
int p = prime.intValue();
descendants.get(p).add(prime);
for (int i = 0; i + p < limit; ++i) {
int s = i + p;
for (Long n : descendants.get(i)) {
Long prod = n * p;
descendants.get(s).add(prod);
if (prod < limit)
ancestor.set(prod.intValue(), Long.valueOf(s));
}
}
}
int totalDescendants = 0;
for (int i = 1; i < limit; ++i) {
List<Long> ancestors = getAncestors(ancestor, i);
writer.write("[" + i + "] Level: " + ancestors.size() + "\n");
writer.write("Ancestors: ");
Collections.sort(ancestors);
print(writer, ancestors);
writer.write("Descendants: ");
List<Long> desc = descendants.get(i);
if (!desc.isEmpty()) {
Collections.sort(desc);
if (desc.get(0) == i)
desc.remove(0);
}
writer.write(desc.size() + "\n");
totalDescendants += desc.size();
if (!desc.isEmpty())
print(writer, desc);
writer.write("\n");
}
writer.write("Total descendants: " + totalDescendants + "\n");
}
private static List<Long> findPrimes(int limit) {
boolean[] isprime = new boolean[limit];
Arrays.fill(isprime, true);
isprime[0] = isprime[1] = false;
for (int p = 2; p * p < limit; ++p) {
if (isprime[p]) {
for (int i = p * p; i < limit; i += p)
isprime[i] = false;
}
}
List<Long> primes = new ArrayList<>();
for (int p = 2; p < limit; ++p) {
if (isprime[p])
primes.add(Long.valueOf(p));
}
return primes;
}
private static List<Long> getAncestors(List<Long> ancestor, int n) {
List<Long> result = new ArrayList<>();
for (Long a = ancestor.get(n); a != 0 && a != n; ) {
n = a.intValue();
a = ancestor.get(n);
result.add(Long.valueOf(n));
}
return result;
}
private static void print(Writer writer, List<Long> list) throws IOException {
if (list.isEmpty()) {
writer.write("none\n");
return;
}
int i = 0;
writer.write(String.valueOf(list.get(i++)));
for (; i != list.size(); ++i)
writer.write(", " + list.get(i));
writer.write("\n");
}
}
| var maxsum = 99
var primes = maxsum.primes
var descendants = (maxsum+1).of { [] }
var ancestors = (maxsum+1).of { [] }
for p in (primes) {
descendants[p] << p
for s in (1 .. descendants.end-p) {
descendants[s + p] << descendants[s].map {|q| p*q }...
}
}
for p in (primes + [4]) {
descendants[p].pop
}
var total = 0
for s in (1 .. maxsum) {
descendants[s].sort!
total += (var dsclen = descendants[s].len)
var idx = descendants[s].first_index {|x| x > maxsum }
for d in (descendants[s].slice(0, idx)) {
ancestors[d] = (ancestors[s] + [s])
}
if ((s <= 20) || (s ~~ [46, 74, 99])) {
printf("%2d: %d Ancestor(s): %-15s %5s Descendant(s): %s\n", s,
ancestors[s].len, "[
dsclen <= 10 ? descendants[s] : "[
}
}
say "\nTotal descendants:
|
Convert this Java block to Ruby, preserving its control flow and logic. | import java.util.Arrays;
public class CircleSort {
public static void main(String[] args) {
circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1});
}
public static void circleSort(int[] arr) {
if (arr.length > 0)
do {
System.out.println(Arrays.toString(arr));
} while (circleSortR(arr, 0, arr.length - 1, 0) != 0);
}
private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) {
if (lo == hi)
return numSwaps;
int high = hi;
int low = lo;
int mid = (hi - lo) / 2;
while (lo < hi) {
if (arr[lo] > arr[hi]) {
swap(arr, lo, hi);
numSwaps++;
}
lo++;
hi--;
}
if (lo == hi && arr[lo] > arr[hi + 1]) {
swap(arr, lo, hi + 1);
numSwaps++;
}
numSwaps = circleSortR(arr, low, low + mid, numSwaps);
numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps);
return numSwaps;
}
private static void swap(int[] arr, int idx1, int idx2) {
int tmp = arr[idx1];
arr[idx1] = arr[idx2];
arr[idx2] = tmp;
}
}
| class Array
def circle_sort!
while _circle_sort!(0, size-1) > 0
end
self
end
private
def _circle_sort!(lo, hi, swaps=0)
return swaps if lo == hi
low, high = lo, hi
mid = (lo + hi) / 2
while lo < hi
if self[lo] > self[hi]
self[lo], self[hi] = self[hi], self[lo]
swaps += 1
end
lo += 1
hi -= 1
end
if lo == hi && self[lo] > self[hi+1]
self[lo], self[hi+1] = self[hi+1], self[lo]
swaps += 1
end
swaps + _circle_sort!(low, mid) + _circle_sort!(mid+1, high)
end
end
ary = [6, 7, 8, 9, 2, 5, 3, 4, 1]
puts "before sort:
puts " after sort:
|
Change the following Java code into Ruby without altering its purpose. | public class BraceExpansion {
public static void main(String[] args) {
for (String s : new String[]{"It{{em,alic}iz,erat}e{d,}, please.",
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
"{,{,gotta have{ ,\\, again\\, }}more }cowbell!",
"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"}) {
System.out.println();
expand(s);
}
}
public static void expand(String s) {
expandR("", s, "");
}
private static void expandR(String pre, String s, String suf) {
int i1 = -1, i2 = 0;
String noEscape = s.replaceAll("([\\\\]{2}|[\\\\][,}{])", " ");
StringBuilder sb = null;
outer:
while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {
i2 = i1 + 1;
sb = new StringBuilder(s);
for (int depth = 1; i2 < s.length() && depth > 0; i2++) {
char c = noEscape.charAt(i2);
depth = (c == '{') ? ++depth : depth;
depth = (c == '}') ? --depth : depth;
if (c == ',' && depth == 1) {
sb.setCharAt(i2, '\u0000');
} else if (c == '}' && depth == 0 && sb.indexOf("\u0000") != -1)
break outer;
}
}
if (i1 == -1) {
if (suf.length() > 0)
expandR(pre + s, suf, "");
else
System.out.printf("%s%s%s%n", pre, s, suf);
} else {
for (String m : sb.substring(i1 + 1, i2).split("\u0000", -1))
expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);
}
}
}
| def getitem(s, depth=0)
out = [""]
until s.empty?
c = s[0]
break if depth>0 and (c == ',' or c == '}')
if c == '{' and x = getgroup(s[1..-1], depth+1)
out = out.product(x[0]).map{|a,b| a+b}
s = x[1]
else
s, c = s[1..-1], c + s[1] if c == '\\' and s.size > 1
out, s = out.map{|a| a+c}, s[1..-1]
end
end
return out, s
end
def getgroup(s, depth)
out, comma = [], false
until s.empty?
g, s = getitem(s, depth)
break if s.empty?
out += g
case s[0]
when '}' then return (comma ? out : out.map{|a| "{
when ',' then comma, s = true, s[1..-1]
end
end
end
strs = <<'EOS'
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
EOS
strs.each_line do |s|
puts s.chomp!
puts getitem(s)[0].map{|str| "\t"+str}
puts
end
|
Port the following code from Java to Ruby with equivalent syntax and logic. | package intersectingNumberWheels;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
public class WheelController {
private static final String IS_NUMBER = "[0-9]";
private static final int TWENTY = 20;
private static Map<String, WheelModel> wheelMap;
public static void advance(String wheel) {
WheelModel w = wheelMap.get(wheel);
if (w.list.get(w.position).matches(IS_NUMBER)) {
w.printThePosition();
w.advanceThePosition();
} else {
String wheelName = w.list.get(w.position);
advance(wheelName);
w.advanceThePosition();
}
}
public static void run() {
System.out.println(wheelMap);
IntStream.rangeClosed(1, TWENTY).forEach(i -> advance("A"));
System.out.println();
wheelMap.clear();
}
public static void main(String[] args) {
wheelMap = new HashMap<>();
wheelMap.put("A", new WheelModel("A", "1", "2", "3"));
run();
wheelMap.put("A", new WheelModel("A", "1", "B", "2"));
wheelMap.put("B", new WheelModel("B", "3", "4"));
run();
wheelMap.put("A", new WheelModel("A", "1", "D", "D"));
wheelMap.put("D", new WheelModel("D", "6", "7", "8"));
run();
wheelMap.put("A", new WheelModel("A", "1", "B", "C"));
wheelMap.put("B", new WheelModel("B", "3", "4"));
wheelMap.put("C", new WheelModel("C", "5", "B"));
run();
}
}
class WheelModel {
String name;
List<String> list;
int position;
int endPosition;
private static final int INITIAL = 0;
public WheelModel(String name, String... values) {
super();
this.name = name.toUpperCase();
this.list = new ArrayList<>();
for (String value : values) {
list.add(value);
}
this.position = INITIAL;
this.endPosition = this.list.size() - 1;
}
@Override
public String toString() {
return list.toString();
}
public void advanceThePosition() {
if (this.position == this.endPosition) {
this.position = INITIAL;
} else {
this.position++;
}
}
public void printThePosition() {
System.out.print(" " + this.list.get(position));
}
}
| groups = [{A: [1, 2, 3]},
{A: [1, :B, 2], B: [3, 4]},
{A: [1, :D, :D], D: [6, 7, 8]},
{A: [1, :B, :C], B: [3, 4], C: [5, :B]} ]
groups.each do |group|
p group
wheels = group.transform_values(&:cycle)
res = 20.times.map do
el = wheels[:A].next
el = wheels[el].next until el.is_a?(Integer)
el
end
puts res.join(" "),""
end
|
Change the programming language of this snippet from Java to Ruby without modifying what it does. | package intersectingNumberWheels;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
public class WheelController {
private static final String IS_NUMBER = "[0-9]";
private static final int TWENTY = 20;
private static Map<String, WheelModel> wheelMap;
public static void advance(String wheel) {
WheelModel w = wheelMap.get(wheel);
if (w.list.get(w.position).matches(IS_NUMBER)) {
w.printThePosition();
w.advanceThePosition();
} else {
String wheelName = w.list.get(w.position);
advance(wheelName);
w.advanceThePosition();
}
}
public static void run() {
System.out.println(wheelMap);
IntStream.rangeClosed(1, TWENTY).forEach(i -> advance("A"));
System.out.println();
wheelMap.clear();
}
public static void main(String[] args) {
wheelMap = new HashMap<>();
wheelMap.put("A", new WheelModel("A", "1", "2", "3"));
run();
wheelMap.put("A", new WheelModel("A", "1", "B", "2"));
wheelMap.put("B", new WheelModel("B", "3", "4"));
run();
wheelMap.put("A", new WheelModel("A", "1", "D", "D"));
wheelMap.put("D", new WheelModel("D", "6", "7", "8"));
run();
wheelMap.put("A", new WheelModel("A", "1", "B", "C"));
wheelMap.put("B", new WheelModel("B", "3", "4"));
wheelMap.put("C", new WheelModel("C", "5", "B"));
run();
}
}
class WheelModel {
String name;
List<String> list;
int position;
int endPosition;
private static final int INITIAL = 0;
public WheelModel(String name, String... values) {
super();
this.name = name.toUpperCase();
this.list = new ArrayList<>();
for (String value : values) {
list.add(value);
}
this.position = INITIAL;
this.endPosition = this.list.size() - 1;
}
@Override
public String toString() {
return list.toString();
}
public void advanceThePosition() {
if (this.position == this.endPosition) {
this.position = INITIAL;
} else {
this.position++;
}
}
public void printThePosition() {
System.out.print(" " + this.list.get(position));
}
}
| groups = [{A: [1, 2, 3]},
{A: [1, :B, 2], B: [3, 4]},
{A: [1, :D, :D], D: [6, 7, 8]},
{A: [1, :B, :C], B: [3, 4], C: [5, :B]} ]
groups.each do |group|
p group
wheels = group.transform_values(&:cycle)
res = 20.times.map do
el = wheels[:A].next
el = wheels[el].next until el.is_a?(Integer)
el
end
puts res.join(" "),""
end
|
Convert this Java snippet to Ruby and keep its semantics consistent. | public static Color getColorAt(int x, int y){
return new Robot().getPixelColor(x, y);
}
| module Screen
IMPORT_COMMAND = '/usr/bin/import'
def self.pixel(x, y)
if m = `
m[1..3].map(&:to_i)
else
false
end
end
end
|
Generate an equivalent Ruby version of this Java code. | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class YahooSearch {
private String query;
private int page = 1;
private static final Pattern pattern = Pattern.compile(
"<a class=\"yschttl spt\" href=\"[^*]+?\\*\\*([^\"]+?)\">(.+?)</a></h3>.*?<div class=\"(?:sm-abs|abstr)\">(.+?)</div>");
public YahooSearch(String query) {
this.query = query;
}
public List<YahooResult> search() throws MalformedURLException, URISyntaxException, IOException {
StringBuilder searchUrl = new StringBuilder("http:
searchUrl.append("p=").append(URLEncoder.encode(query, "UTF-8"));
if (page > 1) {searchUrl.append("&b=").append((page - 1) * 10 + 1);}
URL url = new URL(searchUrl.toString());
List<YahooResult> result = new ArrayList<YahooResult>();
StringBuilder sb = new StringBuilder();
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(url.openStream()));
String line = in.readLine();
while (line != null) {
sb.append(line);
line = in.readLine();
}
}
catch (IOException ioe) {
ioe.printStackTrace();
}
finally {
try {in.close();} catch (Exception ignoreMe) {}
}
String searchResult = sb.toString();
Matcher matcher = pattern.matcher(searchResult);
while (matcher.find()) {
String resultUrl = URLDecoder.decode(matcher.group(1), "UTF-8");
String resultTitle = matcher.group(2).replaceAll("</?b>", "").replaceAll("<wbr ?/?>", "");
String resultContent = matcher.group(3).replaceAll("</?b>", "").replaceAll("<wbr ?/?>", "");
result.add(new YahooResult(resultUrl, resultTitle, resultContent));
}
return result;
}
public List<YahooResult> search(int page) throws MalformedURLException, URISyntaxException, IOException {
this.page = page;
return search();
}
public List<YahooResult> nextPage() throws MalformedURLException, URISyntaxException, IOException {
page++;
return search();
}
public List<YahooResult> previousPage() throws MalformedURLException, URISyntaxException, IOException {
if (page > 1) {
page--;
return search();
} else return new ArrayList<YahooResult>();
}
}
class YahooResult {
private URL url;
private String title;
private String content;
public URL getUrl() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
public void setUrl(String url) throws MalformedURLException {
this.url = new URL(url);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public YahooResult(URL url, String title, String content) {
setUrl(url);
setTitle(title);
setContent(content);
}
public YahooResult(String url, String title, String content) throws MalformedURLException {
setUrl(url);
setTitle(title);
setContent(content);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (title != null) {
sb.append(",title=").append(title);
}
if (url != null) {
sb.append(",url=").append(url);
}
return sb.charAt(0) == ',' ? sb.substring(1) : sb.toString();
}
}
public class TestYahooSearch {
public static void main(String[] args) throws MalformedURLException, URISyntaxException, IOException {
YahooSearch search = new YahooSearch("Rosetta code");
List<YahooResult> results = search.search();
for (YahooResult result : results) {
System.out.println(result.toString());
}
}
}
| require 'open-uri'
require 'hpricot'
SearchResult = Struct.new(:url, :title, :content)
class SearchYahoo
@@urlinfo = [nil, 'ca.search.yahoo.com', 80, '/search', nil, nil]
def initialize(term)
@term = term
@page = 1
@results = nil
@url = URI::HTTP.build(@@urlinfo)
end
def next_result
if not @results
@results = []
fetch_results
elsif @results.empty?
next_page
end
@results.shift
end
def fetch_results
@url.query = URI.escape("p=%s&b=%d" % [@term, @page])
doc = open(@url) { |f| Hpricot(f) }
parse_html(doc)
end
def next_page
@page += 10
fetch_results
end
def parse_html(doc)
doc.search("div
next unless div.has_attribute?("class") and div.get_attribute("class").index("res") == 0
result = SearchResult.new
div.search("a").each do |link|
next unless link.has_attribute?("class") and link.get_attribute("class") == "yschttl spt"
result.url = link.get_attribute("href")
result.title = link.inner_text
end
div.search("div").each do |abstract|
next unless abstract.has_attribute?("class") and abstract.get_attribute("class").index("abstr")
result.content = abstract.inner_text
end
@results << result
end
end
end
s = SearchYahoo.new("test")
15.times do |i|
result = s.next_result
puts i+1
puts result.title
puts result.url
puts result.content
puts
end
|
Rewrite the snippet below in Ruby so it works the same as the original Java code. | import java.util.Objects;
public class Circles {
private static class Point {
private final double x, y;
public Point(Double x, Double y) {
this.x = x;
this.y = y;
}
public double distanceFrom(Point other) {
double dx = x - other.x;
double dy = y - other.y;
return Math.sqrt(dx * dx + dy * dy);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Point point = (Point) other;
return x == point.x && y == point.y;
}
@Override
public String toString() {
return String.format("(%.4f, %.4f)", x, y);
}
}
private static Point[] findCircles(Point p1, Point p2, double r) {
if (r < 0.0) throw new IllegalArgumentException("the radius can't be negative");
if (r == 0.0 && p1 != p2) throw new IllegalArgumentException("no circles can ever be drawn");
if (r == 0.0) return new Point[]{p1, p1};
if (Objects.equals(p1, p2)) throw new IllegalArgumentException("an infinite number of circles can be drawn");
double distance = p1.distanceFrom(p2);
double diameter = 2.0 * r;
if (distance > diameter) throw new IllegalArgumentException("the points are too far apart to draw a circle");
Point center = new Point((p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0);
if (distance == diameter) return new Point[]{center, center};
double mirrorDistance = Math.sqrt(r * r - distance * distance / 4.0);
double dx = (p2.x - p1.x) * mirrorDistance / distance;
double dy = (p2.y - p1.y) * mirrorDistance / distance;
return new Point[]{
new Point(center.x - dy, center.y + dx),
new Point(center.x + dy, center.y - dx)
};
}
public static void main(String[] args) {
Point[] p = new Point[]{
new Point(0.1234, 0.9876),
new Point(0.8765, 0.2345),
new Point(0.0000, 2.0000),
new Point(0.0000, 0.0000)
};
Point[][] points = new Point[][]{
{p[0], p[1]},
{p[2], p[3]},
{p[0], p[0]},
{p[0], p[1]},
{p[0], p[0]},
};
double[] radii = new double[]{2.0, 1.0, 2.0, 0.5, 0.0};
for (int i = 0; i < radii.length; ++i) {
Point p1 = points[i][0];
Point p2 = points[i][1];
double r = radii[i];
System.out.printf("For points %s and %s with radius %f\n", p1, p2, r);
try {
Point[] circles = findCircles(p1, p2, r);
Point c1 = circles[0];
Point c2 = circles[1];
if (Objects.equals(c1, c2)) {
System.out.printf("there is just one circle with center at %s\n", c1);
} else {
System.out.printf("there are two circles with centers at %s and %s\n", c1, c2);
}
} catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
}
System.out.println();
}
}
}
| Pt = Struct.new(:x, :y)
Circle = Struct.new(:x, :y, :r)
def circles_from(pt1, pt2, r)
raise ArgumentError, "Infinite number of circles, points coincide." if pt1 == pt2 && r > 0
return [Circle.new(pt1.x, pt1.y, r)] if pt1 == pt2 && r == 0
dx, dy = pt2.x - pt1.x, pt2.y - pt1.y
q = Math.hypot(dx, dy)
raise ArgumentError, "Distance of points > diameter." if q > 2.0*r
x3, y3 = (pt1.x + pt2.x)/2.0, (pt1.y + pt2.y)/2.0
d = (r**2 - (q/2)**2)**0.5
[Circle.new(x3 - d*dy/q, y3 + d*dx/q, r),
Circle.new(x3 + d*dy/q, y3 - d*dx/q, r)].uniq
end
ar = [[Pt.new(0.1234, 0.9876), Pt.new(0.8765, 0.2345), 2.0],
[Pt.new(0.0000, 2.0000), Pt.new(0.0000, 0.0000), 1.0],
[Pt.new(0.1234, 0.9876), Pt.new(0.1234, 0.9876), 2.0],
[Pt.new(0.1234, 0.9876), Pt.new(0.8765, 0.2345), 0.5],
[Pt.new(0.1234, 0.9876), Pt.new(0.1234, 0.9876), 0.0]]
ar.each do |p1, p2, r|
print "Given points:\n
begin
circles = circles_from(p1, p2, r)
puts "You can construct the following circles:"
circles.each{|c| puts "
rescue ArgumentError => e
puts e
end
puts
end
|
Write a version of this Java function in Ruby with identical behavior. | import java.util.Objects;
public class Circles {
private static class Point {
private final double x, y;
public Point(Double x, Double y) {
this.x = x;
this.y = y;
}
public double distanceFrom(Point other) {
double dx = x - other.x;
double dy = y - other.y;
return Math.sqrt(dx * dx + dy * dy);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Point point = (Point) other;
return x == point.x && y == point.y;
}
@Override
public String toString() {
return String.format("(%.4f, %.4f)", x, y);
}
}
private static Point[] findCircles(Point p1, Point p2, double r) {
if (r < 0.0) throw new IllegalArgumentException("the radius can't be negative");
if (r == 0.0 && p1 != p2) throw new IllegalArgumentException("no circles can ever be drawn");
if (r == 0.0) return new Point[]{p1, p1};
if (Objects.equals(p1, p2)) throw new IllegalArgumentException("an infinite number of circles can be drawn");
double distance = p1.distanceFrom(p2);
double diameter = 2.0 * r;
if (distance > diameter) throw new IllegalArgumentException("the points are too far apart to draw a circle");
Point center = new Point((p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0);
if (distance == diameter) return new Point[]{center, center};
double mirrorDistance = Math.sqrt(r * r - distance * distance / 4.0);
double dx = (p2.x - p1.x) * mirrorDistance / distance;
double dy = (p2.y - p1.y) * mirrorDistance / distance;
return new Point[]{
new Point(center.x - dy, center.y + dx),
new Point(center.x + dy, center.y - dx)
};
}
public static void main(String[] args) {
Point[] p = new Point[]{
new Point(0.1234, 0.9876),
new Point(0.8765, 0.2345),
new Point(0.0000, 2.0000),
new Point(0.0000, 0.0000)
};
Point[][] points = new Point[][]{
{p[0], p[1]},
{p[2], p[3]},
{p[0], p[0]},
{p[0], p[1]},
{p[0], p[0]},
};
double[] radii = new double[]{2.0, 1.0, 2.0, 0.5, 0.0};
for (int i = 0; i < radii.length; ++i) {
Point p1 = points[i][0];
Point p2 = points[i][1];
double r = radii[i];
System.out.printf("For points %s and %s with radius %f\n", p1, p2, r);
try {
Point[] circles = findCircles(p1, p2, r);
Point c1 = circles[0];
Point c2 = circles[1];
if (Objects.equals(c1, c2)) {
System.out.printf("there is just one circle with center at %s\n", c1);
} else {
System.out.printf("there are two circles with centers at %s and %s\n", c1, c2);
}
} catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
}
System.out.println();
}
}
}
| Pt = Struct.new(:x, :y)
Circle = Struct.new(:x, :y, :r)
def circles_from(pt1, pt2, r)
raise ArgumentError, "Infinite number of circles, points coincide." if pt1 == pt2 && r > 0
return [Circle.new(pt1.x, pt1.y, r)] if pt1 == pt2 && r == 0
dx, dy = pt2.x - pt1.x, pt2.y - pt1.y
q = Math.hypot(dx, dy)
raise ArgumentError, "Distance of points > diameter." if q > 2.0*r
x3, y3 = (pt1.x + pt2.x)/2.0, (pt1.y + pt2.y)/2.0
d = (r**2 - (q/2)**2)**0.5
[Circle.new(x3 - d*dy/q, y3 + d*dx/q, r),
Circle.new(x3 + d*dy/q, y3 - d*dx/q, r)].uniq
end
ar = [[Pt.new(0.1234, 0.9876), Pt.new(0.8765, 0.2345), 2.0],
[Pt.new(0.0000, 2.0000), Pt.new(0.0000, 0.0000), 1.0],
[Pt.new(0.1234, 0.9876), Pt.new(0.1234, 0.9876), 2.0],
[Pt.new(0.1234, 0.9876), Pt.new(0.8765, 0.2345), 0.5],
[Pt.new(0.1234, 0.9876), Pt.new(0.1234, 0.9876), 0.0]]
ar.each do |p1, p2, r|
print "Given points:\n
begin
circles = circles_from(p1, p2, r)
puts "You can construct the following circles:"
circles.each{|c| puts "
rescue ArgumentError => e
puts e
end
puts
end
|
Translate this program into Ruby but keep the logic exactly as in Java. | import java.util.Arrays;
import java.util.HashSet;
public class VampireNumbers{
private static int numDigits(long num){
return Long.toString(Math.abs(num)).length();
}
private static boolean fangCheck(long orig, long fang1, long fang2){
if(Long.toString(fang1).endsWith("0") && Long.toString(fang2).endsWith("0")) return false;
int origLen = numDigits(orig);
if(numDigits(fang1) != origLen / 2 || numDigits(fang2) != origLen / 2) return false;
byte[] origBytes = Long.toString(orig).getBytes();
byte[] fangBytes = (Long.toString(fang1) + Long.toString(fang2)).getBytes();
Arrays.sort(origBytes);
Arrays.sort(fangBytes);
return Arrays.equals(origBytes, fangBytes);
}
public static void main(String[] args){
HashSet<Long> vamps = new HashSet<Long>();
for(long i = 10; vamps.size() <= 25; i++ ){
if((numDigits(i) % 2) != 0) {i = i * 10 - 1; continue;}
for(long fang1 = 2; fang1 <= Math.sqrt(i) + 1; fang1++){
if(i % fang1 == 0){
long fang2 = i / fang1;
if(fangCheck(i, fang1, fang2) && fang1 <= fang2){
vamps.add(i);
System.out.println(i + ": [" + fang1 + ", " + fang2 +"]");
}
}
}
}
Long[] nums = {16758243290880L, 24959017348650L, 14593825548650L};
for(Long i : nums){
for(long fang1 = 2; fang1 <= Math.sqrt(i) + 1; fang1++){
if(i % fang1 == 0){
long fang2 = i / fang1;
if(fangCheck(i, fang1, fang2) && fang1 <= fang2){
System.out.println(i + ": [" + fang1 + ", " + fang2 +"]");
}
}
}
}
}
}
| def factor_pairs n
first = n / (10 ** (n.to_s.size / 2) - 1)
(first .. n ** 0.5).map { |i| [i, n / i] if n % i == 0 }.compact
end
def vampire_factors n
return [] if n.to_s.size.odd?
half = n.to_s.size / 2
factor_pairs(n).select do |a, b|
a.to_s.size == half && b.to_s.size == half &&
[a, b].count {|x| x%10 == 0} != 2 &&
"
end
end
i = vamps = 0
until vamps == 25
vf = vampire_factors(i += 1)
unless vf.empty?
puts "
vamps += 1
end
end
[16758243290880, 24959017348650, 14593825548650].each do |n|
if (vf = vampire_factors n).empty?
puts "
else
puts "
end
end
|
Write the same code in Ruby as shown below in Java. | import java.util.Arrays;
import java.util.List;
public class Cistercian {
private static final int SIZE = 15;
private final char[][] canvas = new char[SIZE][SIZE];
public Cistercian(int n) {
initN();
draw(n);
}
public void initN() {
for (var row : canvas) {
Arrays.fill(row, ' ');
row[5] = 'x';
}
}
private void horizontal(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r][c] = 'x';
}
}
private void vertical(int r1, int r2, int c) {
for (int r = r1; r <= r2; r++) {
canvas[r][c] = 'x';
}
}
private void diagd(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r + c - c1][c] = 'x';
}
}
private void diagu(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r - c + c1][c] = 'x';
}
}
private void draw(int v) {
var thousands = v / 1000;
v %= 1000;
var hundreds = v / 100;
v %= 100;
var tens = v / 10;
var ones = v % 10;
drawPart(1000 * thousands);
drawPart(100 * hundreds);
drawPart(10 * tens);
drawPart(ones);
}
private void drawPart(int v) {
switch (v) {
case 1:
horizontal(6, 10, 0);
break;
case 2:
horizontal(6, 10, 4);
break;
case 3:
diagd(6, 10, 0);
break;
case 4:
diagu(6, 10, 4);
break;
case 5:
drawPart(1);
drawPart(4);
break;
case 6:
vertical(0, 4, 10);
break;
case 7:
drawPart(1);
drawPart(6);
break;
case 8:
drawPart(2);
drawPart(6);
break;
case 9:
drawPart(1);
drawPart(8);
break;
case 10:
horizontal(0, 4, 0);
break;
case 20:
horizontal(0, 4, 4);
break;
case 30:
diagu(0, 4, 4);
break;
case 40:
diagd(0, 4, 0);
break;
case 50:
drawPart(10);
drawPart(40);
break;
case 60:
vertical(0, 4, 0);
break;
case 70:
drawPart(10);
drawPart(60);
break;
case 80:
drawPart(20);
drawPart(60);
break;
case 90:
drawPart(10);
drawPart(80);
break;
case 100:
horizontal(6, 10, 14);
break;
case 200:
horizontal(6, 10, 10);
break;
case 300:
diagu(6, 10, 14);
break;
case 400:
diagd(6, 10, 10);
break;
case 500:
drawPart(100);
drawPart(400);
break;
case 600:
vertical(10, 14, 10);
break;
case 700:
drawPart(100);
drawPart(600);
break;
case 800:
drawPart(200);
drawPart(600);
break;
case 900:
drawPart(100);
drawPart(800);
break;
case 1000:
horizontal(0, 4, 14);
break;
case 2000:
horizontal(0, 4, 10);
break;
case 3000:
diagd(0, 4, 10);
break;
case 4000:
diagu(0, 4, 14);
break;
case 5000:
drawPart(1000);
drawPart(4000);
break;
case 6000:
vertical(10, 14, 0);
break;
case 7000:
drawPart(1000);
drawPart(6000);
break;
case 8000:
drawPart(2000);
drawPart(6000);
break;
case 9000:
drawPart(1000);
drawPart(8000);
break;
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (var row : canvas) {
builder.append(row);
builder.append('\n');
}
return builder.toString();
}
public static void main(String[] args) {
for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {
System.out.printf("%d:\n", number);
var c = new Cistercian(number);
System.out.println(c);
}
}
}
| def initN
n = Array.new(15){Array.new(11, ' ')}
for i in 1..15
n[i - 1][5] = 'x'
end
return n
end
def horiz(n, c1, c2, r)
for c in c1..c2
n[r][c] = 'x'
end
end
def verti(n, r1, r2, c)
for r in r1..r2
n[r][c] = 'x'
end
end
def diagd(n, c1, c2, r)
for c in c1..c2
n[r+c-c1][c] = 'x'
end
end
def diagu(n, c1, c2, r)
for c in c1..c2
n[r-c+c1][c] = 'x'
end
end
def initDraw
draw = []
draw[1] = lambda do |n| horiz(n, 6, 10, 0) end
draw[2] = lambda do |n| horiz(n, 6, 10, 4) end
draw[3] = lambda do |n| diagd(n, 6, 10, 0) end
draw[4] = lambda do |n| diagu(n, 6, 10, 4) end
draw[5] = lambda do |n|
draw[1].call(n)
draw[4].call(n)
end
draw[6] = lambda do |n| verti(n, 0, 4, 10) end
draw[7] = lambda do |n|
draw[1].call(n)
draw[6].call(n)
end
draw[8] = lambda do |n|
draw[2].call(n)
draw[6].call(n)
end
draw[9] = lambda do |n|
draw[1].call(n)
draw[8].call(n)
end
draw[10] = lambda do |n| horiz(n, 0, 4, 0) end
draw[20] = lambda do |n| horiz(n, 0, 4, 4) end
draw[30] = lambda do |n| diagu(n, 0, 4, 4) end
draw[40] = lambda do |n| diagd(n, 0, 4, 0) end
draw[50] = lambda do |n|
draw[10].call(n)
draw[40].call(n)
end
draw[60] = lambda do |n| verti(n, 0, 4, 0) end
draw[70] = lambda do |n|
draw[10].call(n)
draw[60].call(n)
end
draw[80] = lambda do |n|
draw[20].call(n)
draw[60].call(n)
end
draw[90] = lambda do |n|
draw[10].call(n)
draw[80].call(n)
end
draw[100] = lambda do |n| horiz(n, 6, 10, 14) end
draw[200] = lambda do |n| horiz(n, 6, 10, 10) end
draw[300] = lambda do |n| diagu(n, 6, 10, 14) end
draw[400] = lambda do |n| diagd(n, 6, 10, 10) end
draw[500] = lambda do |n|
draw[100].call(n)
draw[400].call(n)
end
draw[600] = lambda do |n| verti(n, 10, 14, 10) end
draw[700] = lambda do |n|
draw[100].call(n)
draw[600].call(n)
end
draw[800] = lambda do |n|
draw[200].call(n)
draw[600].call(n)
end
draw[900] = lambda do |n|
draw[100].call(n)
draw[800].call(n)
end
draw[1000] = lambda do |n| horiz(n, 0, 4, 14) end
draw[2000] = lambda do |n| horiz(n, 0, 4, 10) end
draw[3000] = lambda do |n| diagd(n, 0, 4, 10) end
draw[4000] = lambda do |n| diagu(n, 0, 4, 14) end
draw[5000] = lambda do |n|
draw[1000].call(n)
draw[4000].call(n)
end
draw[6000] = lambda do |n| verti(n, 10, 14, 0) end
draw[7000] = lambda do |n|
draw[1000].call(n)
draw[6000].call(n)
end
draw[8000] = lambda do |n|
draw[2000].call(n)
draw[6000].call(n)
end
draw[9000] = lambda do |n|
draw[1000].call(n)
draw[8000].call(n)
end
return draw
end
def printNumeral(n)
for a in n
for b in a
print b
end
print "\n"
end
print "\n"
end
draw = initDraw()
for number in [0, 1, 20, 300, 4000, 5555, 6789, 9999]
n = initN()
print number, ":\n"
thousands = (number / 1000).floor
number = number % 1000
hundreds = (number / 100).floor
number = number % 100
tens = (number / 10).floor
ones = number % 10
if thousands > 0 then
draw[thousands * 1000].call(n)
end
if hundreds > 0 then
draw[hundreds * 100].call(n)
end
if tens > 0 then
draw[tens * 10].call(n)
end
if ones > 0 then
draw[ones].call(n)
end
printNumeral(n)
end
|
Convert this Java snippet to Ruby and keep its semantics consistent. | import java.util.Arrays;
import java.util.List;
public class Cistercian {
private static final int SIZE = 15;
private final char[][] canvas = new char[SIZE][SIZE];
public Cistercian(int n) {
initN();
draw(n);
}
public void initN() {
for (var row : canvas) {
Arrays.fill(row, ' ');
row[5] = 'x';
}
}
private void horizontal(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r][c] = 'x';
}
}
private void vertical(int r1, int r2, int c) {
for (int r = r1; r <= r2; r++) {
canvas[r][c] = 'x';
}
}
private void diagd(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r + c - c1][c] = 'x';
}
}
private void diagu(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r - c + c1][c] = 'x';
}
}
private void draw(int v) {
var thousands = v / 1000;
v %= 1000;
var hundreds = v / 100;
v %= 100;
var tens = v / 10;
var ones = v % 10;
drawPart(1000 * thousands);
drawPart(100 * hundreds);
drawPart(10 * tens);
drawPart(ones);
}
private void drawPart(int v) {
switch (v) {
case 1:
horizontal(6, 10, 0);
break;
case 2:
horizontal(6, 10, 4);
break;
case 3:
diagd(6, 10, 0);
break;
case 4:
diagu(6, 10, 4);
break;
case 5:
drawPart(1);
drawPart(4);
break;
case 6:
vertical(0, 4, 10);
break;
case 7:
drawPart(1);
drawPart(6);
break;
case 8:
drawPart(2);
drawPart(6);
break;
case 9:
drawPart(1);
drawPart(8);
break;
case 10:
horizontal(0, 4, 0);
break;
case 20:
horizontal(0, 4, 4);
break;
case 30:
diagu(0, 4, 4);
break;
case 40:
diagd(0, 4, 0);
break;
case 50:
drawPart(10);
drawPart(40);
break;
case 60:
vertical(0, 4, 0);
break;
case 70:
drawPart(10);
drawPart(60);
break;
case 80:
drawPart(20);
drawPart(60);
break;
case 90:
drawPart(10);
drawPart(80);
break;
case 100:
horizontal(6, 10, 14);
break;
case 200:
horizontal(6, 10, 10);
break;
case 300:
diagu(6, 10, 14);
break;
case 400:
diagd(6, 10, 10);
break;
case 500:
drawPart(100);
drawPart(400);
break;
case 600:
vertical(10, 14, 10);
break;
case 700:
drawPart(100);
drawPart(600);
break;
case 800:
drawPart(200);
drawPart(600);
break;
case 900:
drawPart(100);
drawPart(800);
break;
case 1000:
horizontal(0, 4, 14);
break;
case 2000:
horizontal(0, 4, 10);
break;
case 3000:
diagd(0, 4, 10);
break;
case 4000:
diagu(0, 4, 14);
break;
case 5000:
drawPart(1000);
drawPart(4000);
break;
case 6000:
vertical(10, 14, 0);
break;
case 7000:
drawPart(1000);
drawPart(6000);
break;
case 8000:
drawPart(2000);
drawPart(6000);
break;
case 9000:
drawPart(1000);
drawPart(8000);
break;
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (var row : canvas) {
builder.append(row);
builder.append('\n');
}
return builder.toString();
}
public static void main(String[] args) {
for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {
System.out.printf("%d:\n", number);
var c = new Cistercian(number);
System.out.println(c);
}
}
}
| def initN
n = Array.new(15){Array.new(11, ' ')}
for i in 1..15
n[i - 1][5] = 'x'
end
return n
end
def horiz(n, c1, c2, r)
for c in c1..c2
n[r][c] = 'x'
end
end
def verti(n, r1, r2, c)
for r in r1..r2
n[r][c] = 'x'
end
end
def diagd(n, c1, c2, r)
for c in c1..c2
n[r+c-c1][c] = 'x'
end
end
def diagu(n, c1, c2, r)
for c in c1..c2
n[r-c+c1][c] = 'x'
end
end
def initDraw
draw = []
draw[1] = lambda do |n| horiz(n, 6, 10, 0) end
draw[2] = lambda do |n| horiz(n, 6, 10, 4) end
draw[3] = lambda do |n| diagd(n, 6, 10, 0) end
draw[4] = lambda do |n| diagu(n, 6, 10, 4) end
draw[5] = lambda do |n|
draw[1].call(n)
draw[4].call(n)
end
draw[6] = lambda do |n| verti(n, 0, 4, 10) end
draw[7] = lambda do |n|
draw[1].call(n)
draw[6].call(n)
end
draw[8] = lambda do |n|
draw[2].call(n)
draw[6].call(n)
end
draw[9] = lambda do |n|
draw[1].call(n)
draw[8].call(n)
end
draw[10] = lambda do |n| horiz(n, 0, 4, 0) end
draw[20] = lambda do |n| horiz(n, 0, 4, 4) end
draw[30] = lambda do |n| diagu(n, 0, 4, 4) end
draw[40] = lambda do |n| diagd(n, 0, 4, 0) end
draw[50] = lambda do |n|
draw[10].call(n)
draw[40].call(n)
end
draw[60] = lambda do |n| verti(n, 0, 4, 0) end
draw[70] = lambda do |n|
draw[10].call(n)
draw[60].call(n)
end
draw[80] = lambda do |n|
draw[20].call(n)
draw[60].call(n)
end
draw[90] = lambda do |n|
draw[10].call(n)
draw[80].call(n)
end
draw[100] = lambda do |n| horiz(n, 6, 10, 14) end
draw[200] = lambda do |n| horiz(n, 6, 10, 10) end
draw[300] = lambda do |n| diagu(n, 6, 10, 14) end
draw[400] = lambda do |n| diagd(n, 6, 10, 10) end
draw[500] = lambda do |n|
draw[100].call(n)
draw[400].call(n)
end
draw[600] = lambda do |n| verti(n, 10, 14, 10) end
draw[700] = lambda do |n|
draw[100].call(n)
draw[600].call(n)
end
draw[800] = lambda do |n|
draw[200].call(n)
draw[600].call(n)
end
draw[900] = lambda do |n|
draw[100].call(n)
draw[800].call(n)
end
draw[1000] = lambda do |n| horiz(n, 0, 4, 14) end
draw[2000] = lambda do |n| horiz(n, 0, 4, 10) end
draw[3000] = lambda do |n| diagd(n, 0, 4, 10) end
draw[4000] = lambda do |n| diagu(n, 0, 4, 14) end
draw[5000] = lambda do |n|
draw[1000].call(n)
draw[4000].call(n)
end
draw[6000] = lambda do |n| verti(n, 10, 14, 0) end
draw[7000] = lambda do |n|
draw[1000].call(n)
draw[6000].call(n)
end
draw[8000] = lambda do |n|
draw[2000].call(n)
draw[6000].call(n)
end
draw[9000] = lambda do |n|
draw[1000].call(n)
draw[8000].call(n)
end
return draw
end
def printNumeral(n)
for a in n
for b in a
print b
end
print "\n"
end
print "\n"
end
draw = initDraw()
for number in [0, 1, 20, 300, 4000, 5555, 6789, 9999]
n = initN()
print number, ":\n"
thousands = (number / 1000).floor
number = number % 1000
hundreds = (number / 100).floor
number = number % 100
tens = (number / 10).floor
ones = number % 10
if thousands > 0 then
draw[thousands * 1000].call(n)
end
if hundreds > 0 then
draw[hundreds * 100].call(n)
end
if tens > 0 then
draw[tens * 10].call(n)
end
if ones > 0 then
draw[ones].call(n)
end
printNumeral(n)
end
|
Write the same code in Ruby as shown below in Java. | import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
public class PokerHandAnalyzer {
final static String faces = "AKQJT98765432";
final static String suits = "HDSC";
final static String[] deck = buildDeck();
public static void main(String[] args) {
System.out.println("Regular hands:\n");
for (String input : new String[]{"2H 2D 2S KS QD",
"2H 5H 7D 8S 9D",
"AH 2D 3S 4S 5S",
"2H 3H 2D 3S 3D",
"2H 7H 2D 3S 3D",
"2H 7H 7D 7S 7C",
"TH JH QH KH AH",
"4H 4C KC 5D TC",
"QC TC 7C 6C 4C",
"QC TC 7C 7C TD"}) {
System.out.println(analyzeHand(input.split(" ")));
}
System.out.println("\nHands with wildcards:\n");
for (String input : new String[]{"2H 2D 2S KS WW",
"2H 5H 7D 8S WW",
"AH 2D 3S 4S WW",
"2H 3H 2D 3S WW",
"2H 7H 2D 3S WW",
"2H 7H 7D WW WW",
"TH JH QH WW WW",
"4H 4C KC WW WW",
"QC TC 7C WW WW",
"QC TC 7H WW WW"}) {
System.out.println(analyzeHandWithWildcards(input.split(" ")));
}
}
private static Score analyzeHand(final String[] hand) {
if (hand.length != 5)
return new Score("invalid hand: wrong number of cards", -1, hand);
if (new HashSet<>(Arrays.asList(hand)).size() != hand.length)
return new Score("invalid hand: duplicates", -1, hand);
int[] faceCount = new int[faces.length()];
long straight = 0, flush = 0;
for (String card : hand) {
int face = faces.indexOf(card.charAt(0));
if (face == -1)
return new Score("invalid hand: non existing face", -1, hand);
straight |= (1 << face);
faceCount[face]++;
if (suits.indexOf(card.charAt(1)) == -1)
return new Score("invalid hand: non-existing suit", -1, hand);
flush |= (1 << card.charAt(1));
}
while (straight % 2 == 0)
straight >>= 1;
boolean hasStraight = straight == 0b11111 || straight == 0b1111000000001;
boolean hasFlush = (flush & (flush - 1)) == 0;
if (hasStraight && hasFlush)
return new Score("straight-flush", 9, hand);
int total = 0;
for (int count : faceCount) {
if (count == 4)
return new Score("four-of-a-kind", 8, hand);
if (count == 3)
total += 3;
else if (count == 2)
total += 2;
}
if (total == 5)
return new Score("full-house", 7, hand);
if (hasFlush)
return new Score("flush", 6, hand);
if (hasStraight)
return new Score("straight", 5, hand);
if (total == 3)
return new Score("three-of-a-kind", 4, hand);
if (total == 4)
return new Score("two-pair", 3, hand);
if (total == 2)
return new Score("one-pair", 2, hand);
return new Score("high-card", 1, hand);
}
private static WildScore analyzeHandWithWildcards(String[] hand) {
if (Collections.frequency(Arrays.asList(hand), "WW") > 2)
throw new IllegalArgumentException("too many wildcards");
return new WildScore(analyzeHandWithWildcardsR(hand, null), hand.clone());
}
private static Score analyzeHandWithWildcardsR(String[] hand,
Score best) {
for (int i = 0; i < hand.length; i++) {
if (hand[i].equals("WW")) {
for (String card : deck) {
if (!Arrays.asList(hand).contains(card)) {
hand[i] = card;
best = analyzeHandWithWildcardsR(hand, best);
}
}
hand[i] = "WW";
break;
}
}
Score result = analyzeHand(hand);
if (best == null || result.weight > best.weight)
best = result;
return best;
}
private static String[] buildDeck() {
String[] dck = new String[suits.length() * faces.length()];
int i = 0;
for (char s : suits.toCharArray()) {
for (char f : faces.toCharArray()) {
dck[i] = "" + f + s;
i++;
}
}
return dck;
}
private static class Score {
final int weight;
final String name;
final String[] hand;
Score(String n, int w, String[] h) {
weight = w;
name = n;
hand = h != null ? h.clone() : h;
}
@Override
public String toString() {
return Arrays.toString(hand) + " " + name;
}
}
private static class WildScore {
final String[] wild;
final Score score;
WildScore(Score s, String[] w) {
score = s;
wild = w;
}
@Override
public String toString() {
return String.format("%s%n%s%n", Arrays.toString(wild),
score.toString());
}
}
}
| class Card
include Comparable
attr_accessor :ordinal
attr_reader :suit, :face
SUITS = %i(♥ ♦ ♣ ♠)
FACES = %i(2 3 4 5 6 7 8 9 10 j q k a)
def initialize(str)
@face, @suit = parse(str)
@ordinal = FACES.index(@face)
end
def <=> (other)
self.ordinal <=> other.ordinal
end
def to_s
"
end
private
def parse(str)
face, suit = str.chop.to_sym, str[-1].to_sym
raise ArgumentError, "invalid card:
[face, suit]
end
end
class Hand
include Comparable
attr_reader :cards, :rank
RANKS = %i(high-card one-pair two-pair three-of-a-kind straight flush
full-house four-of-a-kind straight-flush five-of-a-kind)
WHEEL_FACES = %i(2 3 4 5 a)
def initialize(str_of_cards)
@cards = str_of_cards.downcase.tr(',',' ').split.map{|str| Card.new(str)}
grouped = @cards.group_by(&:face).values
@face_pattern = grouped.map(&:size).sort
@rank = categorize
@rank_num = RANKS.index(@rank)
@tiebreaker = grouped.map{|ar| [ar.size, ar.first.ordinal]}.sort.reverse
end
def <=> (other)
self.compare_value <=> other.compare_value
end
def to_s
@cards.map(&:to_s).join(" ")
end
protected
def compare_value
[@rank_num, @tiebreaker]
end
private
def one_suit?
@cards.map(&:suit).uniq.size == 1
end
def consecutive?
sort.each_cons(2).all? {|c1,c2| c2.ordinal - c1.ordinal == 1 }
end
def sort
if @cards.sort.map(&:face) == WHEEL_FACES
@cards.detect {|c| c.face == :a}.ordinal = -1
end
@cards.sort
end
def categorize
if consecutive?
one_suit? ? :'straight-flush' : :straight
elsif one_suit?
:flush
else
case @face_pattern
when [1,1,1,1,1] then :'high-card'
when [1,1,1,2] then :'one-pair'
when [1,2,2] then :'two-pair'
when [1,1,3] then :'three-of-a-kind'
when [2,3] then :'full-house'
when [1,4] then :'four-of-a-kind'
when [5] then :'five-of-a-kind'
end
end
end
end
test_hands = <<EOS
2♥ 2♦ 2♣ k♣ q♦
2♥ 5♥ 7♦ 8♣ 9♠
a♥ 2♦ 3♣ 4♣ 5♦
2♥ 3♥ 2♦ 3♣ 3♦
2♥ 7♥ 2♦ 3♣ 3♦
2♥ 6♥ 2♦ 3♣ 3♦
10♥ j♥ q♥ k♥ a♥
4♥ 4♠ k♠ 2♦ 10♠
4♥ 4♠ k♠ 3♦ 10♠
q♣ 10♣ 7♣ 6♣ 4♣
q♣ 10♣ 7♣ 6♣ 3♣
9♥ 10♥ q♥ k♥ j♣
2♥ 3♥ 4♥ 5♥ a♥
2♥ 2♥ 2♦ 3♣ 3♦
EOS
hands = test_hands.each_line.map{|line| Hand.new(line) }
puts "High to low"
hands.sort.reverse.each{|hand| puts "
puts
str = <<EOS
joker 2♦ 2♠ k♠ q♦
joker 5♥ 7♦ 8♠ 9♦
joker 2♦ 3♠ 4♠ 5♠
joker 3♥ 2♦ 3♠ 3♦
joker 7♥ 2♦ 3♠ 3♦
joker 7♥ 7♦ 7♠ 7♣
joker j♥ q♥ k♥ A♥
joker 4♣ k♣ 5♦ 10♠
joker k♣ 7♣ 6♣ 4♣
joker 2♦ joker 4♠ 5♠
joker Q♦ joker A♠ 10♠
joker Q♦ joker A♦ 10♦
joker 2♦ 2♠ joker q♦
EOS
DECK = Card::FACES.product(Card::SUITS).map(&:join)
str.each_line do |line|
cards_in_arrays = line.split.map{|c| c == "joker" ? DECK.dup : [c]}
all_tries = cards_in_arrays.shift.product(*cards_in_arrays).map{|ar| Hand.new(ar.join" ")}
best = all_tries.max
puts "
end
|
Ensure the translated Ruby code behaves exactly like the original Java snippet. | import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
public class PokerHandAnalyzer {
final static String faces = "AKQJT98765432";
final static String suits = "HDSC";
final static String[] deck = buildDeck();
public static void main(String[] args) {
System.out.println("Regular hands:\n");
for (String input : new String[]{"2H 2D 2S KS QD",
"2H 5H 7D 8S 9D",
"AH 2D 3S 4S 5S",
"2H 3H 2D 3S 3D",
"2H 7H 2D 3S 3D",
"2H 7H 7D 7S 7C",
"TH JH QH KH AH",
"4H 4C KC 5D TC",
"QC TC 7C 6C 4C",
"QC TC 7C 7C TD"}) {
System.out.println(analyzeHand(input.split(" ")));
}
System.out.println("\nHands with wildcards:\n");
for (String input : new String[]{"2H 2D 2S KS WW",
"2H 5H 7D 8S WW",
"AH 2D 3S 4S WW",
"2H 3H 2D 3S WW",
"2H 7H 2D 3S WW",
"2H 7H 7D WW WW",
"TH JH QH WW WW",
"4H 4C KC WW WW",
"QC TC 7C WW WW",
"QC TC 7H WW WW"}) {
System.out.println(analyzeHandWithWildcards(input.split(" ")));
}
}
private static Score analyzeHand(final String[] hand) {
if (hand.length != 5)
return new Score("invalid hand: wrong number of cards", -1, hand);
if (new HashSet<>(Arrays.asList(hand)).size() != hand.length)
return new Score("invalid hand: duplicates", -1, hand);
int[] faceCount = new int[faces.length()];
long straight = 0, flush = 0;
for (String card : hand) {
int face = faces.indexOf(card.charAt(0));
if (face == -1)
return new Score("invalid hand: non existing face", -1, hand);
straight |= (1 << face);
faceCount[face]++;
if (suits.indexOf(card.charAt(1)) == -1)
return new Score("invalid hand: non-existing suit", -1, hand);
flush |= (1 << card.charAt(1));
}
while (straight % 2 == 0)
straight >>= 1;
boolean hasStraight = straight == 0b11111 || straight == 0b1111000000001;
boolean hasFlush = (flush & (flush - 1)) == 0;
if (hasStraight && hasFlush)
return new Score("straight-flush", 9, hand);
int total = 0;
for (int count : faceCount) {
if (count == 4)
return new Score("four-of-a-kind", 8, hand);
if (count == 3)
total += 3;
else if (count == 2)
total += 2;
}
if (total == 5)
return new Score("full-house", 7, hand);
if (hasFlush)
return new Score("flush", 6, hand);
if (hasStraight)
return new Score("straight", 5, hand);
if (total == 3)
return new Score("three-of-a-kind", 4, hand);
if (total == 4)
return new Score("two-pair", 3, hand);
if (total == 2)
return new Score("one-pair", 2, hand);
return new Score("high-card", 1, hand);
}
private static WildScore analyzeHandWithWildcards(String[] hand) {
if (Collections.frequency(Arrays.asList(hand), "WW") > 2)
throw new IllegalArgumentException("too many wildcards");
return new WildScore(analyzeHandWithWildcardsR(hand, null), hand.clone());
}
private static Score analyzeHandWithWildcardsR(String[] hand,
Score best) {
for (int i = 0; i < hand.length; i++) {
if (hand[i].equals("WW")) {
for (String card : deck) {
if (!Arrays.asList(hand).contains(card)) {
hand[i] = card;
best = analyzeHandWithWildcardsR(hand, best);
}
}
hand[i] = "WW";
break;
}
}
Score result = analyzeHand(hand);
if (best == null || result.weight > best.weight)
best = result;
return best;
}
private static String[] buildDeck() {
String[] dck = new String[suits.length() * faces.length()];
int i = 0;
for (char s : suits.toCharArray()) {
for (char f : faces.toCharArray()) {
dck[i] = "" + f + s;
i++;
}
}
return dck;
}
private static class Score {
final int weight;
final String name;
final String[] hand;
Score(String n, int w, String[] h) {
weight = w;
name = n;
hand = h != null ? h.clone() : h;
}
@Override
public String toString() {
return Arrays.toString(hand) + " " + name;
}
}
private static class WildScore {
final String[] wild;
final Score score;
WildScore(Score s, String[] w) {
score = s;
wild = w;
}
@Override
public String toString() {
return String.format("%s%n%s%n", Arrays.toString(wild),
score.toString());
}
}
}
| class Card
include Comparable
attr_accessor :ordinal
attr_reader :suit, :face
SUITS = %i(♥ ♦ ♣ ♠)
FACES = %i(2 3 4 5 6 7 8 9 10 j q k a)
def initialize(str)
@face, @suit = parse(str)
@ordinal = FACES.index(@face)
end
def <=> (other)
self.ordinal <=> other.ordinal
end
def to_s
"
end
private
def parse(str)
face, suit = str.chop.to_sym, str[-1].to_sym
raise ArgumentError, "invalid card:
[face, suit]
end
end
class Hand
include Comparable
attr_reader :cards, :rank
RANKS = %i(high-card one-pair two-pair three-of-a-kind straight flush
full-house four-of-a-kind straight-flush five-of-a-kind)
WHEEL_FACES = %i(2 3 4 5 a)
def initialize(str_of_cards)
@cards = str_of_cards.downcase.tr(',',' ').split.map{|str| Card.new(str)}
grouped = @cards.group_by(&:face).values
@face_pattern = grouped.map(&:size).sort
@rank = categorize
@rank_num = RANKS.index(@rank)
@tiebreaker = grouped.map{|ar| [ar.size, ar.first.ordinal]}.sort.reverse
end
def <=> (other)
self.compare_value <=> other.compare_value
end
def to_s
@cards.map(&:to_s).join(" ")
end
protected
def compare_value
[@rank_num, @tiebreaker]
end
private
def one_suit?
@cards.map(&:suit).uniq.size == 1
end
def consecutive?
sort.each_cons(2).all? {|c1,c2| c2.ordinal - c1.ordinal == 1 }
end
def sort
if @cards.sort.map(&:face) == WHEEL_FACES
@cards.detect {|c| c.face == :a}.ordinal = -1
end
@cards.sort
end
def categorize
if consecutive?
one_suit? ? :'straight-flush' : :straight
elsif one_suit?
:flush
else
case @face_pattern
when [1,1,1,1,1] then :'high-card'
when [1,1,1,2] then :'one-pair'
when [1,2,2] then :'two-pair'
when [1,1,3] then :'three-of-a-kind'
when [2,3] then :'full-house'
when [1,4] then :'four-of-a-kind'
when [5] then :'five-of-a-kind'
end
end
end
end
test_hands = <<EOS
2♥ 2♦ 2♣ k♣ q♦
2♥ 5♥ 7♦ 8♣ 9♠
a♥ 2♦ 3♣ 4♣ 5♦
2♥ 3♥ 2♦ 3♣ 3♦
2♥ 7♥ 2♦ 3♣ 3♦
2♥ 6♥ 2♦ 3♣ 3♦
10♥ j♥ q♥ k♥ a♥
4♥ 4♠ k♠ 2♦ 10♠
4♥ 4♠ k♠ 3♦ 10♠
q♣ 10♣ 7♣ 6♣ 4♣
q♣ 10♣ 7♣ 6♣ 3♣
9♥ 10♥ q♥ k♥ j♣
2♥ 3♥ 4♥ 5♥ a♥
2♥ 2♥ 2♦ 3♣ 3♦
EOS
hands = test_hands.each_line.map{|line| Hand.new(line) }
puts "High to low"
hands.sort.reverse.each{|hand| puts "
puts
str = <<EOS
joker 2♦ 2♠ k♠ q♦
joker 5♥ 7♦ 8♠ 9♦
joker 2♦ 3♠ 4♠ 5♠
joker 3♥ 2♦ 3♠ 3♦
joker 7♥ 2♦ 3♠ 3♦
joker 7♥ 7♦ 7♠ 7♣
joker j♥ q♥ k♥ A♥
joker 4♣ k♣ 5♦ 10♠
joker k♣ 7♣ 6♣ 4♣
joker 2♦ joker 4♠ 5♠
joker Q♦ joker A♠ 10♠
joker Q♦ joker A♦ 10♦
joker 2♦ 2♠ joker q♦
EOS
DECK = Card::FACES.product(Card::SUITS).map(&:join)
str.each_line do |line|
cards_in_arrays = line.split.map{|c| c == "joker" ? DECK.dup : [c]}
all_tries = cards_in_arrays.shift.product(*cards_in_arrays).map{|ar| Hand.new(ar.join" ")}
best = all_tries.max
puts "
end
|
Change the following Java code into Ruby without altering its purpose. | import java.awt.*;
import javax.swing.*;
public class FibonacciWordFractal extends JPanel {
String wordFractal;
FibonacciWordFractal(int n) {
setPreferredSize(new Dimension(450, 620));
setBackground(Color.white);
wordFractal = wordFractal(n);
}
public String wordFractal(int n) {
if (n < 2)
return n == 1 ? "1" : "";
StringBuilder f1 = new StringBuilder("1");
StringBuilder f2 = new StringBuilder("0");
for (n = n - 2; n > 0; n--) {
String tmp = f2.toString();
f2.append(f1);
f1.setLength(0);
f1.append(tmp);
}
return f2.toString();
}
void drawWordFractal(Graphics2D g, int x, int y, int dx, int dy) {
for (int n = 0; n < wordFractal.length(); n++) {
g.drawLine(x, y, x + dx, y + dy);
x += dx;
y += dy;
if (wordFractal.charAt(n) == '0') {
int tx = dx;
dx = (n % 2 == 0) ? -dy : dy;
dy = (n % 2 == 0) ? tx : -tx;
}
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawWordFractal(g, 20, 20, 1, 0);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Fibonacci Word Fractal");
f.setResizable(false);
f.add(new FibonacciWordFractal(23), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
| def fibonacci_word(n)
words = ["1", "0"]
(n-1).times{ words << words[-1] + words[-2] }
words[n]
end
def print_fractal(word)
area = Hash.new(" ")
x = y = 0
dx, dy = 0, -1
area[[x,y]] = "S"
word.each_char.with_index(1) do |c,n|
area[[x+dx, y+dy]] = dx.zero? ? "|" : "-"
x, y = x+2*dx, y+2*dy
area[[x, y]] = "+"
dx,dy = n.even? ? [dy,-dx] : [-dy,dx] if c=="0"
end
(xmin, xmax), (ymin, ymax) = area.keys.transpose.map(&:minmax)
for y in ymin..ymax
puts (xmin..xmax).map{|x| area[[x,y]]}.join
end
end
word = fibonacci_word(16)
print_fractal(word)
|
Translate the given Java code snippet into Ruby without altering its behavior. | import java.util.*;
public class PenneysGame {
public static void main(String[] args) {
Random rand = new Random();
String compChoice = "", playerChoice;
if (rand.nextBoolean()) {
for (int i = 0; i < 3; i++)
compChoice += "HT".charAt(rand.nextInt(2));
System.out.printf("Computer chooses %s%n", compChoice);
playerChoice = prompt(compChoice);
} else {
playerChoice = prompt(compChoice);
compChoice = "T";
if (playerChoice.charAt(1) == 'T')
compChoice = "H";
compChoice += playerChoice.substring(0, 2);
System.out.printf("Computer chooses %s%n", compChoice);
}
String tossed = "";
while (true) {
tossed += "HT".charAt(rand.nextInt(2));
System.out.printf("Tossed %s%n" , tossed);
if (tossed.endsWith(playerChoice)) {
System.out.println("You win!");
break;
}
if (tossed.endsWith(compChoice)) {
System.out.println("Computer wins!");
break;
}
}
}
private static String prompt(String otherChoice) {
Scanner sc = new Scanner(System.in);
String s;
do {
System.out.print("Choose a sequence: ");
s = sc.nextLine().trim().toUpperCase();
} while (!s.matches("[HT]{3}") || s.equals(otherChoice));
return s;
}
}
| Toss = [:Heads, :Tails]
def yourChoice
puts "Enter your choice (H/T)"
choice = []
3.times do
until (c = $stdin.getc.upcase) == "H" or c == "T"
end
choice << (c=="H" ? Toss[0] : Toss[1])
end
puts "You chose
choice
end
loop do
puts "\n%s I start, %s you start ..... %s" % [*Toss, coin = Toss.sample]
if coin == Toss[0]
myC = Toss.shuffle << Toss.sample
puts "I chose
yC = yourChoice
else
yC = yourChoice
myC = Toss - [yC[1]] + yC.first(2)
puts "I chose
end
seq = Array.new(3){Toss.sample}
print seq.join(' ')
loop do
puts "\n I win!" or break if seq == myC
puts "\n You win!" or break if seq == yC
seq.push(Toss.sample).shift
print "
end
end
|
Port the following code from Java to Ruby with equivalent syntax and logic. | import javax.swing.*;
import java.awt.*;
class SierpinskyTriangle {
public static void main(String[] args) {
int i = 3;
if(args.length >= 1) {
try {
i = Integer.parseInt(args[0]);
}
catch(NumberFormatException e) {
System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i);
}
}
final int level = i;
JFrame frame = new JFrame("Sierpinsky Triangle - Java");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);
}
};
panel.setPreferredSize(new Dimension(400, 400));
frame.add(panel);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {
if(level <= 0) return;
g.drawLine(x, y, x+size, y);
g.drawLine(x, y, x, y+size);
g.drawLine(x+size, y, x, y+size);
drawSierpinskyTriangle(level-1, x, y, size/2, g);
drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);
drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);
}
}
| Shoes.app(:height=>540,:width=>540, :title=>"Sierpinski Triangle") do
def triangle(slot, tri, color)
x, y, len = tri
slot.append do
fill color
shape do
move_to(x,y)
dx = len * Math::cos(Math::PI/3)
dy = len * Math::sin(Math::PI/3)
line_to(x-dx, y+dy)
line_to(x+dx, y+dy)
line_to(x,y)
end
end
end
@s = stack(:width => 520, :height => 520) {}
@s.move(10,10)
length = 512
@triangles = [[length/2,0,length]]
triangle(@s, @triangles[0], rgb(0,0,0))
@n = 1
animate(1) do
if @n <= 7
@triangles = @triangles.inject([]) do |sum, (x, y, len)|
dx = len/2 * Math::cos(Math::PI/3)
dy = len/2 * Math::sin(Math::PI/3)
triangle(@s, [x, y+2*dy, -len/2], rgb(255,255,255))
sum += [[x, y, len/2], [x-dx, y+dy, len/2], [x+dx, y+dy, len/2]]
end
end
@n += 1
end
keypress do |key|
case key
when :control_q, "\x11" then exit
end
end
end
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | import javax.swing.*;
import java.awt.*;
class SierpinskyTriangle {
public static void main(String[] args) {
int i = 3;
if(args.length >= 1) {
try {
i = Integer.parseInt(args[0]);
}
catch(NumberFormatException e) {
System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i);
}
}
final int level = i;
JFrame frame = new JFrame("Sierpinsky Triangle - Java");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);
}
};
panel.setPreferredSize(new Dimension(400, 400));
frame.add(panel);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {
if(level <= 0) return;
g.drawLine(x, y, x+size, y);
g.drawLine(x, y, x, y+size);
g.drawLine(x+size, y, x, y+size);
drawSierpinskyTriangle(level-1, x, y, size/2, g);
drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);
drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);
}
}
| Shoes.app(:height=>540,:width=>540, :title=>"Sierpinski Triangle") do
def triangle(slot, tri, color)
x, y, len = tri
slot.append do
fill color
shape do
move_to(x,y)
dx = len * Math::cos(Math::PI/3)
dy = len * Math::sin(Math::PI/3)
line_to(x-dx, y+dy)
line_to(x+dx, y+dy)
line_to(x,y)
end
end
end
@s = stack(:width => 520, :height => 520) {}
@s.move(10,10)
length = 512
@triangles = [[length/2,0,length]]
triangle(@s, @triangles[0], rgb(0,0,0))
@n = 1
animate(1) do
if @n <= 7
@triangles = @triangles.inject([]) do |sum, (x, y, len)|
dx = len/2 * Math::cos(Math::PI/3)
dy = len/2 * Math::sin(Math::PI/3)
triangle(@s, [x, y+2*dy, -len/2], rgb(255,255,255))
sum += [[x, y, len/2], [x-dx, y+dy, len/2], [x+dx, y+dy, len/2]]
end
end
@n += 1
end
keypress do |key|
case key
when :control_q, "\x11" then exit
end
end
end
|
Write a version of this Java function in Ruby with identical behavior. | import java.util.*;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;
public class Nonoblock {
public static void main(String[] args) {
printBlock("21", 5);
printBlock("", 5);
printBlock("8", 10);
printBlock("2323", 15);
printBlock("23", 5);
}
static void printBlock(String data, int len) {
int sumChars = data.chars().map(c -> Character.digit(c, 10)).sum();
String[] a = data.split("");
System.out.printf("%nblocks %s, cells %s%n", Arrays.toString(a), len);
if (len - sumChars <= 0) {
System.out.println("No solution");
return;
}
List<String> prep = stream(a).filter(x -> !"".equals(x))
.map(x -> repeat(Character.digit(x.charAt(0), 10), "1"))
.collect(toList());
for (String r : genSequence(prep, len - sumChars + 1))
System.out.println(r.substring(1));
}
static List<String> genSequence(List<String> ones, int numZeros) {
if (ones.isEmpty())
return Arrays.asList(repeat(numZeros, "0"));
List<String> result = new ArrayList<>();
for (int x = 1; x < numZeros - ones.size() + 2; x++) {
List<String> skipOne = ones.stream().skip(1).collect(toList());
for (String tail : genSequence(skipOne, numZeros - x))
result.add(repeat(x, "0") + ones.get(0) + tail);
}
return result;
}
static String repeat(int n, String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
sb.append(s);
return sb.toString();
}
}
| def nonoblocks(cell, blocks)
raise 'Those blocks will not fit in those cells' if cell < blocks.inject(0,:+) + blocks.size - 1
nblock(cell, blocks, '', [])
end
def nblock(cell, blocks, position, result)
if cell <= 0
result << position[0..cell-1]
elsif blocks.empty? or blocks[0].zero?
result << position + '.' * cell
else
rest = cell - blocks.inject(:+) - blocks.size + 2
bl, *brest = blocks
rest.times.inject(result) do |res, i|
nblock(cell-i-bl-1, brest, position + '.'*i + '
end
end
end
conf = [[ 5, [2, 1]],
[ 5, []],
[10, [8]],
[15, [2, 3, 2, 3]],
[ 5, [2, 3]], ]
conf.each do |cell, blocks|
begin
puts "
result = nonoblocks(cell, blocks)
puts result, result.size, ""
rescue => e
p e
end
end
|
Translate this program into Ruby but keep the logic exactly as in Java. | import java.util.*;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;
public class Nonoblock {
public static void main(String[] args) {
printBlock("21", 5);
printBlock("", 5);
printBlock("8", 10);
printBlock("2323", 15);
printBlock("23", 5);
}
static void printBlock(String data, int len) {
int sumChars = data.chars().map(c -> Character.digit(c, 10)).sum();
String[] a = data.split("");
System.out.printf("%nblocks %s, cells %s%n", Arrays.toString(a), len);
if (len - sumChars <= 0) {
System.out.println("No solution");
return;
}
List<String> prep = stream(a).filter(x -> !"".equals(x))
.map(x -> repeat(Character.digit(x.charAt(0), 10), "1"))
.collect(toList());
for (String r : genSequence(prep, len - sumChars + 1))
System.out.println(r.substring(1));
}
static List<String> genSequence(List<String> ones, int numZeros) {
if (ones.isEmpty())
return Arrays.asList(repeat(numZeros, "0"));
List<String> result = new ArrayList<>();
for (int x = 1; x < numZeros - ones.size() + 2; x++) {
List<String> skipOne = ones.stream().skip(1).collect(toList());
for (String tail : genSequence(skipOne, numZeros - x))
result.add(repeat(x, "0") + ones.get(0) + tail);
}
return result;
}
static String repeat(int n, String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
sb.append(s);
return sb.toString();
}
}
| def nonoblocks(cell, blocks)
raise 'Those blocks will not fit in those cells' if cell < blocks.inject(0,:+) + blocks.size - 1
nblock(cell, blocks, '', [])
end
def nblock(cell, blocks, position, result)
if cell <= 0
result << position[0..cell-1]
elsif blocks.empty? or blocks[0].zero?
result << position + '.' * cell
else
rest = cell - blocks.inject(:+) - blocks.size + 2
bl, *brest = blocks
rest.times.inject(result) do |res, i|
nblock(cell-i-bl-1, brest, position + '.'*i + '
end
end
end
conf = [[ 5, [2, 1]],
[ 5, []],
[10, [8]],
[15, [2, 3, 2, 3]],
[ 5, [2, 3]], ]
conf.each do |cell, blocks|
begin
puts "
result = nonoblocks(cell, blocks)
puts result, result.size, ""
rescue => e
p e
end
end
|
Change the following Java code into Ruby without altering its purpose. | import java.util.List;
public class Main {
private static class Range {
int start;
int end;
boolean print;
public Range(int s, int e, boolean p) {
start = s;
end = e;
print = p;
}
}
public static void main(String[] args) {
List<Range> rgs = List.of(
new Range(2, 1000, true),
new Range(1000, 4000, true),
new Range(2, 10_000, false),
new Range(2, 100_000, false),
new Range(2, 1_000_000, false),
new Range(2, 10_000_000, false),
new Range(2, 100_000_000, false),
new Range(2, 1_000_000_000, false)
);
for (Range rg : rgs) {
if (rg.start == 2) {
System.out.printf("eban numbers up to and including %d\n", rg.end);
} else {
System.out.printf("eban numbers between %d and %d\n", rg.start, rg.end);
}
int count = 0;
for (int i = rg.start; i <= rg.end; ++i) {
int b = i / 1_000_000_000;
int r = i % 1_000_000_000;
int m = r / 1_000_000;
r = i % 1_000_000;
int t = r / 1_000;
r %= 1_000;
if (m >= 30 && m <= 66) m %= 10;
if (t >= 30 && t <= 66) t %= 10;
if (r >= 30 && r <= 66) r %= 10;
if (b == 0 || b == 2 || b == 4 || b == 6) {
if (m == 0 || m == 2 || m == 4 || m == 6) {
if (t == 0 || t == 2 || t == 4 || t == 6) {
if (r == 0 || r == 2 || r == 4 || r == 6) {
if (rg.print) System.out.printf("%d ", i);
count++;
}
}
}
}
}
if (rg.print) {
System.out.println();
}
System.out.printf("count = %d\n\n", count);
}
}
}
| def main
intervals = [
[2, 1000, true],
[1000, 4000, true],
[2, 10000, false],
[2, 100000, false],
[2, 1000000, false],
[2, 10000000, false],
[2, 100000000, false],
[2, 1000000000, false]
]
for intv in intervals
(start, ending, display) = intv
if start == 2 then
print "eban numbers up to and including %d:\n" % [ending]
else
print "eban numbers between %d and %d (inclusive):\n" % [start, ending]
end
count = 0
for i in (start .. ending).step(2)
b = (i / 1000000000).floor
r = (i % 1000000000)
m = (r / 1000000).floor
r = (r % 1000000)
t = (r / 1000).floor
r = (r % 1000)
if m >= 30 and m <= 66 then
m = m % 10
end
if t >= 30 and t <= 66 then
t = t % 10
end
if r >= 30 and r <= 66 then
r = r % 10
end
if b == 0 or b == 2 or b == 4 or b == 6 then
if m == 0 or m == 2 or m == 4 or m == 6 then
if t == 0 or t == 2 or t == 4 or t == 6 then
if r == 0 or r == 2 or r == 4 or r == 6 then
if display then
print ' ', i
end
count = count + 1
end
end
end
end
end
if display then
print "\n"
end
print "count = %d\n\n" % [count]
end
end
main()
|
Keep all operations the same but rewrite the snippet in Ruby. | import java.util.List;
public class Main {
private static class Range {
int start;
int end;
boolean print;
public Range(int s, int e, boolean p) {
start = s;
end = e;
print = p;
}
}
public static void main(String[] args) {
List<Range> rgs = List.of(
new Range(2, 1000, true),
new Range(1000, 4000, true),
new Range(2, 10_000, false),
new Range(2, 100_000, false),
new Range(2, 1_000_000, false),
new Range(2, 10_000_000, false),
new Range(2, 100_000_000, false),
new Range(2, 1_000_000_000, false)
);
for (Range rg : rgs) {
if (rg.start == 2) {
System.out.printf("eban numbers up to and including %d\n", rg.end);
} else {
System.out.printf("eban numbers between %d and %d\n", rg.start, rg.end);
}
int count = 0;
for (int i = rg.start; i <= rg.end; ++i) {
int b = i / 1_000_000_000;
int r = i % 1_000_000_000;
int m = r / 1_000_000;
r = i % 1_000_000;
int t = r / 1_000;
r %= 1_000;
if (m >= 30 && m <= 66) m %= 10;
if (t >= 30 && t <= 66) t %= 10;
if (r >= 30 && r <= 66) r %= 10;
if (b == 0 || b == 2 || b == 4 || b == 6) {
if (m == 0 || m == 2 || m == 4 || m == 6) {
if (t == 0 || t == 2 || t == 4 || t == 6) {
if (r == 0 || r == 2 || r == 4 || r == 6) {
if (rg.print) System.out.printf("%d ", i);
count++;
}
}
}
}
}
if (rg.print) {
System.out.println();
}
System.out.printf("count = %d\n\n", count);
}
}
}
| def main
intervals = [
[2, 1000, true],
[1000, 4000, true],
[2, 10000, false],
[2, 100000, false],
[2, 1000000, false],
[2, 10000000, false],
[2, 100000000, false],
[2, 1000000000, false]
]
for intv in intervals
(start, ending, display) = intv
if start == 2 then
print "eban numbers up to and including %d:\n" % [ending]
else
print "eban numbers between %d and %d (inclusive):\n" % [start, ending]
end
count = 0
for i in (start .. ending).step(2)
b = (i / 1000000000).floor
r = (i % 1000000000)
m = (r / 1000000).floor
r = (r % 1000000)
t = (r / 1000).floor
r = (r % 1000)
if m >= 30 and m <= 66 then
m = m % 10
end
if t >= 30 and t <= 66 then
t = t % 10
end
if r >= 30 and r <= 66 then
r = r % 10
end
if b == 0 or b == 2 or b == 4 or b == 6 then
if m == 0 or m == 2 or m == 4 or m == 6 then
if t == 0 or t == 2 or t == 4 or t == 6 then
if r == 0 or r == 2 or r == 4 or r == 6 then
if display then
print ' ', i
end
count = count + 1
end
end
end
end
end
if display then
print "\n"
end
print "count = %d\n\n" % [count]
end
end
main()
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | public class Test {
static boolean valid(int n, int nuts) {
for (int k = n; k != 0; k--, nuts -= 1 + nuts / n)
if (nuts % n != 1)
return false;
return nuts != 0 && (nuts % n == 0);
}
public static void main(String[] args) {
int x = 0;
for (int n = 2; n < 10; n++) {
while (!valid(n, x))
x++;
System.out.printf("%d: %d%n", n, x);
}
}
}
| def valid?(sailor, nuts)
sailor.times do
return false if (nuts % sailor) != 1
nuts -= 1 + nuts / sailor
end
nuts > 0 and nuts % sailor == 0
end
[5,6].each do |sailor|
n = sailor
n += 1 until valid?(sailor, n)
puts "\n
(sailor+1).times do
div, mod = n.divmod(sailor)
puts "
n -= 1 + div
end
end
|
Write the same algorithm in Ruby as shown in this Java implementation. | public class Test {
static boolean valid(int n, int nuts) {
for (int k = n; k != 0; k--, nuts -= 1 + nuts / n)
if (nuts % n != 1)
return false;
return nuts != 0 && (nuts % n == 0);
}
public static void main(String[] args) {
int x = 0;
for (int n = 2; n < 10; n++) {
while (!valid(n, x))
x++;
System.out.printf("%d: %d%n", n, x);
}
}
}
| def valid?(sailor, nuts)
sailor.times do
return false if (nuts % sailor) != 1
nuts -= 1 + nuts / sailor
end
nuts > 0 and nuts % sailor == 0
end
[5,6].each do |sailor|
n = sailor
n += 1 until valid?(sailor, n)
puts "\n
(sailor+1).times do
div, mod = n.divmod(sailor)
puts "
n -= 1 + div
end
end
|
Write a version of this Java function in Ruby with identical behavior. | import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class NauticalBell extends Thread {
public static void main(String[] args) {
NauticalBell bells = new NauticalBell();
bells.setDaemon(true);
bells.start();
try {
bells.join();
} catch (InterruptedException e) {
System.out.println(e);
}
}
@Override
public void run() {
DateFormat sdf = new SimpleDateFormat("HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
int numBells = 0;
long time = System.currentTimeMillis();
long next = time - (time % (24 * 60 * 60 * 1000));
while (next < time) {
next += 30 * 60 * 1000;
numBells = 1 + (numBells % 8);
}
while (true) {
long wait = 100L;
time = System.currentTimeMillis();
if (time - next >= 0) {
String bells = numBells == 1 ? "bell" : "bells";
String timeString = sdf.format(time);
System.out.printf("%s : %d %s\n", timeString, numBells, bells);
next += 30 * 60 * 1000;
wait = next - time;
numBells = 1 + (numBells % 8);
}
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
return;
}
}
}
}
| watches = [ "First", "Middle", "Morning", "Forenoon", "Afternoon", "First dog", "Last dog", "First" ]
watch_ends = [ "00:00", "04:00", "08:00", "12:00", "16:00", "18:00", "20:00", "23:59" ]
words = ["One","Two","Three","Four","Five","Six","Seven","Eight"]
sound = "ding!"
loop do
time = Time.now
if time.sec == 0 and time.min % 30 == 0
num = (time.hour * 60 + time.min) / 30 % 8
num = 8 if num == 0
hr_min = time.strftime "%H:%M"
idx = watch_ends.find_index {|t| hr_min <= t}
text = "%s - %s watch, %s bell%s gone" % [
hr_min,
watches[idx],
words[num-1],
num==1 ? "" : "s"
]
bells = (sound * num).gsub(sound + sound) {|dd| dd + ' '}
puts "%-45s %s" % [text, bells]
end
sleep 1
end
|
Maintain the same structure and functionality when rewriting this code in Ruby. | import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class NauticalBell extends Thread {
public static void main(String[] args) {
NauticalBell bells = new NauticalBell();
bells.setDaemon(true);
bells.start();
try {
bells.join();
} catch (InterruptedException e) {
System.out.println(e);
}
}
@Override
public void run() {
DateFormat sdf = new SimpleDateFormat("HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
int numBells = 0;
long time = System.currentTimeMillis();
long next = time - (time % (24 * 60 * 60 * 1000));
while (next < time) {
next += 30 * 60 * 1000;
numBells = 1 + (numBells % 8);
}
while (true) {
long wait = 100L;
time = System.currentTimeMillis();
if (time - next >= 0) {
String bells = numBells == 1 ? "bell" : "bells";
String timeString = sdf.format(time);
System.out.printf("%s : %d %s\n", timeString, numBells, bells);
next += 30 * 60 * 1000;
wait = next - time;
numBells = 1 + (numBells % 8);
}
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
return;
}
}
}
}
| watches = [ "First", "Middle", "Morning", "Forenoon", "Afternoon", "First dog", "Last dog", "First" ]
watch_ends = [ "00:00", "04:00", "08:00", "12:00", "16:00", "18:00", "20:00", "23:59" ]
words = ["One","Two","Three","Four","Five","Six","Seven","Eight"]
sound = "ding!"
loop do
time = Time.now
if time.sec == 0 and time.min % 30 == 0
num = (time.hour * 60 + time.min) / 30 % 8
num = 8 if num == 0
hr_min = time.strftime "%H:%M"
idx = watch_ends.find_index {|t| hr_min <= t}
text = "%s - %s watch, %s bell%s gone" % [
hr_min,
watches[idx],
words[num-1],
num==1 ? "" : "s"
]
bells = (sound * num).gsub(sound + sound) {|dd| dd + ' '}
puts "%-45s %s" % [text, bells]
end
sleep 1
end
|
Generate a Ruby translation of this Java snippet without changing its computational steps. | import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Voronoi extends JFrame {
static double p = 3;
static BufferedImage I;
static int px[], py[], color[], cells = 100, size = 1000;
public Voronoi() {
super("Voronoi Diagram");
setBounds(0, 0, size, size);
setDefaultCloseOperation(EXIT_ON_CLOSE);
int n = 0;
Random rand = new Random();
I = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
px = new int[cells];
py = new int[cells];
color = new int[cells];
for (int i = 0; i < cells; i++) {
px[i] = rand.nextInt(size);
py[i] = rand.nextInt(size);
color[i] = rand.nextInt(16777215);
}
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
n = 0;
for (byte i = 0; i < cells; i++) {
if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {
n = i;
}
}
I.setRGB(x, y, color[n]);
}
}
Graphics2D g = I.createGraphics();
g.setColor(Color.BLACK);
for (int i = 0; i < cells; i++) {
g.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));
}
try {
ImageIO.write(I, "png", new File("voronoi.png"));
} catch (IOException e) {
}
}
public void paint(Graphics g) {
g.drawImage(I, 0, 0, this);
}
static double distance(int x1, int x2, int y1, int y2) {
double d;
d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
return d;
}
public static void main(String[] args) {
new Voronoi().setVisible(true);
}
}
|
require_relative 'raster_graphics'
class ColourPixel < Pixel
def initialize(x, y, colour)
@colour = colour
super x, y
end
attr_accessor :colour
def distance_to(px, py)
Math.hypot(px - x, py - y)
end
end
width = 300
height = 200
npoints = 20
pixmap = Pixmap.new(width, height)
@bases = npoints.times.collect do |_i|
ColourPixel.new(
3 + rand(width - 6), 3 + rand(height - 6),
RGBColour.new(rand(256), rand(256), rand(256))
)
end
pixmap.each_pixel do |x, y|
nearest = @bases.min_by { |base| base.distance_to(x, y) }
pixmap[x, y] = nearest.colour
end
@bases.each do |base|
pixmap[base.x, base.y] = RGBColour::BLACK
pixmap.draw_circle(base, 2, RGBColour::BLACK)
end
pixmap.save_as_png('voronoi_rb.png')
|
Write the same algorithm in Ruby as shown in this Java implementation. | import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Voronoi extends JFrame {
static double p = 3;
static BufferedImage I;
static int px[], py[], color[], cells = 100, size = 1000;
public Voronoi() {
super("Voronoi Diagram");
setBounds(0, 0, size, size);
setDefaultCloseOperation(EXIT_ON_CLOSE);
int n = 0;
Random rand = new Random();
I = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
px = new int[cells];
py = new int[cells];
color = new int[cells];
for (int i = 0; i < cells; i++) {
px[i] = rand.nextInt(size);
py[i] = rand.nextInt(size);
color[i] = rand.nextInt(16777215);
}
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
n = 0;
for (byte i = 0; i < cells; i++) {
if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {
n = i;
}
}
I.setRGB(x, y, color[n]);
}
}
Graphics2D g = I.createGraphics();
g.setColor(Color.BLACK);
for (int i = 0; i < cells; i++) {
g.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));
}
try {
ImageIO.write(I, "png", new File("voronoi.png"));
} catch (IOException e) {
}
}
public void paint(Graphics g) {
g.drawImage(I, 0, 0, this);
}
static double distance(int x1, int x2, int y1, int y2) {
double d;
d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
return d;
}
public static void main(String[] args) {
new Voronoi().setVisible(true);
}
}
|
require_relative 'raster_graphics'
class ColourPixel < Pixel
def initialize(x, y, colour)
@colour = colour
super x, y
end
attr_accessor :colour
def distance_to(px, py)
Math.hypot(px - x, py - y)
end
end
width = 300
height = 200
npoints = 20
pixmap = Pixmap.new(width, height)
@bases = npoints.times.collect do |_i|
ColourPixel.new(
3 + rand(width - 6), 3 + rand(height - 6),
RGBColour.new(rand(256), rand(256), rand(256))
)
end
pixmap.each_pixel do |x, y|
nearest = @bases.min_by { |base| base.distance_to(x, y) }
pixmap[x, y] = nearest.colour
end
@bases.each do |base|
pixmap[base.x, base.y] = RGBColour::BLACK
pixmap.draw_circle(base, 2, RGBColour::BLACK)
end
pixmap.save_as_png('voronoi_rb.png')
|
Produce a language-to-language conversion: from Java to Ruby, same semantics. | import java.io.IOException;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
public class LdapConnectionDemo {
public static void main(String[] args) throws LdapException, IOException {
try (LdapConnection connection = new LdapNetworkConnection("localhost", 10389)) {
connection.bind();
connection.unBind();
}
}
}
| require 'rubygems'
require 'net/ldap'
ldap = Net::LDAP.new(:host => 'ldap.example.com', :base => 'o=companyname')
ldap.authenticate('bind_dn', 'bind_pass')
|
Transform the following Java implementation into Ruby, maintaining the same output and logic. | package hu.pj.alg.test;
import hu.pj.alg.BoundedKnapsack;
import hu.pj.obj.Item;
import java.util.*;
import java.text.*;
public class BoundedKnapsackForTourists {
public BoundedKnapsackForTourists() {
BoundedKnapsack bok = new BoundedKnapsack(400);
bok.add("map", 9, 150, 1);
bok.add("compass", 13, 35, 1);
bok.add("water", 153, 200, 3);
bok.add("sandwich", 50, 60, 2);
bok.add("glucose", 15, 60, 2);
bok.add("tin", 68, 45, 3);
bok.add("banana", 27, 60, 3);
bok.add("apple", 39, 40, 3);
bok.add("cheese", 23, 30, 1);
bok.add("beer", 52, 10, 3);
bok.add("suntan cream", 11, 70, 1);
bok.add("camera", 32, 30, 1);
bok.add("t-shirt", 24, 15, 2);
bok.add("trousers", 48, 10, 2);
bok.add("umbrella", 73, 40, 1);
bok.add("waterproof trousers", 42, 70, 1);
bok.add("waterproof overclothes", 43, 75, 1);
bok.add("note-case", 22, 80, 1);
bok.add("sunglasses", 7, 20, 1);
bok.add("towel", 18, 12, 2);
bok.add("socks", 4, 50, 1);
bok.add("book", 30, 10, 2);
List<Item> itemList = bok.calcSolution();
if (bok.isCalculated()) {
NumberFormat nf = NumberFormat.getInstance();
System.out.println(
"Maximal weight = " +
nf.format(bok.getMaxWeight() / 100.0) + " kg"
);
System.out.println(
"Total weight of solution = " +
nf.format(bok.getSolutionWeight() / 100.0) + " kg"
);
System.out.println(
"Total value = " +
bok.getProfit()
);
System.out.println();
System.out.println(
"You can carry te following materials " +
"in the knapsack:"
);
for (Item item : itemList) {
if (item.getInKnapsack() > 0) {
System.out.format(
"%1$-10s %2$-23s %3$-3s %4$-5s %5$-15s \n",
item.getInKnapsack() + " unit(s) ",
item.getName(),
item.getInKnapsack() * item.getWeight(), "dag ",
"(value = " + item.getInKnapsack() * item.getValue() + ")"
);
}
}
} else {
System.out.println(
"The problem is not solved. " +
"Maybe you gave wrong data."
);
}
}
public static void main(String[] args) {
new BoundedKnapsackForTourists();
}
}
| record Item, name : String, weight : Int32, value : Int32, count : Int32
record Selection, mask : Array(Int32), cur_index : Int32, total_value : Int32
class Knapsack
@threshold_value = 0
@threshold_choice : Selection?
getter checked_nodes = 0
def knapsack_step(taken, items, remaining_weight)
if taken.total_value > @threshold_value
@threshold_value = taken.total_value
@threshold_choice = taken
end
candidate_index = items.index(taken.cur_index) { |item| item.weight <= remaining_weight }
return nil unless candidate_index
@checked_nodes += 1
candidate = items[candidate_index]
return nil if taken.total_value + 1.0 * candidate.value / candidate.weight * remaining_weight < @threshold_value
max_count = {candidate.count, remaining_weight // candidate.weight}.min
(0..max_count).reverse_each do |n|
mask = taken.mask.clone
mask[candidate_index] = n
knapsack_step Selection.new(mask, candidate_index + 1, taken.total_value + n*candidate.value), items, remaining_weight - n*candidate.weight
end
end
def select(items, max_weight)
@checked_variants = 0
list = items.sort_by { |item| -1.0 * item.value / item.weight }
nothing = Selection.new(Array(Int32).new(items.size, 0), 0, 0)
@threshold_value = 0
@threshold_choice = nothing
knapsack_step(nothing, list, max_weight)
selected = @threshold_choice.not_nil!
result = Hash(Item, Int32).new(0)
selected.mask.each_with_index { |v, i| result[list[i]] = v if v > 0 }
result
end
end
possible = [
Item.new("map", 9, 150, 1),
Item.new("compass", 13, 35, 1),
Item.new("water", 153, 200, 2),
Item.new("sandwich", 50, 60, 2),
Item.new("glucose", 15, 60, 2),
Item.new("tin", 68, 45, 3),
Item.new("banana", 27, 60, 3),
Item.new("apple", 39, 40, 3),
Item.new("cheese", 23, 30, 1),
Item.new("beer", 52, 10, 3),
Item.new("suntan cream", 11, 70, 1),
Item.new("camera", 32, 30, 1),
Item.new("T-shirt", 24, 15, 2),
Item.new("trousers", 48, 10, 2),
Item.new("umbrella", 73, 40, 1),
Item.new("waterproof trousers", 42, 70, 1),
Item.new("waterproof overclothes", 43, 75, 1),
Item.new("note-case", 22, 80, 1),
Item.new("sunglasses", 7, 20, 1),
Item.new("towel", 18, 12, 2),
Item.new("socks", 4, 50, 1),
Item.new("book", 30, 10, 2),
]
solver = Knapsack.new
used = solver.select(possible, 400)
puts "optimal choice:
puts "total weight
puts "total value
puts "checked nodes:
|
Write the same code in Ruby as shown below in Java. | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Hidato {
private static int[][] board;
private static int[] given, start;
public static void main(String[] args) {
String[] input = {"_ 33 35 _ _ . . .",
"_ _ 24 22 _ . . .",
"_ _ _ 21 _ _ . .",
"_ 26 _ 13 40 11 . .",
"27 _ _ _ 9 _ 1 .",
". . _ _ 18 _ _ .",
". . . . _ 7 _ _",
". . . . . . 5 _"};
setup(input);
printBoard();
System.out.println("\nFound:");
solve(start[0], start[1], 1, 0);
printBoard();
}
private static void setup(String[] input) {
String[][] puzzle = new String[input.length][];
for (int i = 0; i < input.length; i++)
puzzle[i] = input[i].split(" ");
int nCols = puzzle[0].length;
int nRows = puzzle.length;
List<Integer> list = new ArrayList<>(nRows * nCols);
board = new int[nRows + 2][nCols + 2];
for (int[] row : board)
for (int c = 0; c < nCols + 2; c++)
row[c] = -1;
for (int r = 0; r < nRows; r++) {
String[] row = puzzle[r];
for (int c = 0; c < nCols; c++) {
String cell = row[c];
switch (cell) {
case "_":
board[r + 1][c + 1] = 0;
break;
case ".":
break;
default:
int val = Integer.parseInt(cell);
board[r + 1][c + 1] = val;
list.add(val);
if (val == 1)
start = new int[]{r + 1, c + 1};
}
}
}
Collections.sort(list);
given = new int[list.size()];
for (int i = 0; i < given.length; i++)
given[i] = list.get(i);
}
private static boolean solve(int r, int c, int n, int next) {
if (n > given[given.length - 1])
return true;
if (board[r][c] != 0 && board[r][c] != n)
return false;
if (board[r][c] == 0 && given[next] == n)
return false;
int back = board[r][c];
if (back == n)
next++;
board[r][c] = n;
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
if (solve(r + i, c + j, n + 1, next))
return true;
board[r][c] = back;
return false;
}
private static void printBoard() {
for (int[] row : board) {
for (int c : row) {
if (c == -1)
System.out.print(" . ");
else
System.out.printf(c > 0 ? "%2d " : "__ ", c);
}
System.out.println();
}
}
}
|
class Hidato
Cell = Struct.new(:value, :used, :adj)
ADJUST = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]
def initialize(board, pout=true)
@board = []
board.each_line do |line|
@board << line.split.map{|n| Cell[Integer(n), false] rescue nil} + [nil]
end
@board << []
@board.each_with_index do |row, x|
row.each_with_index do |cell, y|
if cell
@sx, @sy = x, y if cell.value==1
cell.adj = ADJUST.map{|dx,dy| [x+dx,y+dy]}.select{|xx,yy| @board[xx][yy]}
end
end
end
@xmax = @board.size - 1
@ymax = @board.map(&:size).max - 1
@end = @board.flatten.compact.size
puts to_s('Problem:') if pout
end
def solve
@zbl = Array.new(@end+1, false)
@board.flatten.compact.each{|cell| @zbl[cell.value] = true}
puts (try(@board[@sx][@sy], 1) ? to_s('Solution:') : "No solution")
end
def try(cell, seq_num)
return true if seq_num > @end
return false if cell.used
value = cell.value
return false if value > 0 and value != seq_num
return false if value == 0 and @zbl[seq_num]
cell.used = true
cell.adj.each do |x, y|
if try(@board[x][y], seq_num+1)
cell.value = seq_num
return true
end
end
cell.used = false
end
def to_s(msg=nil)
str = (0...@xmax).map do |x|
(0...@ymax).map{|y| "%3s" % ((c=@board[x][y]) ? c.value : c)}.join
end
(msg ? [msg] : []) + str + [""]
end
end
|
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version. | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Hidato {
private static int[][] board;
private static int[] given, start;
public static void main(String[] args) {
String[] input = {"_ 33 35 _ _ . . .",
"_ _ 24 22 _ . . .",
"_ _ _ 21 _ _ . .",
"_ 26 _ 13 40 11 . .",
"27 _ _ _ 9 _ 1 .",
". . _ _ 18 _ _ .",
". . . . _ 7 _ _",
". . . . . . 5 _"};
setup(input);
printBoard();
System.out.println("\nFound:");
solve(start[0], start[1], 1, 0);
printBoard();
}
private static void setup(String[] input) {
String[][] puzzle = new String[input.length][];
for (int i = 0; i < input.length; i++)
puzzle[i] = input[i].split(" ");
int nCols = puzzle[0].length;
int nRows = puzzle.length;
List<Integer> list = new ArrayList<>(nRows * nCols);
board = new int[nRows + 2][nCols + 2];
for (int[] row : board)
for (int c = 0; c < nCols + 2; c++)
row[c] = -1;
for (int r = 0; r < nRows; r++) {
String[] row = puzzle[r];
for (int c = 0; c < nCols; c++) {
String cell = row[c];
switch (cell) {
case "_":
board[r + 1][c + 1] = 0;
break;
case ".":
break;
default:
int val = Integer.parseInt(cell);
board[r + 1][c + 1] = val;
list.add(val);
if (val == 1)
start = new int[]{r + 1, c + 1};
}
}
}
Collections.sort(list);
given = new int[list.size()];
for (int i = 0; i < given.length; i++)
given[i] = list.get(i);
}
private static boolean solve(int r, int c, int n, int next) {
if (n > given[given.length - 1])
return true;
if (board[r][c] != 0 && board[r][c] != n)
return false;
if (board[r][c] == 0 && given[next] == n)
return false;
int back = board[r][c];
if (back == n)
next++;
board[r][c] = n;
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
if (solve(r + i, c + j, n + 1, next))
return true;
board[r][c] = back;
return false;
}
private static void printBoard() {
for (int[] row : board) {
for (int c : row) {
if (c == -1)
System.out.print(" . ");
else
System.out.printf(c > 0 ? "%2d " : "__ ", c);
}
System.out.println();
}
}
}
|
class Hidato
Cell = Struct.new(:value, :used, :adj)
ADJUST = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]
def initialize(board, pout=true)
@board = []
board.each_line do |line|
@board << line.split.map{|n| Cell[Integer(n), false] rescue nil} + [nil]
end
@board << []
@board.each_with_index do |row, x|
row.each_with_index do |cell, y|
if cell
@sx, @sy = x, y if cell.value==1
cell.adj = ADJUST.map{|dx,dy| [x+dx,y+dy]}.select{|xx,yy| @board[xx][yy]}
end
end
end
@xmax = @board.size - 1
@ymax = @board.map(&:size).max - 1
@end = @board.flatten.compact.size
puts to_s('Problem:') if pout
end
def solve
@zbl = Array.new(@end+1, false)
@board.flatten.compact.each{|cell| @zbl[cell.value] = true}
puts (try(@board[@sx][@sy], 1) ? to_s('Solution:') : "No solution")
end
def try(cell, seq_num)
return true if seq_num > @end
return false if cell.used
value = cell.value
return false if value > 0 and value != seq_num
return false if value == 0 and @zbl[seq_num]
cell.used = true
cell.adj.each do |x, y|
if try(@board[x][y], seq_num+1)
cell.value = seq_num
return true
end
end
cell.used = false
end
def to_s(msg=nil)
str = (0...@xmax).map do |x|
(0...@ymax).map{|y| "%3s" % ((c=@board[x][y]) ? c.value : c)}.join
end
(msg ? [msg] : []) + str + [""]
end
end
|
Preserve the algorithm and functionality while converting the code from Java to Ruby. | import java.util.Arrays;
import java.util.LinkedList;
public class Strand{
public static <E extends Comparable<? super E>>
LinkedList<E> strandSort(LinkedList<E> list){
if(list.size() <= 1) return list;
LinkedList<E> result = new LinkedList<E>();
while(list.size() > 0){
LinkedList<E> sorted = new LinkedList<E>();
sorted.add(list.removeFirst());
for(Iterator<E> it = list.iterator(); it.hasNext(); ){
E elem = it.next();
if(sorted.peekLast().compareTo(elem) <= 0){
sorted.addLast(elem);
it.remove();
}
}
result = merge(sorted, result);
}
return result;
}
private static <E extends Comparable<? super E>>
LinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){
LinkedList<E> result = new LinkedList<E>();
while(!left.isEmpty() && !right.isEmpty()){
if(left.peek().compareTo(right.peek()) <= 0)
result.add(left.remove());
else
result.add(right.remove());
}
result.addAll(left);
result.addAll(right);
return result;
}
public static void main(String[] args){
System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5))));
System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5))));
System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6))));
}
}
| class Array
def strandsort
a = dup
result = []
until a.empty?
v = a.first
sublist, a = a.partition{|val| v=val if v<=val}
result.each_index do |idx|
break if sublist.empty?
result.insert(idx, sublist.shift) if sublist.first < result[idx]
end
result += sublist
end
result
end
def strandsort!
replace(strandsort)
end
end
p [1, 6, 3, 2, 1, 7, 5, 3].strandsort
|
Please provide an equivalent version of this Java code in Ruby. | import java.text.DecimalFormat;
public class AnglesNormalizationAndConversion {
public static void main(String[] args) {
DecimalFormat formatAngle = new DecimalFormat("######0.000000");
DecimalFormat formatConv = new DecimalFormat("###0.0000");
System.out.printf(" degrees gradiens mils radians%n");
for ( double angle : new double[] {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ) {
for ( String units : new String[] {"degrees", "gradiens", "mils", "radians"}) {
double d = 0, g = 0, m = 0, r = 0;
switch (units) {
case "degrees":
d = d2d(angle);
g = d2g(d);
m = d2m(d);
r = d2r(d);
break;
case "gradiens":
g = g2g(angle);
d = g2d(g);
m = g2m(g);
r = g2r(g);
break;
case "mils":
m = m2m(angle);
d = m2d(m);
g = m2g(m);
r = m2r(m);
break;
case "radians":
r = r2r(angle);
d = r2d(r);
g = r2g(r);
m = r2m(r);
break;
}
System.out.printf("%15s %8s = %10s %10s %10s %10s%n", formatAngle.format(angle), units, formatConv.format(d), formatConv.format(g), formatConv.format(m), formatConv.format(r));
}
}
}
private static final double DEGREE = 360D;
private static final double GRADIAN = 400D;
private static final double MIL = 6400D;
private static final double RADIAN = (2 * Math.PI);
private static double d2d(double a) {
return a % DEGREE;
}
private static double d2g(double a) {
return a * (GRADIAN / DEGREE);
}
private static double d2m(double a) {
return a * (MIL / DEGREE);
}
private static double d2r(double a) {
return a * (RADIAN / 360);
}
private static double g2d(double a) {
return a * (DEGREE / GRADIAN);
}
private static double g2g(double a) {
return a % GRADIAN;
}
private static double g2m(double a) {
return a * (MIL / GRADIAN);
}
private static double g2r(double a) {
return a * (RADIAN / GRADIAN);
}
private static double m2d(double a) {
return a * (DEGREE / MIL);
}
private static double m2g(double a) {
return a * (GRADIAN / MIL);
}
private static double m2m(double a) {
return a % MIL;
}
private static double m2r(double a) {
return a * (RADIAN / MIL);
}
private static double r2d(double a) {
return a * (DEGREE / RADIAN);
}
private static double r2g(double a) {
return a * (GRADIAN / RADIAN);
}
private static double r2m(double a) {
return a * (MIL / RADIAN);
}
private static double r2r(double a) {
return a % RADIAN;
}
}
| module Angles
BASES = {"d" => 360, "g" => 400, "m" => 6400, "r" => Math::PI*2 ,"h" => 24 }
def self.method_missing(meth, angle)
from, to = BASES.values_at(*meth.to_s.split("2"))
raise NoMethodError, meth if (from.nil? or to.nil?)
mod = (angle.to_f * to / from) % to
angle < 0 ? mod - to : mod
end
end
names = Angles::BASES.keys
puts " " + "%12s "*names.size % names
test = [-2, -1, 0, 1, 2*Math::PI, 16, 360/(2*Math::PI), 360-1, 400-1, 6400-1, 1_000_000]
test.each do |n|
names.each do |first|
res = names.map{|last| Angles.send((first + "2" + last).to_sym, n)}
puts first + "%12g "*names.size % res
end
puts
end
|
Transform the following Java implementation into Ruby, maintaining the same output and logic. | import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class XMLParser {
final static String xmlStr =
"<inventory title=\"OmniCorp Store #45x10^3\">"
+ " <section name=\"health\">"
+ " <item upc=\"123456789\" stock=\"12\">"
+ " <name>Invisibility Cream</name>"
+ " <price>14.50</price>"
+ " <description>Makes you invisible</description>"
+ " </item>"
+ " <item upc=\"445322344\" stock=\"18\">"
+ " <name>Levitation Salve</name>"
+ " <price>23.99</price>"
+ " <description>Levitate yourself for up to 3 hours per application</description>"
+ " </item>"
+ " </section>"
+ " <section name=\"food\">"
+ " <item upc=\"485672034\" stock=\"653\">"
+ " <name>Blork and Freen Instameal</name>"
+ " <price>4.95</price>"
+ " <description>A tasty meal in a tablet; just add water</description>"
+ " </item>"
+ " <item upc=\"132957764\" stock=\"44\">"
+ " <name>Grob winglets</name>"
+ " <price>3.56</price>"
+ " <description>Tender winglets of Grob. Just add priwater</description>"
+ " </item>"
+ " </section>"
+ "</inventory>";
public static void main(String[] args) {
try {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(new InputSource(new StringReader(xmlStr)));
XPath xpath = XPathFactory.newInstance().newXPath();
System.out.println(((Node) xpath.evaluate(
"/inventory/section/item[1]", doc, XPathConstants.NODE))
.getAttributes().getNamedItem("upc"));
NodeList nodes = (NodeList) xpath.evaluate(
"/inventory/section/item/price", doc,
XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++)
System.out.println(nodes.item(i).getTextContent());
} catch (Exception e) {
System.out.println("Error ocurred while parsing XML.");
}
}
}
|
require "rexml/document"
include REXML
doc = Document.new(
%q@<inventory title="OmniCorp Store
...
</inventory>
@
)
invisibility = XPath.first( doc, "//item" )
XPath.each( doc, "//price") { |element| puts element.text }
names = XPath.match( doc, "//name" )
|
Keep all operations the same but rewrite the snippet in Ruby. | import java.util.*;
public class RankingMethods {
final static String[] input = {"44 Solomon", "42 Jason", "42 Errol",
"41 Garry", "41 Bernard", "41 Barry", "39 Stephen"};
public static void main(String[] args) {
int len = input.length;
Map<String, int[]> map = new TreeMap<>((a, b) -> b.compareTo(a));
for (int i = 0; i < len; i++) {
String key = input[i].split("\\s+")[0];
int[] arr;
if ((arr = map.get(key)) == null)
arr = new int[]{i, 0};
arr[1]++;
map.put(key, arr);
}
int[][] groups = map.values().toArray(new int[map.size()][]);
standardRanking(len, groups);
modifiedRanking(len, groups);
denseRanking(len, groups);
ordinalRanking(len);
fractionalRanking(len, groups);
}
private static void standardRanking(int len, int[][] groups) {
System.out.println("\nStandard ranking");
for (int i = 0, rank = 0, group = 0; i < len; i++) {
if (group < groups.length && i == groups[group][0]) {
rank = i + 1;
group++;
}
System.out.printf("%d %s%n", rank, input[i]);
}
}
private static void modifiedRanking(int len, int[][] groups) {
System.out.println("\nModified ranking");
for (int i = 0, rank = 0, group = 0; i < len; i++) {
if (group < groups.length && i == groups[group][0])
rank += groups[group++][1];
System.out.printf("%d %s%n", rank, input[i]);
}
}
private static void denseRanking(int len, int[][] groups) {
System.out.println("\nDense ranking");
for (int i = 0, rank = 0; i < len; i++) {
if (rank < groups.length && i == groups[rank][0])
rank++;
System.out.printf("%d %s%n", rank, input[i]);
}
}
private static void ordinalRanking(int len) {
System.out.println("\nOrdinal ranking");
for (int i = 0; i < len; i++)
System.out.printf("%d %s%n", i + 1, input[i]);
}
private static void fractionalRanking(int len, int[][] groups) {
System.out.println("\nFractional ranking");
float rank = 0;
for (int i = 0, tmp = 0, group = 0; i < len; i++) {
if (group < groups.length && i == groups[group][0]) {
tmp += groups[group++][1];
rank = (i + 1 + tmp) / 2.0F;
}
System.out.printf("%2.1f %s%n", rank, input[i]);
}
}
}
| ar = "44 Solomon
42 Jason
42 Errol
41 Garry
41 Bernard
41 Barry
39 Stephen".lines.map{|line| line.split}
grouped = ar.group_by{|pair| pair.shift.to_i}
s_rnk = 1
m_rnk = o_rnk = 0
puts "stand.\tmod.\tdense\tord.\tfract."
grouped.each.with_index(1) do |(score, names), d_rnk|
m_rnk += names.flatten!.size
f_rnk = (s_rnk + m_rnk)/2.0
names.each do |name|
o_rnk += 1
puts "
end
s_rnk += names.size
end
|
Transform the following Java implementation into Ruby, maintaining the same output and logic. | import java.io.*;
import java.util.*;
import java.util.regex.*;
public class UpdateConfig {
public static void main(String[] args) {
if (args[0] == null) {
System.out.println("filename required");
} else if (readConfig(args[0])) {
enableOption("seedsremoved");
disableOption("needspeeling");
setOption("numberofbananas", "1024");
addOption("numberofstrawberries", "62000");
store();
}
}
private enum EntryType {
EMPTY, ENABLED, DISABLED, COMMENT
}
private static class Entry {
EntryType type;
String name, value;
Entry(EntryType t, String n, String v) {
type = t;
name = n;
value = v;
}
}
private static Map<String, Entry> entries = new LinkedHashMap<>();
private static String path;
private static boolean readConfig(String p) {
path = p;
File f = new File(path);
if (!f.exists() || f.isDirectory())
return false;
String regexString = "^(;*)\\s*([A-Za-z0-9]+)\\s*([A-Za-z0-9]*)";
Pattern regex = Pattern.compile(regexString);
try (Scanner sc = new Scanner(new FileReader(f))){
int emptyLines = 0;
String line;
while (sc.hasNext()) {
line = sc.nextLine().trim();
if (line.isEmpty()) {
addOption("" + emptyLines++, null, EntryType.EMPTY);
} else if (line.charAt(0) == '#') {
entries.put(line, new Entry(EntryType.COMMENT, line, null));
} else {
line = line.replaceAll("[^a-zA-Z0-9\\x20;]", "");
Matcher m = regex.matcher(line);
if (m.find() && !m.group(2).isEmpty()) {
EntryType t = EntryType.ENABLED;
if (!m.group(1).isEmpty())
t = EntryType.DISABLED;
addOption(m.group(2), m.group(3), t);
}
}
}
} catch (IOException e) {
System.out.println(e);
}
return true;
}
private static void addOption(String name, String value) {
addOption(name, value, EntryType.ENABLED);
}
private static void addOption(String name, String value, EntryType t) {
name = name.toUpperCase();
entries.put(name, new Entry(t, name, value));
}
private static void enableOption(String name) {
Entry e = entries.get(name.toUpperCase());
if (e != null)
e.type = EntryType.ENABLED;
}
private static void disableOption(String name) {
Entry e = entries.get(name.toUpperCase());
if (e != null)
e.type = EntryType.DISABLED;
}
private static void setOption(String name, String value) {
Entry e = entries.get(name.toUpperCase());
if (e != null)
e.value = value;
}
private static void store() {
try (PrintWriter pw = new PrintWriter(path)) {
for (Entry e : entries.values()) {
switch (e.type) {
case EMPTY:
pw.println();
break;
case ENABLED:
pw.format("%s %s%n", e.name, e.value);
break;
case DISABLED:
pw.format("; %s %s%n", e.name, e.value);
break;
case COMMENT:
pw.println(e.name);
break;
default:
break;
}
}
if (pw.checkError()) {
throw new IOException("writing to file failed");
}
} catch (IOException e) {
System.out.println(e);
}
}
}
| require 'stringio'
class ConfigFile
def self.file(filename)
fh = File.open(filename)
obj = self.new(fh)
obj.filename = filename
fh.close
obj
end
def self.data(string)
fh = StringIO.new(string)
obj = self.new(fh)
fh.close
obj
end
def initialize(filehandle)
@lines = filehandle.readlines
@filename = nil
tidy_file
end
attr :filename
def save()
if @filename
File.open(@filename, "w") {|f| f.write(self)}
end
end
def tidy_file()
@lines.map! do |line|
line.lstrip!
if line.match(/^
line
else
line.sub!(/^;+\s+/, "; ")
if line.match(/^; \s*$/)
line = ""
else
line = line.rstrip + "\n"
if m = line.match(/^(; )?([[:upper:]]+)\s+(.*)/)
line = (m[1].nil? ? "" : m[1]) + format_line(m[2], m[3])
end
end
line
end
end
end
def format_line(option, value)
"%s%s\n" % [option.upcase.strip, value.nil? ? "" : " " + value.to_s.strip]
end
def find_option(option)
@lines.find_index {|line| line.match(/^
end
def enable_option(option)
if idx = find_option("; " + option)
@lines[idx][/^; /] = ""
end
end
def disable_option(option)
if idx = find_option(option)
@lines[idx][/^/] = "; "
end
end
def set_value(option, value)
if idx = find_option(option)
@lines[idx] = format_line(option, value)
else
@lines << format_line(option, value)
end
end
def to_s
@lines.join('')
end
end
config = ConfigFile.data(DATA.read)
config.disable_option('needspeeling')
config.enable_option('seedsremoved')
config.set_value('numberofbananas', 1024)
config.set_value('numberofstrawberries', 62000)
puts config
__END__
FAVOURITEFRUIT banana
NEEDSPEELING
;;; SEEDSREMOVED
;;;
NUMBEROFBANANAS 48
|
Keep all operations the same but rewrite the snippet in Ruby. | import java.util.HashMap;
import java.util.Map;
import java.util.regex.*;
public class StraddlingCheckerboard {
final static String[] keyvals = {"H:0", "O:1", "L:2", "M:4", "E:5", "S:6",
"R:8", "T:9", "A:30", "B:31", "C:32", "D:33", "F:34", "G:35", "I:36",
"J:37", "K:38", "N:39", "P:70", "Q:71", "U:72", "V:73", "W:74", "X:75",
"Y:76", "Z:77", ".:78", "/:79", "0:790", "1:791", "2:792", "3:793",
"4:794", "5:795", "6:796", "7:797", "8:798", "9:799"};
final static Map<String, String> val2key = new HashMap<>();
final static Map<String, String> key2val = new HashMap<>();
public static void main(String[] args) {
for (String keyval : keyvals) {
String[] kv = keyval.split(":");
val2key.put(kv[0], kv[1]);
key2val.put(kv[1], kv[0]);
}
String enc = encode("One night-it was on the twentieth of March, "
+ "1888-I was returning");
System.out.println(enc);
System.out.println(decode(enc));
}
static String encode(String s) {
StringBuilder sb = new StringBuilder();
for (String c : s.toUpperCase().split("")) {
c = val2key.get(c);
if (c != null)
sb.append(c);
}
return sb.toString();
}
static String decode(String s) {
Matcher m = Pattern.compile("(79.|3.|7.|.)").matcher(s);
StringBuilder sb = new StringBuilder();
while (m.find()) {
String v = key2val.get(m.group(1));
if (v != null)
sb.append(v);
}
return sb.toString();
}
}
| class StraddlingCheckerboard
EncodableChars = "A-Z0-9."
SortedChars = " ./" + [*"A".."Z"].join
def initialize(board = nil)
if board.nil?
rest = "BCDFGHJKLMPQUVWXYZ/.".chars.shuffle
@board = [" ESTONIAR".chars.shuffle, rest[0..9], rest[10..19]]
elsif board.chars.sort.join == SortedChars
@board = board.chars.each_slice(10).to_a
else
raise ArgumentError, "invalid
end
@row_labels = @board[0].each_with_index.select {|v, i| v == " "}.map {|v,i| i}
@mapping = {}
@board[0].each_with_index {|char, idx| @mapping[char] = idx.to_s unless char == " "}
@board[1..2].each_with_index do |row, row_idx|
row.each_with_index do |char, idx|
@mapping[char] = "%d%d" % [@row_labels[row_idx], idx]
end
end
end
def encode(message)
msg = message.upcase.delete("^
msg.chars.inject("") do |crypt, char|
crypt << (char =~ /[0-9]/ ? @mapping["/"] + char : @mapping[char])
end
end
def decode(code)
msg = ""
tokens = code.chars
until tokens.empty?
token = tokens.shift
itoken = token.to_i
unless @row_labels.include?(itoken)
msg << @board[0][itoken]
else
token2 = tokens.shift
if @mapping["/"] == token + token2
msg << tokens.shift
else
msg << @board[1+@row_labels.index(itoken)][token2.to_i]
end
end
end
msg
end
def to_s
@board.inject("") {|res, row| res << row.join}
end
def inspect
"
end
end
|
Maintain the same structure and functionality when rewriting this code in Ruby. | import java.io.BufferedReader;
import java.io.FileReader;
public class IbeforeE
{
public static void main(String[] args)
{
IbeforeE now=new IbeforeE();
String wordlist="unixdict.txt";
if(now.isPlausibleRule(wordlist))
System.out.println("Rule is plausible.");
else
System.out.println("Rule is not plausible.");
}
boolean isPlausibleRule(String filename)
{
int truecount=0,falsecount=0;
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
String word;
while((word=br.readLine())!=null)
{
if(isPlausibleWord(word))
truecount++;
else if(isOppPlausibleWord(word))
falsecount++;
}
br.close();
}
catch(Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
System.out.println("Plausible count: "+truecount);
System.out.println("Implausible count: "+falsecount);
if(truecount>2*falsecount)
return true;
return false;
}
boolean isPlausibleWord(String word)
{
if(!word.contains("c")&&word.contains("ie"))
return true;
else if(word.contains("cei"))
return true;
return false;
}
boolean isOppPlausibleWord(String word)
{
if(!word.contains("c")&&word.contains("ei"))
return true;
else if(word.contains("cie"))
return true;
return false;
}
}
| require 'open-uri'
plausibility_ratio = 2
counter = Hash.new(0)
path = 'http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'
rules = [['I before E when not preceded by C:', 'ie', 'ei'],
['E before I when preceded by C:', 'cei', 'cie']]
open(path){|f| f.each{|line| line.scan(/ie|ei|cie|cei/){|match| counter[match] += 1 }}}
overall_plausible = rules.all? do |(str, x, y)|
num_x, num_y, ratio = counter[x], counter[y], counter[x] / counter[y].to_f
plausibility = ratio > plausibility_ratio
puts str
puts "
plausibility
end
puts "Overall:
|
Write the same algorithm in Ruby as shown in this Java implementation. | import java.io.BufferedReader;
import java.io.FileReader;
public class IbeforeE
{
public static void main(String[] args)
{
IbeforeE now=new IbeforeE();
String wordlist="unixdict.txt";
if(now.isPlausibleRule(wordlist))
System.out.println("Rule is plausible.");
else
System.out.println("Rule is not plausible.");
}
boolean isPlausibleRule(String filename)
{
int truecount=0,falsecount=0;
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
String word;
while((word=br.readLine())!=null)
{
if(isPlausibleWord(word))
truecount++;
else if(isOppPlausibleWord(word))
falsecount++;
}
br.close();
}
catch(Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
System.out.println("Plausible count: "+truecount);
System.out.println("Implausible count: "+falsecount);
if(truecount>2*falsecount)
return true;
return false;
}
boolean isPlausibleWord(String word)
{
if(!word.contains("c")&&word.contains("ie"))
return true;
else if(word.contains("cei"))
return true;
return false;
}
boolean isOppPlausibleWord(String word)
{
if(!word.contains("c")&&word.contains("ei"))
return true;
else if(word.contains("cie"))
return true;
return false;
}
}
| require 'open-uri'
plausibility_ratio = 2
counter = Hash.new(0)
path = 'http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'
rules = [['I before E when not preceded by C:', 'ie', 'ei'],
['E before I when preceded by C:', 'cei', 'cie']]
open(path){|f| f.each{|line| line.scan(/ie|ei|cie|cei/){|match| counter[match] += 1 }}}
overall_plausible = rules.all? do |(str, x, y)|
num_x, num_y, ratio = counter[x], counter[y], counter[x] / counter[y].to_f
plausibility = ratio > plausibility_ratio
puts str
puts "
plausibility
end
puts "Overall:
|
Port the provided Java code into Ruby while preserving the original functionality. | import java.awt.*;
import static java.lang.Math.*;
import javax.swing.*;
public class XiaolinWu extends JPanel {
public XiaolinWu() {
Dimension dim = new Dimension(640, 640);
setPreferredSize(dim);
setBackground(Color.white);
}
void plot(Graphics2D g, double x, double y, double c) {
g.setColor(new Color(0f, 0f, 0f, (float)c));
g.fillOval((int) x, (int) y, 2, 2);
}
int ipart(double x) {
return (int) x;
}
double fpart(double x) {
return x - floor(x);
}
double rfpart(double x) {
return 1.0 - fpart(x);
}
void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) {
boolean steep = abs(y1 - y0) > abs(x1 - x0);
if (steep)
drawLine(g, y0, x0, y1, x1);
if (x0 > x1)
drawLine(g, x1, y1, x0, y0);
double dx = x1 - x0;
double dy = y1 - y0;
double gradient = dy / dx;
double xend = round(x0);
double yend = y0 + gradient * (xend - x0);
double xgap = rfpart(x0 + 0.5);
double xpxl1 = xend;
double ypxl1 = ipart(yend);
if (steep) {
plot(g, ypxl1, xpxl1, rfpart(yend) * xgap);
plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap);
} else {
plot(g, xpxl1, ypxl1, rfpart(yend) * xgap);
plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap);
}
double intery = yend + gradient;
xend = round(x1);
yend = y1 + gradient * (xend - x1);
xgap = fpart(x1 + 0.5);
double xpxl2 = xend;
double ypxl2 = ipart(yend);
if (steep) {
plot(g, ypxl2, xpxl2, rfpart(yend) * xgap);
plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap);
} else {
plot(g, xpxl2, ypxl2, rfpart(yend) * xgap);
plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap);
}
for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) {
if (steep) {
plot(g, ipart(intery), x, rfpart(intery));
plot(g, ipart(intery) + 1, x, fpart(intery));
} else {
plot(g, x, ipart(intery), rfpart(intery));
plot(g, x, ipart(intery) + 1, fpart(intery));
}
intery = intery + gradient;
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
drawLine(g, 550, 170, 50, 435);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Xiaolin Wu's line algorithm");
f.setResizable(false);
f.add(new XiaolinWu(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
| def ipart(n); n.truncate; end
def fpart(n); n - ipart(n); end
def rfpart(n); 1.0 - fpart(n); end
class Pixmap
def draw_line_antialised(p1, p2, colour)
x1, y1 = p1.x, p1.y
x2, y2 = p2.x, p2.y
steep = (y2 - y1).abs > (x2 - x1).abs
if steep
x1, y1 = y1, x1
x2, y2 = y2, x2
end
if x1 > x2
x1, x2 = x2, x1
y1, y2 = y2, y1
end
deltax = x2 - x1
deltay = (y2 - y1).abs
gradient = 1.0 * deltay / deltax
xend = x1.round
yend = y1 + gradient * (xend - x1)
xgap = rfpart(x1 + 0.5)
xpxl1 = xend
ypxl1 = ipart(yend)
put_colour(xpxl1, ypxl1, colour, steep, rfpart(yend)*xgap)
put_colour(xpxl1, ypxl1 + 1, colour, steep, fpart(yend)*xgap)
itery = yend + gradient
xend = x2.round
yend = y2 + gradient * (xend - x2)
xgap = rfpart(x2 + 0.5)
xpxl2 = xend
ypxl2 = ipart(yend)
put_colour(xpxl2, ypxl2, colour, steep, rfpart(yend)*xgap)
put_colour(xpxl2, ypxl2 + 1, colour, steep, fpart(yend)*xgap)
(xpxl1 + 1).upto(xpxl2 - 1).each do |x|
put_colour(x, ipart(itery), colour, steep, rfpart(itery))
put_colour(x, ipart(itery) + 1, colour, steep, fpart(itery))
itery = itery + gradient
end
end
def put_colour(x, y, colour, steep, c)
x, y = y, x if steep
self[x, y] = anti_alias(colour, self[x, y], c)
end
def anti_alias(new, old, ratio)
blended = new.values.zip(old.values).map {|n, o| (n*ratio + o*(1.0 - ratio)).round}
RGBColour.new(*blended)
end
end
bitmap = Pixmap.new(500, 500)
bitmap.fill(RGBColour::BLUE)
10.step(430, 60) do |a|
bitmap.draw_line_antialised(Pixel[10, 10], Pixel[490,a], RGBColour::YELLOW)
bitmap.draw_line_antialised(Pixel[10, 10], Pixel[a,490], RGBColour::YELLOW)
end
bitmap.draw_line_antialised(Pixel[10, 10], Pixel[490,490], RGBColour::YELLOW)
|
Transform the following Java implementation into Ruby, maintaining the same output and logic. | import java.math.BigInteger;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class NextHighestIntFromDigits {
public static void main(String[] args) {
for ( String s : new String[] {"0", "9", "12", "21", "12453", "738440", "45072010", "95322020", "9589776899767587796600", "3345333"} ) {
System.out.printf("%s -> %s%n", format(s), format(next(s)));
}
testAll("12345");
testAll("11122");
}
private static NumberFormat FORMAT = NumberFormat.getNumberInstance();
private static String format(String s) {
return FORMAT.format(new BigInteger(s));
}
private static void testAll(String s) {
System.out.printf("Test all permutations of: %s%n", s);
String sOrig = s;
String sPrev = s;
int count = 1;
boolean orderOk = true;
Map <String,Integer> uniqueMap = new HashMap<>();
uniqueMap.put(s, 1);
while ( (s = next(s)).compareTo("0") != 0 ) {
count++;
if ( Long.parseLong(s) < Long.parseLong(sPrev) ) {
orderOk = false;
}
uniqueMap.merge(s, 1, (v1, v2) -> v1 + v2);
sPrev = s;
}
System.out.printf(" Order: OK = %b%n", orderOk);
String reverse = new StringBuilder(sOrig).reverse().toString();
System.out.printf(" Last permutation: Actual = %s, Expected = %s, OK = %b%n", sPrev, reverse, sPrev.compareTo(reverse) == 0);
boolean unique = true;
for ( String key : uniqueMap.keySet() ) {
if ( uniqueMap.get(key) > 1 ) {
unique = false;
}
}
System.out.printf(" Permutations unique: OK = %b%n", unique);
Map<Character,Integer> charMap = new HashMap<>();
for ( char c : sOrig.toCharArray() ) {
charMap.merge(c, 1, (v1, v2) -> v1 + v2);
}
long permCount = factorial(sOrig.length());
for ( char c : charMap.keySet() ) {
permCount /= factorial(charMap.get(c));
}
System.out.printf(" Permutation count: Actual = %d, Expected = %d, OK = %b%n", count, permCount, count == permCount);
}
private static long factorial(long n) {
long fact = 1;
for (long num = 2 ; num <= n ; num++ ) {
fact *= num;
}
return fact;
}
private static String next(String s) {
StringBuilder sb = new StringBuilder();
int index = s.length()-1;
while ( index > 0 && s.charAt(index-1) >= s.charAt(index)) {
index--;
}
if ( index == 0 ) {
return "0";
}
int index2 = index;
for ( int i = index + 1 ; i < s.length() ; i++ ) {
if ( s.charAt(i) < s.charAt(index2) && s.charAt(i) > s.charAt(index-1) ) {
index2 = i;
}
}
if ( index > 1 ) {
sb.append(s.subSequence(0, index-1));
}
sb.append(s.charAt(index2));
List<Character> chars = new ArrayList<>();
chars.add(s.charAt(index-1));
for ( int i = index ; i < s.length() ; i++ ) {
if ( i != index2 ) {
chars.add(s.charAt(i));
}
}
Collections.sort(chars);
for ( char c : chars ) {
sb.append(c);
}
return sb.toString();
}
}
| func next_from_digits(n, b = 10) {
var a = n.digits(b).flip
while (a.next_permutation) {
with (a.flip.digits2num(b)) { |t|
return t if (t > n)
}
}
return 0
}
say 'Next largest integer able to be made from these digits, or zero if no larger exists:'
for n in (
0, 9, 12, 21, 12453, 738440, 3345333, 45072010,
95322020, 982765431, 9589776899767587796600,
) {
printf("%30s -> %s\n", n, next_from_digits(n))
}
|
Port the provided Java code into Ruby while preserving the original functionality. | import java.math.BigInteger;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class NextHighestIntFromDigits {
public static void main(String[] args) {
for ( String s : new String[] {"0", "9", "12", "21", "12453", "738440", "45072010", "95322020", "9589776899767587796600", "3345333"} ) {
System.out.printf("%s -> %s%n", format(s), format(next(s)));
}
testAll("12345");
testAll("11122");
}
private static NumberFormat FORMAT = NumberFormat.getNumberInstance();
private static String format(String s) {
return FORMAT.format(new BigInteger(s));
}
private static void testAll(String s) {
System.out.printf("Test all permutations of: %s%n", s);
String sOrig = s;
String sPrev = s;
int count = 1;
boolean orderOk = true;
Map <String,Integer> uniqueMap = new HashMap<>();
uniqueMap.put(s, 1);
while ( (s = next(s)).compareTo("0") != 0 ) {
count++;
if ( Long.parseLong(s) < Long.parseLong(sPrev) ) {
orderOk = false;
}
uniqueMap.merge(s, 1, (v1, v2) -> v1 + v2);
sPrev = s;
}
System.out.printf(" Order: OK = %b%n", orderOk);
String reverse = new StringBuilder(sOrig).reverse().toString();
System.out.printf(" Last permutation: Actual = %s, Expected = %s, OK = %b%n", sPrev, reverse, sPrev.compareTo(reverse) == 0);
boolean unique = true;
for ( String key : uniqueMap.keySet() ) {
if ( uniqueMap.get(key) > 1 ) {
unique = false;
}
}
System.out.printf(" Permutations unique: OK = %b%n", unique);
Map<Character,Integer> charMap = new HashMap<>();
for ( char c : sOrig.toCharArray() ) {
charMap.merge(c, 1, (v1, v2) -> v1 + v2);
}
long permCount = factorial(sOrig.length());
for ( char c : charMap.keySet() ) {
permCount /= factorial(charMap.get(c));
}
System.out.printf(" Permutation count: Actual = %d, Expected = %d, OK = %b%n", count, permCount, count == permCount);
}
private static long factorial(long n) {
long fact = 1;
for (long num = 2 ; num <= n ; num++ ) {
fact *= num;
}
return fact;
}
private static String next(String s) {
StringBuilder sb = new StringBuilder();
int index = s.length()-1;
while ( index > 0 && s.charAt(index-1) >= s.charAt(index)) {
index--;
}
if ( index == 0 ) {
return "0";
}
int index2 = index;
for ( int i = index + 1 ; i < s.length() ; i++ ) {
if ( s.charAt(i) < s.charAt(index2) && s.charAt(i) > s.charAt(index-1) ) {
index2 = i;
}
}
if ( index > 1 ) {
sb.append(s.subSequence(0, index-1));
}
sb.append(s.charAt(index2));
List<Character> chars = new ArrayList<>();
chars.add(s.charAt(index-1));
for ( int i = index ; i < s.length() ; i++ ) {
if ( i != index2 ) {
chars.add(s.charAt(i));
}
}
Collections.sort(chars);
for ( char c : chars ) {
sb.append(c);
}
return sb.toString();
}
}
| func next_from_digits(n, b = 10) {
var a = n.digits(b).flip
while (a.next_permutation) {
with (a.flip.digits2num(b)) { |t|
return t if (t > n)
}
}
return 0
}
say 'Next largest integer able to be made from these digits, or zero if no larger exists:'
for n in (
0, 9, 12, 21, 12453, 738440, 3345333, 45072010,
95322020, 982765431, 9589776899767587796600,
) {
printf("%30s -> %s\n", n, next_from_digits(n))
}
|
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version. | public class FourIsMagic {
public static void main(String[] args) {
for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) {
String magic = fourIsMagic(n);
System.out.printf("%d = %s%n", n, toSentence(magic));
}
}
private static final String toSentence(String s) {
return s.substring(0,1).toUpperCase() + s.substring(1) + ".";
}
private static final String[] nums = new String[] {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
private static final String fourIsMagic(long n) {
if ( n == 4 ) {
return numToString(n) + " is magic";
}
String result = numToString(n);
return result + " is " + numToString(result.length()) + ", " + fourIsMagic(result.length());
}
private static final String numToString(long n) {
if ( n < 0 ) {
return "negative " + numToString(-n);
}
int index = (int) n;
if ( n <= 19 ) {
return nums[index];
}
if ( n <= 99 ) {
return tens[index/10] + (n % 10 > 0 ? " " + numToString(n % 10) : "");
}
String label = null;
long factor = 0;
if ( n <= 999 ) {
label = "hundred";
factor = 100;
}
else if ( n <= 999999) {
label = "thousand";
factor = 1000;
}
else if ( n <= 999999999) {
label = "million";
factor = 1000000;
}
else if ( n <= 999999999999L) {
label = "billion";
factor = 1000000000;
}
else if ( n <= 999999999999999L) {
label = "trillion";
factor = 1000000000000L;
}
else if ( n <= 999999999999999999L) {
label = "quadrillion";
factor = 1000000000000000L;
}
else {
label = "quintillion";
factor = 1000000000000000000L;
}
return numToString(n / factor) + " " + label + (n % factor > 0 ? " " + numToString(n % factor ) : "");
}
}
| module NumberToWord
NUMBERS = {
1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four',
5 => 'five',
6 => 'six',
7 => 'seven',
8 => 'eight',
9 => 'nine',
10 => 'ten',
11 => 'eleven',
12 => 'twelve',
13 => 'thirteen',
14 => 'fourteen',
15 => 'fifteen',
16 => 'sixteen',
17 => 'seventeen',
18 => 'eighteen',
19 => 'nineteen',
20 => 'twenty',
30 => 'thirty',
40 => 'forty',
50 => 'fifty',
60 => 'sixty',
70 => 'seventy',
80 => 'eighty',
90 => 'ninety',
100 => 'hundred',
1000 => 'thousand',
10 ** 6 => 'million',
10 ** 9 => 'billion',
10 ** 12 => 'trillion',
10 ** 15 => 'quadrillion',
10 ** 18 => 'quintillion',
10 ** 21 => 'sextillion',
10 ** 24 => 'septillion',
10 ** 27 => 'octillion',
10 ** 30 => 'nonillion',
10 ** 33 => 'decillion'}.reverse_each.to_h
refine Integer do
def to_english
return 'zero' if i.zero?
words = self < 0 ? ['negative'] : []
i = self.abs
NUMBERS.each do |k, v|
if k <= i then
times = i/k
words << times.to_english if k >= 100
words << v
i -= times * k
end
return words.join(" ") if i.zero?
end
end
end
end
using NumberToWord
def magic4(n)
words = []
until n == 4
s = n.to_english
n = s.size
words << "
end
words << "four is magic."
words.join(", ").capitalize
end
[0, 4, 6, 11, 13, 75, 337, -164, 9_876_543_209].each{|n| puts magic4(n) }
|
Ensure the translated Ruby code behaves exactly like the original Java snippet. | import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.geom.Path2D;
import static java.lang.Math.*;
import java.util.Random;
import javax.swing.*;
public class SierpinskiPentagon extends JPanel {
final double degrees072 = toRadians(72);
final double scaleFactor = 1 / (2 + cos(degrees072) * 2);
final int margin = 20;
int limit = 0;
Random r = new Random();
public SierpinskiPentagon() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
new Timer(3000, (ActionEvent e) -> {
limit++;
if (limit >= 5)
limit = 0;
repaint();
}).start();
}
void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {
double angle = 3 * degrees072;
if (depth == 0) {
Path2D p = new Path2D.Double();
p.moveTo(x, y);
for (int i = 0; i < 5; i++) {
x = x + cos(angle) * side;
y = y - sin(angle) * side;
p.lineTo(x, y);
angle += degrees072;
}
g.setColor(RandomHue.next());
g.fill(p);
} else {
side *= scaleFactor;
double distance = side + side * cos(degrees072) * 2;
for (int i = 0; i < 5; i++) {
x = x + cos(angle) * distance;
y = y - sin(angle) * distance;
drawPentagon(g, x, y, side, depth - 1);
angle += degrees072;
}
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
double radius = w / 2 - 2 * margin;
double side = radius * sin(PI / 5) * 2;
drawPentagon(g, w / 2, 3 * margin, side, limit);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Sierpinski Pentagon");
f.setResizable(true);
f.add(new SierpinskiPentagon(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
class RandomHue {
final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;
private static double hue = Math.random();
static Color next() {
hue = (hue + goldenRatioConjugate) % 1;
return Color.getHSBColor((float) hue, 1, 1);
}
}
| THETA = Math::PI * 2 / 5
SCALE_FACTOR = (3 - Math.sqrt(5)) / 2
MARGIN = 20
attr_reader :pentagons, :renderer
def settings
size(400, 400)
end
def setup
sketch_title 'Pentaflake'
radius = width / 2 - 2 * MARGIN
center = Vec2D.new(radius - 2 * MARGIN, 3 * MARGIN)
pentaflake = Pentaflake.new(center, radius, 5)
@pentagons = pentaflake.pentagons
end
def draw
background(255)
stroke(0)
pentagons.each do |penta|
draw_pentagon(penta)
end
no_loop
end
def draw_pentagon(pent)
points = pent.vertices
begin_shape
points.each do |pnt|
pnt.to_vertex(renderer)
end
end_shape(CLOSE)
end
def renderer
@renderer ||= GfxRender.new(self.g)
end
class Pentaflake
attr_reader :pentagons
def initialize(center, radius, depth)
@pentagons = []
create_pentagons(center, radius, depth)
end
def create_pentagons(center, radius, depth)
if depth.zero?
pentagons << Pentagon.new(center, radius)
else
radius *= SCALE_FACTOR
distance = radius * Math.sin(THETA) * 2
(0..4).each do |idx|
x = center.x + Math.cos(idx * THETA) * distance
y = center.y + Math.sin(idx * THETA) * distance
center = Vec2D.new(x, y)
create_pentagons(center, radius, depth - 1)
end
end
end
end
class Pentagon
attr_reader :center, :radius
def initialize(center, radius)
@center = center
@radius = radius
end
def vertices
(0..4).map do |idx|
center + Vec2D.new(radius * Math.sin(THETA * idx), radius * Math.cos(THETA * idx))
end
end
end
|
Maintain the same structure and functionality when rewriting this code in Ruby. | import java.awt.Point;
import java.util.*;
public class ZhangSuen {
final static String[] image = {
" ",
" ################# ############# ",
" ################## ################ ",
" ################### ################## ",
" ######## ####### ################### ",
" ###### ####### ####### ###### ",
" ###### ####### ####### ",
" ################# ####### ",
" ################ ####### ",
" ################# ####### ",
" ###### ####### ####### ",
" ###### ####### ####### ",
" ###### ####### ####### ###### ",
" ######## ####### ################### ",
" ######## ####### ###### ################## ###### ",
" ######## ####### ###### ################ ###### ",
" ######## ####### ###### ############# ###### ",
" "};
final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1},
{-1, 1}, {-1, 0}, {-1, -1}, {0, -1}};
final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6},
{0, 4, 6}}};
static List<Point> toWhite = new ArrayList<>();
static char[][] grid;
public static void main(String[] args) {
grid = new char[image.length][];
for (int r = 0; r < image.length; r++)
grid[r] = image[r].toCharArray();
thinImage();
}
static void thinImage() {
boolean firstStep = false;
boolean hasChanged;
do {
hasChanged = false;
firstStep = !firstStep;
for (int r = 1; r < grid.length - 1; r++) {
for (int c = 1; c < grid[0].length - 1; c++) {
if (grid[r][c] != '#')
continue;
int nn = numNeighbors(r, c);
if (nn < 2 || nn > 6)
continue;
if (numTransitions(r, c) != 1)
continue;
if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1))
continue;
toWhite.add(new Point(c, r));
hasChanged = true;
}
}
for (Point p : toWhite)
grid[p.y][p.x] = ' ';
toWhite.clear();
} while (firstStep || hasChanged);
printResult();
}
static int numNeighbors(int r, int c) {
int count = 0;
for (int i = 0; i < nbrs.length - 1; i++)
if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#')
count++;
return count;
}
static int numTransitions(int r, int c) {
int count = 0;
for (int i = 0; i < nbrs.length - 1; i++)
if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {
if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#')
count++;
}
return count;
}
static boolean atLeastOneIsWhite(int r, int c, int step) {
int count = 0;
int[][] group = nbrGroups[step];
for (int i = 0; i < 2; i++)
for (int j = 0; j < group[i].length; j++) {
int[] nbr = nbrs[group[i][j]];
if (grid[r + nbr[1]][c + nbr[0]] == ' ') {
count++;
break;
}
}
return count > 1;
}
static void printResult() {
for (char[] row : grid)
System.out.println(row);
}
}
| class ZhangSuen
NEIGHBOUR8 = [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]]
CIRCULARS = NEIGHBOUR8 + [NEIGHBOUR8.first]
def initialize(str, black="
s1 = str.each_line.map{|line| line.chomp.each_char.map{|c| c==black ? 1 : 0}}
s2 = s1.map{|line| line.map{0}}
xrange = 1 ... s1.size-1
yrange = 1 ... s1[0].size-1
printout(s1)
begin
@r = 0
xrange.each{|x| yrange.each{|y| s2[x][y] = s1[x][y] - zs(s1,x,y,1)}}
xrange.each{|x| yrange.each{|y| s1[x][y] = s2[x][y] - zs(s2,x,y,0)}}
end until @r == 0
printout(s1)
end
def zs(ng,x,y,g)
return 0 if ng[x][y] == 0 or
(ng[x-1][y] + ng[x][y+1] + ng[x+g][y-1+g]) == 3 or
(ng[x-1+g][y+g] + ng[x+1][y] + ng[x][y-1]) == 3
bp1 = NEIGHBOUR8.inject(0){|res,(i,j)| res += ng[x+i][y+j]}
return 0 if bp1 < 2 or 6 < bp1
ap1 = CIRCULARS.map{|i,j| ng[x+i][y+j]}.each_cons(2).count{|a,b| a<b}
return 0 if ap1 != 1
@r = 1
end
def printout(image)
puts image.map{|row| row.map{|col| "
end
end
str = <<EOS
...........................................................
.
.
.
.
...
...
...
...
...
...
...
...
.
.
.
.
...........................................................
EOS
ZhangSuen.new(str)
task_example = <<EOS
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
EOS
ZhangSuen.new(task_example, "1")
|
Keep all operations the same but rewrite the snippet in Ruby. | import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Chess960{
private static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R');
public static List<Character> generateFirstRank(){
do{
Collections.shuffle(pieces);
}while(!check(pieces.toString().replaceAll("[^\\p{Upper}]", "")));
return pieces;
}
private static boolean check(String rank){
if(!rank.matches(".*R.*K.*R.*")) return false;
if(!rank.matches(".*B(..|....|......|)B.*")) return false;
return true;
}
public static void main(String[] args){
for(int i = 0; i < 10; i++){
System.out.println(generateFirstRank());
}
}
}
| pieces = %i(♔ ♕ ♘ ♘ ♗ ♗ ♖ ♖)
regexes = [/♗(..)*♗/, /♖.*♔.*♖/]
row = pieces.shuffle.join until regexes.all?{|re| re.match(row)}
puts row
|
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version. | import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
public class UPC {
private static final int SEVEN = 7;
private static final Map<String, Integer> LEFT_DIGITS = Map.of(
" ## #", 0,
" ## #", 1,
" # ##", 2,
" #### #", 3,
" # ##", 4,
" ## #", 5,
" # ####", 6,
" ### ##", 7,
" ## ###", 8,
" # ##", 9
);
private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()
.stream()
.collect(Collectors.toMap(
entry -> entry.getKey()
.replace(' ', 's')
.replace('#', ' ')
.replace('s', '#'),
Map.Entry::getValue
));
private static final String END_SENTINEL = "# #";
private static final String MID_SENTINEL = " # # ";
private static void decodeUPC(String input) {
Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {
int pos = 0;
var part = candidate.substring(pos, pos + END_SENTINEL.length());
List<Integer> output = new ArrayList<>();
if (END_SENTINEL.equals(part)) {
pos += END_SENTINEL.length();
} else {
return Map.entry(false, output);
}
for (int i = 1; i < SEVEN; i++) {
part = candidate.substring(pos, pos + SEVEN);
pos += SEVEN;
if (LEFT_DIGITS.containsKey(part)) {
output.add(LEFT_DIGITS.get(part));
} else {
return Map.entry(false, output);
}
}
part = candidate.substring(pos, pos + MID_SENTINEL.length());
if (MID_SENTINEL.equals(part)) {
pos += MID_SENTINEL.length();
} else {
return Map.entry(false, output);
}
for (int i = 1; i < SEVEN; i++) {
part = candidate.substring(pos, pos + SEVEN);
pos += SEVEN;
if (RIGHT_DIGITS.containsKey(part)) {
output.add(RIGHT_DIGITS.get(part));
} else {
return Map.entry(false, output);
}
}
part = candidate.substring(pos, pos + END_SENTINEL.length());
if (!END_SENTINEL.equals(part)) {
return Map.entry(false, output);
}
int sum = 0;
for (int i = 0; i < output.size(); i++) {
if (i % 2 == 0) {
sum += 3 * output.get(i);
} else {
sum += output.get(i);
}
}
return Map.entry(sum % 10 == 0, output);
};
Consumer<List<Integer>> printList = list -> {
var it = list.iterator();
System.out.print('[');
if (it.hasNext()) {
System.out.print(it.next());
}
while (it.hasNext()) {
System.out.print(", ");
System.out.print(it.next());
}
System.out.print(']');
};
var candidate = input.trim();
var out = decode.apply(candidate);
if (out.getKey()) {
printList.accept(out.getValue());
System.out.println();
} else {
StringBuilder builder = new StringBuilder(candidate);
builder.reverse();
out = decode.apply(builder.toString());
if (out.getKey()) {
printList.accept(out.getValue());
System.out.println(" Upside down");
} else if (out.getValue().size() == 12) {
System.out.println("Invalid checksum");
} else {
System.out.println("Invalid digit(s)");
}
}
}
public static void main(String[] args) {
var barcodes = List.of(
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "
);
barcodes.forEach(UPC::decodeUPC);
}
}
| DIGIT_F = {
"
"
"
"
"
"
"
"
"
"
}
DIGIT_R = {
"
"
"
"
"
"
"
"
"
"
}
END_SENTINEL = "
MID_SENTINEL = "
def decode_upc(s)
def decode_upc_impl(input)
upc = input.strip
if upc.length != 95 then
return false
end
pos = 0
digits = []
sum = 0
if upc[pos .. pos + 2] == END_SENTINEL then
pos += 3
else
return false
end
for i in 0 .. 5
digit = DIGIT_F[upc[pos .. pos + 6]]
if digit == nil then
return false
else
digits.push(digit)
sum += digit * [1, 3][digits.length % 2]
pos += 7
end
end
if upc[pos .. pos + 4] == MID_SENTINEL then
pos += 5
else
return false
end
for i in 0 .. 5
digit = DIGIT_R[upc[pos .. pos + 6]]
if digit == nil then
return false
else
digits.push(digit)
sum += digit * [1, 3][digits.length % 2]
pos += 7
end
end
if upc[pos .. pos + 2] == END_SENTINEL then
pos += 3
else
return false
end
if sum % 10 == 0 then
print digits, " "
return true
else
print "Failed Checksum "
return false
end
end
if decode_upc_impl(s) then
puts "Rightside Up"
elsif decode_upc_impl(s.reverse) then
puts "Upside Down"
else
puts "Invalid digit(s)"
end
end
def main
num = 0
print "%2d: " % [num += 1]
decode_upc("
print "%2d: " % [num += 1]
decode_upc("
print "%2d: " % [num += 1]
decode_upc("
print "%2d: " % [num += 1]
decode_upc("
print "%2d: " % [num += 1]
decode_upc("
print "%2d: " % [num += 1]
decode_upc("
print "%2d: " % [num += 1]
decode_upc("
print "%2d: " % [num += 1]
decode_upc("
print "%2d: " % [num += 1]
decode_upc("
print "%2d: " % [num += 1]
decode_upc("
end
main()
|
Port the provided Java code into Ruby while preserving the original functionality. | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class WriteToWindowsEventLog {
public static void main(String[] args) throws IOException, InterruptedException {
String osName = System.getProperty("os.name").toUpperCase(Locale.ENGLISH);
if (!osName.startsWith("WINDOWS")) {
System.err.println("Not windows");
return;
}
Process process = Runtime.getRuntime().exec("EventCreate /t INFORMATION /id 123 /l APPLICATION /so Java /d \"Rosetta Code Example\"");
process.waitFor(10, TimeUnit.SECONDS);
int exitValue = process.exitValue();
System.out.printf("Process exited with value %d\n", exitValue);
if (exitValue != 0) {
InputStream errorStream = process.getErrorStream();
String result = new BufferedReader(new InputStreamReader(errorStream))
.lines()
.collect(Collectors.joining("\n"));
System.err.println(result);
}
}
}
| require 'win32/eventlog'
logger = Win32::EventLog.new
logger.report_event(:event_type => Win32::EventLog::INFO, :data => "a test event log entry")
|
Convert this Java snippet to Ruby and keep its semantics consistent. | import java.util.HashMap;
import java.util.Map;
public class SpellingOfOrdinalNumbers {
public static void main(String[] args) {
for ( long test : new long[] {1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003L} ) {
System.out.printf("%d = %s%n", test, toOrdinal(test));
}
}
private static Map<String,String> ordinalMap = new HashMap<>();
static {
ordinalMap.put("one", "first");
ordinalMap.put("two", "second");
ordinalMap.put("three", "third");
ordinalMap.put("five", "fifth");
ordinalMap.put("eight", "eighth");
ordinalMap.put("nine", "ninth");
ordinalMap.put("twelve", "twelfth");
}
private static String toOrdinal(long n) {
String spelling = numToString(n);
String[] split = spelling.split(" ");
String last = split[split.length - 1];
String replace = "";
if ( last.contains("-") ) {
String[] lastSplit = last.split("-");
String lastWithDash = lastSplit[1];
String lastReplace = "";
if ( ordinalMap.containsKey(lastWithDash) ) {
lastReplace = ordinalMap.get(lastWithDash);
}
else if ( lastWithDash.endsWith("y") ) {
lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + "ieth";
}
else {
lastReplace = lastWithDash + "th";
}
replace = lastSplit[0] + "-" + lastReplace;
}
else {
if ( ordinalMap.containsKey(last) ) {
replace = ordinalMap.get(last);
}
else if ( last.endsWith("y") ) {
replace = last.substring(0, last.length() - 1) + "ieth";
}
else {
replace = last + "th";
}
}
split[split.length - 1] = replace;
return String.join(" ", split);
}
private static final String[] nums = new String[] {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
private static final String numToString(long n) {
return numToStringHelper(n);
}
private static final String numToStringHelper(long n) {
if ( n < 0 ) {
return "negative " + numToStringHelper(-n);
}
int index = (int) n;
if ( n <= 19 ) {
return nums[index];
}
if ( n <= 99 ) {
return tens[index/10] + (n % 10 > 0 ? "-" + numToStringHelper(n % 10) : "");
}
String label = null;
long factor = 0;
if ( n <= 999 ) {
label = "hundred";
factor = 100;
}
else if ( n <= 999999) {
label = "thousand";
factor = 1000;
}
else if ( n <= 999999999) {
label = "million";
factor = 1000000;
}
else if ( n <= 999999999999L) {
label = "billion";
factor = 1000000000;
}
else if ( n <= 999999999999999L) {
label = "trillion";
factor = 1000000000000L;
}
else if ( n <= 999999999999999999L) {
label = "quadrillion";
factor = 1000000000000000L;
}
else {
label = "quintillion";
factor = 1000000000000000000L;
}
return numToStringHelper(n / factor) + " " + label + (n % factor > 0 ? " " + numToStringHelper(n % factor ) : "");
}
}
| var lingua_en = frequire('Lingua::EN::Numbers')
var tests = [1,2,3,4,5,11,65,100,101,272,23456,8007006005004003]
tests.each {|n|
printf("%16s : %s\n", n, lingua_en.num2en_ordinal(n))
}
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ParseIPAddress {
public static void main(String[] args) {
String [] tests = new String[] {"192.168.0.1", "127.0.0.1", "256.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "[32e::12f]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", "2001:db8:85a3:0:0:8a2e:370:7334"};
System.out.printf("%-40s %-32s %s%n", "Test Case", "Hex Address", "Port");
for ( String ip : tests ) {
try {
String [] parsed = parseIP(ip);
System.out.printf("%-40s %-32s %s%n", ip, parsed[0], parsed[1]);
}
catch (IllegalArgumentException e) {
System.out.printf("%-40s Invalid address: %s%n", ip, e.getMessage());
}
}
}
private static final Pattern IPV4_PAT = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)(?::(\\d+)){0,1}$");
private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile("^\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\]:(\\d+)){0,1}$");
private static String ipv6Pattern;
static {
ipv6Pattern = "^\\[{0,1}";
for ( int i = 1 ; i <= 7 ; i ++ ) {
ipv6Pattern += "([0-9a-f]+):";
}
ipv6Pattern += "([0-9a-f]+)(?:\\]:(\\d+)){0,1}$";
}
private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern);
private static String[] parseIP(String ip) {
String hex = "";
String port = "";
Matcher ipv4Matcher = IPV4_PAT.matcher(ip);
if ( ipv4Matcher.matches() ) {
for ( int i = 1 ; i <= 4 ; i++ ) {
hex += toHex4(ipv4Matcher.group(i));
}
if ( ipv4Matcher.group(5) != null ) {
port = ipv4Matcher.group(5);
}
return new String[] {hex, port};
}
Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip);
if ( ipv6DoubleColonMatcher.matches() ) {
String p1 = ipv6DoubleColonMatcher.group(1);
if ( p1.isEmpty() ) {
p1 = "0";
}
String p2 = ipv6DoubleColonMatcher.group(2);
if ( p2.isEmpty() ) {
p2 = "0";
}
ip = p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2;
if ( ipv6DoubleColonMatcher.group(3) != null ) {
ip = "[" + ip + "]:" + ipv6DoubleColonMatcher.group(3);
}
}
Matcher ipv6Matcher = IPV6_PAT.matcher(ip);
if ( ipv6Matcher.matches() ) {
for ( int i = 1 ; i <= 8 ; i++ ) {
hex += String.format("%4s", toHex6(ipv6Matcher.group(i))).replace(" ", "0");
}
if ( ipv6Matcher.group(9) != null ) {
port = ipv6Matcher.group(9);
}
return new String[] {hex, port};
}
throw new IllegalArgumentException("ERROR 103: Unknown address: " + ip);
}
private static int numCount(String s) {
return s.split(":").length;
}
private static String getZero(int count) {
StringBuilder sb = new StringBuilder();
sb.append(":");
while ( count > 0 ) {
sb.append("0:");
count--;
}
return sb.toString();
}
private static String toHex4(String s) {
int val = Integer.parseInt(s);
if ( val < 0 || val > 255 ) {
throw new IllegalArgumentException("ERROR 101: Invalid value : " + s);
}
return String.format("%2s", Integer.toHexString(val)).replace(" ", "0");
}
private static String toHex6(String s) {
int val = Integer.parseInt(s, 16);
if ( val < 0 || val > 65536 ) {
throw new IllegalArgumentException("ERROR 102: Invalid hex value : " + s);
}
return s;
}
}
| require 'ipaddr'
TESTCASES = ["127.0.0.1", "127.0.0.1:80",
"::1", "[::1]:80",
"2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80"]
output = [%w(String Address Port Family Hex),
%w(------ ------- ---- ------ ---)]
def output_table(rows)
widths = []
rows.each {|row| row.each_with_index {|col, i| widths[i] = [widths[i].to_i, col.to_s.length].max }}
format = widths.map {|size| "%
rows.each {|row| puts format % row}
end
TESTCASES.each do |str|
case str
when /\A\[(?<address> .* )\]:(?<port> \d+ )\z/x
address, port = $~[:address], $~[:port]
when /\A(?<address> [^:]+ ):(?<port> \d+ )\z/x
address, port = $~[:address], $~[:port]
else
address, port = str, nil
end
ip_addr = IPAddr.new(address)
family = "IPv4" if ip_addr.ipv4?
family = "IPv6" if ip_addr.ipv6?
output << [str, ip_addr.to_s, port.to_s, family, ip_addr.to_i.to_s(16)]
end
output_table(output)
|
Change the programming language of this snippet from Java to Ruby without modifying what it does. | import java.util.*;
import java.awt.geom.*;
public class LineCircleIntersection {
public static void main(String[] args) {
try {
demo();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void demo() throws NoninvertibleTransformException {
Point2D center = makePoint(3, -5);
double radius = 3.0;
System.out.println("The intersection points (if any) between:");
System.out.println("\n A circle, center (3, -5) with radius 3, and:");
System.out.println("\n a line containing the points (-10, 11) and (10, -9) is/are:");
System.out.println(" " + toString(intersection(makePoint(-10, 11), makePoint(10, -9),
center, radius, false)));
System.out.println("\n a segment starting at (-10, 11) and ending at (-11, 12) is/are");
System.out.println(" " + toString(intersection(makePoint(-10, 11), makePoint(-11, 12),
center, radius, true)));
System.out.println("\n a horizontal line containing the points (3, -2) and (7, -2) is/are:");
System.out.println(" " + toString(intersection(makePoint(3, -2), makePoint(7, -2), center, radius, false)));
center.setLocation(0, 0);
radius = 4.0;
System.out.println("\n A circle, center (0, 0) with radius 4, and:");
System.out.println("\n a vertical line containing the points (0, -3) and (0, 6) is/are:");
System.out.println(" " + toString(intersection(makePoint(0, -3), makePoint(0, 6),
center, radius, false)));
System.out.println("\n a vertical segment starting at (0, -3) and ending at (0, 6) is/are:");
System.out.println(" " + toString(intersection(makePoint(0, -3), makePoint(0, 6),
center, radius, true)));
center.setLocation(4, 2);
radius = 5.0;
System.out.println("\n A circle, center (4, 2) with radius 5, and:");
System.out.println("\n a line containing the points (6, 3) and (10, 7) is/are:");
System.out.println(" " + toString(intersection(makePoint(6, 3), makePoint(10, 7),
center, radius, false)));
System.out.println("\n a segment starting at (7, 4) and ending at (11, 8) is/are:");
System.out.println(" " + toString(intersection(makePoint(7, 4), makePoint(11, 8),
center, radius, true)));
}
private static Point2D makePoint(double x, double y) {
return new Point2D.Double(x, y);
}
public static List<Point2D> intersection(Point2D p1, Point2D p2, Point2D center,
double radius, boolean isSegment) throws NoninvertibleTransformException {
List<Point2D> result = new ArrayList<>();
double dx = p2.getX() - p1.getX();
double dy = p2.getY() - p1.getY();
AffineTransform trans = AffineTransform.getRotateInstance(dx, dy);
trans.invert();
trans.translate(-center.getX(), -center.getY());
Point2D p1a = trans.transform(p1, null);
Point2D p2a = trans.transform(p2, null);
double y = p1a.getY();
double minX = Math.min(p1a.getX(), p2a.getX());
double maxX = Math.max(p1a.getX(), p2a.getX());
if (y == radius || y == -radius) {
if (!isSegment || (0 <= maxX && 0 >= minX)) {
p1a.setLocation(0, y);
trans.inverseTransform(p1a, p1a);
result.add(p1a);
}
} else if (y < radius && y > -radius) {
double x = Math.sqrt(radius * radius - y * y);
if (!isSegment || (-x <= maxX && -x >= minX)) {
p1a.setLocation(-x, y);
trans.inverseTransform(p1a, p1a);
result.add(p1a);
}
if (!isSegment || (x <= maxX && x >= minX)) {
p2a.setLocation(x, y);
trans.inverseTransform(p2a, p2a);
result.add(p2a);
}
}
return result;
}
public static String toString(Point2D point) {
return String.format("(%g, %g)", point.getX(), point.getY());
}
public static String toString(List<Point2D> points) {
StringBuilder str = new StringBuilder("[");
for (int i = 0, n = points.size(); i < n; ++i) {
if (i > 0)
str.append(", ");
str.append(toString(points.get(i)));
}
str.append("]");
return str.toString();
}
}
| EPS = 1e-14
def sq(x)
return x * x
end
def intersects(p1, p2, cp, r, segment)
res = []
(x0, y0) = cp
(x1, y1) = p1
(x2, y2) = p2
aa = y2 - y1
bb = x1 - x2
cc = x2 * y1 - x1 * y2
a = sq(aa) + sq(bb)
if bb.abs >= EPS then
b = 2 * (aa * cc + aa * bb * y0 - sq(bb) * x0)
c = sq(cc) + 2 * bb * cc * y0 - sq(bb) * (sq(r) - sq(x0) - sq(y0))
bnz = true
else
b = 2 * (bb * cc + aa * bb * x0 - sq(aa) * y0)
c = sq(cc) + 2 * aa * cc * x0 - sq(aa) * (sq(r) - sq(x0) - sq(y0))
bnz = false
end
d = sq(b) - 4 * a * c
if d < 0 then
return res
end
within = ->(x, y) {
d1 = Math.sqrt(sq(x2 - x1) + sq(y2 - y1))
d2 = Math.sqrt(sq(x - x1) + sq(y - y1))
d3 = Math.sqrt(sq(x2 - x) + sq(y2 - y))
delta = d1 - d2 - d3
return delta.abs < EPS
}
fx = ->(x) {
return -(aa * x + cc) / bb
}
fy = ->(y) {
return -(bb * y + cc) / aa
}
rxy = ->(x, y) {
if not segment or within.call(x, y) then
if x == 0.0 then
x = 0.0
end
if y == 0.0 then
y = 0.0
end
res << [x, y]
end
}
if d == 0.0 then
if bnz then
x = -b / (2 * a)
y = fx.call(x)
rxy.call(x, y)
else
y = -b / (2 * a)
x = fy.call(y)
rxy.call(x, y)
end
else
d = Math.sqrt(d)
if bnz then
x = (-b + d) / (2 * a)
y = fx.call(x)
rxy.call(x, y)
x = (-b - d) / (2 * a)
y = fx.call(x)
rxy.call(x, y)
else
y = (-b + d) / (2 * a)
x = fy.call(y)
rxy.call(x, y)
y = (-b - d) / (2 * a)
x = fy.call(y)
rxy.call(x, y)
end
end
return res
end
def main
print "The intersection points (if any) between:\n"
cp = [3.0, -5.0]
r = 3.0
print " A circle, center %s with radius %f, and:\n" % [cp, r]
p1 = [-10.0, 11.0]
p2 = [10.0, -9.0]
print " a line containing the points %s and %s is/are:\n" % [p1, p2]
print " %s\n" % [intersects(p1, p2, cp, r, false)]
p2 = [-10.0, 12.0]
print " a segment starting at %s and ending at %s is/are:\n" % [p1, p2]
print " %s\n" % [intersects(p1, p2, cp, r, true)]
p1 = [3.0, -2.0]
p2 = [7.0, -2.0]
print " a horizontal line containing the points %s and %s is/are:\n" % [p1, p2]
print " %s\n" % [intersects(p1, p2, cp, r, false)]
cp = [0.0, 0.0]
r = 4.0
print " A circle, center %s with radius %f, and:\n" % [cp, r]
p1 = [0.0, -3.0]
p2 = [0.0, 6.0]
print " a vertical line containing the points %s and %s is/are:\n" % [p1, p2]
print " %s\n" % [intersects(p1, p2, cp, r, false)]
print " a vertical line segment containing the points %s and %s is/are:\n" % [p1, p2]
print " %s\n" % [intersects(p1, p2, cp, r, true)]
cp = [4.0, 2.0]
r = 5.0
print " A circle, center %s with radius %f, and:\n" % [cp, r]
p1 = [6.0, 3.0]
p2 = [10.0, 7.0]
print " a line containing the points %s and %s is/are:\n" % [p1, p2]
print " %s\n" % [intersects(p1, p2, cp, r, false)]
p1 = [7.0, 4.0]
p2 = [11.0, 8.0]
print " a segment starting at %s and ending at %s is/are:\n" % [p1, p2]
print " %s\n" % [intersects(p1, p2, cp, r, true)]
end
main()
|
Please provide an equivalent version of this Java code in Ruby. | public static int findNumOfDec(double x){
String str = String.valueOf(x);
if(str.endsWith(".0")) return 0;
else return (str.substring(str.indexOf('.')).length() - 1);
}
| func number_of_decimals(n, limit = 1e5) {
var prec = Num(Num!PREC)>>2
var prev = ''
n = Number(n) if !n.kind_of(Number)
loop {
var str = n.as_dec(prec)
if (prev == str) {
return (str.contains('.') ? str.substr(str.index('.')+1).len : 0)
}
prev = str
prec *= 2
return Inf if (prec > limit)
}
}
var list = [
9, 12.345, "12.3450", "12.345e53",
12.34555555555555555555, 0.1234567890987654321,
Num.pi, 1/3, 1.5**63
]
list.each {|n|
var c = number_of_decimals(n)
say "Number of decimals:
}
|
Transform the following Java implementation into Ruby, maintaining the same output and logic. | import java.util.*;
public class Hopido {
final static String[] board = {
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0..."};
final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2}};
static int[][] grid;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 6;
int nCols = board[0].length() + 6;
grid = new int[nRows][nCols];
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
for (int c = 3; c < nCols - 3; c++)
if (r >= 3 && r < nRows - 3) {
if (board[r - 3].charAt(c - 3) == '0') {
grid[r][c] = 0;
totalToFill++;
}
}
}
int pos = -1, r, c;
do {
do {
pos++;
r = pos / nCols;
c = pos % nCols;
} while (grid[r][c] == -1);
grid[r][c] = 1;
if (solve(r, c, 2))
break;
grid[r][c] = 0;
} while (pos < nRows * nCols);
printResult();
}
static boolean solve(int r, int c, int count) {
if (count > totalToFill)
return true;
List<int[]> nbrs = neighbors(r, c);
if (nbrs.isEmpty() && count != totalToFill)
return false;
Collections.sort(nbrs, (a, b) -> a[2] - b[2]);
for (int[] nb : nbrs) {
r = nb[0];
c = nb[1];
grid[r][c] = count;
if (solve(r, c, count + 1))
return true;
grid[r][c] = 0;
}
return false;
}
static List<int[]> neighbors(int r, int c) {
List<int[]> nbrs = new ArrayList<>();
for (int[] m : moves) {
int x = m[0];
int y = m[1];
if (grid[r + y][c + x] == 0) {
int num = countNeighbors(r + y, c + x) - 1;
nbrs.add(new int[]{r + y, c + x, num});
}
}
return nbrs;
}
static int countNeighbors(int r, int c) {
int num = 0;
for (int[] m : moves)
if (grid[r + m[1]][c + m[0]] == 0)
num++;
return num;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
System.out.printf("%2s ", ' ');
else
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
| require 'HLPsolver'
ADJACENT = [[-3, 0], [0, -3], [0, 3], [3, 0], [-2, -2], [-2, 2], [2, -2], [2, 2]]
board1 = <<EOS
. 0 0 . 0 0 .
0 0 0 0 0 0 0
0 0 0 0 0 0 0
. 0 0 0 0 0 .
. . 0 0 0 . .
. . . 1 . . .
EOS
t0 = Time.now
HLPsolver.new(board1).solve
puts "
|
Translate the given Java code snippet into Ruby without altering its behavior. | import java.util.*;
public class Hopido {
final static String[] board = {
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0..."};
final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2}};
static int[][] grid;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 6;
int nCols = board[0].length() + 6;
grid = new int[nRows][nCols];
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
for (int c = 3; c < nCols - 3; c++)
if (r >= 3 && r < nRows - 3) {
if (board[r - 3].charAt(c - 3) == '0') {
grid[r][c] = 0;
totalToFill++;
}
}
}
int pos = -1, r, c;
do {
do {
pos++;
r = pos / nCols;
c = pos % nCols;
} while (grid[r][c] == -1);
grid[r][c] = 1;
if (solve(r, c, 2))
break;
grid[r][c] = 0;
} while (pos < nRows * nCols);
printResult();
}
static boolean solve(int r, int c, int count) {
if (count > totalToFill)
return true;
List<int[]> nbrs = neighbors(r, c);
if (nbrs.isEmpty() && count != totalToFill)
return false;
Collections.sort(nbrs, (a, b) -> a[2] - b[2]);
for (int[] nb : nbrs) {
r = nb[0];
c = nb[1];
grid[r][c] = count;
if (solve(r, c, count + 1))
return true;
grid[r][c] = 0;
}
return false;
}
static List<int[]> neighbors(int r, int c) {
List<int[]> nbrs = new ArrayList<>();
for (int[] m : moves) {
int x = m[0];
int y = m[1];
if (grid[r + y][c + x] == 0) {
int num = countNeighbors(r + y, c + x) - 1;
nbrs.add(new int[]{r + y, c + x, num});
}
}
return nbrs;
}
static int countNeighbors(int r, int c) {
int num = 0;
for (int[] m : moves)
if (grid[r + m[1]][c + m[0]] == 0)
num++;
return num;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
System.out.printf("%2s ", ' ');
else
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
| require 'HLPsolver'
ADJACENT = [[-3, 0], [0, -3], [0, 3], [3, 0], [-2, -2], [-2, 2], [2, -2], [2, 2]]
board1 = <<EOS
. 0 0 . 0 0 .
0 0 0 0 0 0 0
0 0 0 0 0 0 0
. 0 0 0 0 0 .
. . 0 0 0 . .
. . . 1 . . .
EOS
t0 = Time.now
HLPsolver.new(board1).solve
puts "
|
Please provide an equivalent version of this Java code in Ruby. | import java.util.*;
public class Numbrix {
final static String[] board = {
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00"};
final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
static int[][] grid;
static int[] clues;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 2;
int nCols = board[0].split(",").length + 2;
int startRow = 0, startCol = 0;
grid = new int[nRows][nCols];
totalToFill = (nRows - 2) * (nCols - 2);
List<Integer> lst = new ArrayList<>();
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
if (r >= 1 && r < nRows - 1) {
String[] row = board[r - 1].split(",");
for (int c = 1; c < nCols - 1; c++) {
int val = Integer.parseInt(row[c - 1]);
if (val > 0)
lst.add(val);
if (val == 1) {
startRow = r;
startCol = c;
}
grid[r][c] = val;
}
}
}
clues = lst.stream().sorted().mapToInt(i -> i).toArray();
if (solve(startRow, startCol, 1, 0))
printResult();
}
static boolean solve(int r, int c, int count, int nextClue) {
if (count > totalToFill)
return true;
if (grid[r][c] != 0 && grid[r][c] != count)
return false;
if (grid[r][c] == 0 && nextClue < clues.length)
if (clues[nextClue] == count)
return false;
int back = grid[r][c];
if (back == count)
nextClue++;
grid[r][c] = count;
for (int[] move : moves)
if (solve(r + move[1], c + move[0], count + 1, nextClue))
return true;
grid[r][c] = back;
return false;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
continue;
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
| require 'HLPsolver'
ADJACENT = [[-1, 0], [0, -1], [0, 1], [1, 0]]
board1 = <<EOS
0 0 0 0 0 0 0 0 0
0 0 46 45 0 55 74 0 0
0 38 0 0 43 0 0 78 0
0 35 0 0 0 0 0 71 0
0 0 33 0 0 0 59 0 0
0 17 0 0 0 0 0 67 0
0 18 0 0 11 0 0 64 0
0 0 24 21 0 1 2 0 0
0 0 0 0 0 0 0 0 0
EOS
HLPsolver.new(board1).solve
board2 = <<EOS
0 0 0 0 0 0 0 0 0
0 11 12 15 18 21 62 61 0
0 6 0 0 0 0 0 60 0
0 33 0 0 0 0 0 57 0
0 32 0 0 0 0 0 56 0
0 37 0 1 0 0 0 73 0
0 38 0 0 0 0 0 72 0
0 43 44 47 48 51 76 77 0
0 0 0 0 0 0 0 0 0
EOS
HLPsolver.new(board2).solve
|
Please provide an equivalent version of this Java code in Ruby. | import java.util.*;
public class Numbrix {
final static String[] board = {
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00"};
final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
static int[][] grid;
static int[] clues;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 2;
int nCols = board[0].split(",").length + 2;
int startRow = 0, startCol = 0;
grid = new int[nRows][nCols];
totalToFill = (nRows - 2) * (nCols - 2);
List<Integer> lst = new ArrayList<>();
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
if (r >= 1 && r < nRows - 1) {
String[] row = board[r - 1].split(",");
for (int c = 1; c < nCols - 1; c++) {
int val = Integer.parseInt(row[c - 1]);
if (val > 0)
lst.add(val);
if (val == 1) {
startRow = r;
startCol = c;
}
grid[r][c] = val;
}
}
}
clues = lst.stream().sorted().mapToInt(i -> i).toArray();
if (solve(startRow, startCol, 1, 0))
printResult();
}
static boolean solve(int r, int c, int count, int nextClue) {
if (count > totalToFill)
return true;
if (grid[r][c] != 0 && grid[r][c] != count)
return false;
if (grid[r][c] == 0 && nextClue < clues.length)
if (clues[nextClue] == count)
return false;
int back = grid[r][c];
if (back == count)
nextClue++;
grid[r][c] = count;
for (int[] move : moves)
if (solve(r + move[1], c + move[0], count + 1, nextClue))
return true;
grid[r][c] = back;
return false;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
continue;
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
| require 'HLPsolver'
ADJACENT = [[-1, 0], [0, -1], [0, 1], [1, 0]]
board1 = <<EOS
0 0 0 0 0 0 0 0 0
0 0 46 45 0 55 74 0 0
0 38 0 0 43 0 0 78 0
0 35 0 0 0 0 0 71 0
0 0 33 0 0 0 59 0 0
0 17 0 0 0 0 0 67 0
0 18 0 0 11 0 0 64 0
0 0 24 21 0 1 2 0 0
0 0 0 0 0 0 0 0 0
EOS
HLPsolver.new(board1).solve
board2 = <<EOS
0 0 0 0 0 0 0 0 0
0 11 12 15 18 21 62 61 0
0 6 0 0 0 0 0 60 0
0 33 0 0 0 0 0 57 0
0 32 0 0 0 0 0 56 0
0 37 0 1 0 0 0 73 0
0 38 0 0 0 0 0 72 0
0 43 44 47 48 51 76 77 0
0 0 0 0 0 0 0 0 0
EOS
HLPsolver.new(board2).solve
|
Generate an equivalent Ruby version of this Java code. | import java.util.Stack;
public class ArithmeticEvaluation {
public interface Expression {
BigRational eval();
}
public enum Parentheses {LEFT}
public enum BinaryOperator {
ADD('+', 1),
SUB('-', 1),
MUL('*', 2),
DIV('/', 2);
public final char symbol;
public final int precedence;
BinaryOperator(char symbol, int precedence) {
this.symbol = symbol;
this.precedence = precedence;
}
public BigRational eval(BigRational leftValue, BigRational rightValue) {
switch (this) {
case ADD:
return leftValue.add(rightValue);
case SUB:
return leftValue.subtract(rightValue);
case MUL:
return leftValue.multiply(rightValue);
case DIV:
return leftValue.divide(rightValue);
}
throw new IllegalStateException();
}
public static BinaryOperator forSymbol(char symbol) {
for (BinaryOperator operator : values()) {
if (operator.symbol == symbol) {
return operator;
}
}
throw new IllegalArgumentException(String.valueOf(symbol));
}
}
public static class Number implements Expression {
private final BigRational number;
public Number(BigRational number) {
this.number = number;
}
@Override
public BigRational eval() {
return number;
}
@Override
public String toString() {
return number.toString();
}
}
public static class BinaryExpression implements Expression {
public final Expression leftOperand;
public final BinaryOperator operator;
public final Expression rightOperand;
public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {
this.leftOperand = leftOperand;
this.operator = operator;
this.rightOperand = rightOperand;
}
@Override
public BigRational eval() {
BigRational leftValue = leftOperand.eval();
BigRational rightValue = rightOperand.eval();
return operator.eval(leftValue, rightValue);
}
@Override
public String toString() {
return "(" + leftOperand + " " + operator.symbol + " " + rightOperand + ")";
}
}
private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {
Expression rightOperand = operands.pop();
Expression leftOperand = operands.pop();
operands.push(new BinaryExpression(leftOperand, operator, rightOperand));
}
public static Expression parse(String input) {
int curIndex = 0;
boolean afterOperand = false;
Stack<Expression> operands = new Stack<>();
Stack<Object> operators = new Stack<>();
while (curIndex < input.length()) {
int startIndex = curIndex;
char c = input.charAt(curIndex++);
if (Character.isWhitespace(c))
continue;
if (afterOperand) {
if (c == ')') {
Object operator;
while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))
createNewOperand((BinaryOperator) operator, operands);
continue;
}
afterOperand = false;
BinaryOperator operator = BinaryOperator.forSymbol(c);
while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))
createNewOperand((BinaryOperator) operators.pop(), operands);
operators.push(operator);
continue;
}
if (c == '(') {
operators.push(Parentheses.LEFT);
continue;
}
afterOperand = true;
while (curIndex < input.length()) {
c = input.charAt(curIndex);
if (((c < '0') || (c > '9')) && (c != '.'))
break;
curIndex++;
}
operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));
}
while (!operators.isEmpty()) {
Object operator = operators.pop();
if (operator == Parentheses.LEFT)
throw new IllegalArgumentException();
createNewOperand((BinaryOperator) operator, operands);
}
Expression expression = operands.pop();
if (!operands.isEmpty())
throw new IllegalArgumentException();
return expression;
}
public static void main(String[] args) {
String[] testExpressions = {
"2+3",
"2+3/4",
"2*3-4",
"2*(3+4)+5/6",
"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10",
"2*-3--4+-.25"};
for (String testExpression : testExpressions) {
Expression expression = parse(testExpression);
System.out.printf("Input: \"%s\", AST: \"%s\", value=%s%n", testExpression, expression, expression.eval());
}
}
}
| $op_priority = {"+" => 0, "-" => 0, "*" => 1, "/" => 1}
class TreeNode
OP_FUNCTION = {
"+" => lambda {|x, y| x + y},
"-" => lambda {|x, y| x - y},
"*" => lambda {|x, y| x * y},
"/" => lambda {|x, y| x / y}}
attr_accessor :info, :left, :right
def initialize(info)
@info = info
end
def leaf?
@left.nil? and @right.nil?
end
def to_s(order)
if leaf?
@info
else
left_s, right_s = @left.to_s(order), @right.to_s(order)
strs = case order
when :prefix then [@info, left_s, right_s]
when :infix then [left_s, @info, right_s]
when :postfix then [left_s, right_s, @info]
else []
end
"(" + strs.join(" ") + ")"
end
end
def eval
if !leaf? and operator?(@info)
OP_FUNCTION[@info].call(@left.eval, @right.eval)
else
@info.to_f
end
end
end
def tokenize(exp)
exp
.gsub('(', ' ( ')
.gsub(')', ' ) ')
.gsub('+', ' + ')
.gsub('-', ' - ')
.gsub('*', ' * ')
.gsub('/', ' / ')
.split(' ')
end
def operator?(token)
$op_priority.has_key?(token)
end
def pop_connect_push(op_stack, node_stack)
temp = op_stack.pop
temp.right = node_stack.pop
temp.left = node_stack.pop
node_stack.push(temp)
end
def infix_exp_to_tree(exp)
tokens = tokenize(exp)
op_stack, node_stack = [], []
tokens.each do |token|
if operator?(token)
until (op_stack.empty? or
op_stack.last.info == "(" or
$op_priority[op_stack.last.info] < $op_priority[token])
pop_connect_push(op_stack, node_stack)
end
op_stack.push(TreeNode.new(token))
elsif token == "("
op_stack.push(TreeNode.new(token))
elsif token == ")"
while op_stack.last.info != "("
pop_connect_push(op_stack, node_stack)
end
op_stack.pop
else
node_stack.push(TreeNode.new(token))
end
end
until op_stack.empty?
pop_connect_push(op_stack, node_stack)
end
node_stack.last
end
|
Please provide an equivalent version of this Java code in Ruby. | import java.util.Stack;
public class ArithmeticEvaluation {
public interface Expression {
BigRational eval();
}
public enum Parentheses {LEFT}
public enum BinaryOperator {
ADD('+', 1),
SUB('-', 1),
MUL('*', 2),
DIV('/', 2);
public final char symbol;
public final int precedence;
BinaryOperator(char symbol, int precedence) {
this.symbol = symbol;
this.precedence = precedence;
}
public BigRational eval(BigRational leftValue, BigRational rightValue) {
switch (this) {
case ADD:
return leftValue.add(rightValue);
case SUB:
return leftValue.subtract(rightValue);
case MUL:
return leftValue.multiply(rightValue);
case DIV:
return leftValue.divide(rightValue);
}
throw new IllegalStateException();
}
public static BinaryOperator forSymbol(char symbol) {
for (BinaryOperator operator : values()) {
if (operator.symbol == symbol) {
return operator;
}
}
throw new IllegalArgumentException(String.valueOf(symbol));
}
}
public static class Number implements Expression {
private final BigRational number;
public Number(BigRational number) {
this.number = number;
}
@Override
public BigRational eval() {
return number;
}
@Override
public String toString() {
return number.toString();
}
}
public static class BinaryExpression implements Expression {
public final Expression leftOperand;
public final BinaryOperator operator;
public final Expression rightOperand;
public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {
this.leftOperand = leftOperand;
this.operator = operator;
this.rightOperand = rightOperand;
}
@Override
public BigRational eval() {
BigRational leftValue = leftOperand.eval();
BigRational rightValue = rightOperand.eval();
return operator.eval(leftValue, rightValue);
}
@Override
public String toString() {
return "(" + leftOperand + " " + operator.symbol + " " + rightOperand + ")";
}
}
private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {
Expression rightOperand = operands.pop();
Expression leftOperand = operands.pop();
operands.push(new BinaryExpression(leftOperand, operator, rightOperand));
}
public static Expression parse(String input) {
int curIndex = 0;
boolean afterOperand = false;
Stack<Expression> operands = new Stack<>();
Stack<Object> operators = new Stack<>();
while (curIndex < input.length()) {
int startIndex = curIndex;
char c = input.charAt(curIndex++);
if (Character.isWhitespace(c))
continue;
if (afterOperand) {
if (c == ')') {
Object operator;
while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))
createNewOperand((BinaryOperator) operator, operands);
continue;
}
afterOperand = false;
BinaryOperator operator = BinaryOperator.forSymbol(c);
while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))
createNewOperand((BinaryOperator) operators.pop(), operands);
operators.push(operator);
continue;
}
if (c == '(') {
operators.push(Parentheses.LEFT);
continue;
}
afterOperand = true;
while (curIndex < input.length()) {
c = input.charAt(curIndex);
if (((c < '0') || (c > '9')) && (c != '.'))
break;
curIndex++;
}
operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));
}
while (!operators.isEmpty()) {
Object operator = operators.pop();
if (operator == Parentheses.LEFT)
throw new IllegalArgumentException();
createNewOperand((BinaryOperator) operator, operands);
}
Expression expression = operands.pop();
if (!operands.isEmpty())
throw new IllegalArgumentException();
return expression;
}
public static void main(String[] args) {
String[] testExpressions = {
"2+3",
"2+3/4",
"2*3-4",
"2*(3+4)+5/6",
"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10",
"2*-3--4+-.25"};
for (String testExpression : testExpressions) {
Expression expression = parse(testExpression);
System.out.printf("Input: \"%s\", AST: \"%s\", value=%s%n", testExpression, expression, expression.eval());
}
}
}
| $op_priority = {"+" => 0, "-" => 0, "*" => 1, "/" => 1}
class TreeNode
OP_FUNCTION = {
"+" => lambda {|x, y| x + y},
"-" => lambda {|x, y| x - y},
"*" => lambda {|x, y| x * y},
"/" => lambda {|x, y| x / y}}
attr_accessor :info, :left, :right
def initialize(info)
@info = info
end
def leaf?
@left.nil? and @right.nil?
end
def to_s(order)
if leaf?
@info
else
left_s, right_s = @left.to_s(order), @right.to_s(order)
strs = case order
when :prefix then [@info, left_s, right_s]
when :infix then [left_s, @info, right_s]
when :postfix then [left_s, right_s, @info]
else []
end
"(" + strs.join(" ") + ")"
end
end
def eval
if !leaf? and operator?(@info)
OP_FUNCTION[@info].call(@left.eval, @right.eval)
else
@info.to_f
end
end
end
def tokenize(exp)
exp
.gsub('(', ' ( ')
.gsub(')', ' ) ')
.gsub('+', ' + ')
.gsub('-', ' - ')
.gsub('*', ' * ')
.gsub('/', ' / ')
.split(' ')
end
def operator?(token)
$op_priority.has_key?(token)
end
def pop_connect_push(op_stack, node_stack)
temp = op_stack.pop
temp.right = node_stack.pop
temp.left = node_stack.pop
node_stack.push(temp)
end
def infix_exp_to_tree(exp)
tokens = tokenize(exp)
op_stack, node_stack = [], []
tokens.each do |token|
if operator?(token)
until (op_stack.empty? or
op_stack.last.info == "(" or
$op_priority[op_stack.last.info] < $op_priority[token])
pop_connect_push(op_stack, node_stack)
end
op_stack.push(TreeNode.new(token))
elsif token == "("
op_stack.push(TreeNode.new(token))
elsif token == ")"
while op_stack.last.info != "("
pop_connect_push(op_stack, node_stack)
end
op_stack.pop
else
node_stack.push(TreeNode.new(token))
end
end
until op_stack.empty?
pop_connect_push(op_stack, node_stack)
end
node_stack.last
end
|
Convert the following code from Java to Ruby, ensuring the logic remains intact. | import java.io.*;
public class SierpinskiCurve {
public static void main(final String[] args) {
try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) {
SierpinskiCurve s = new SierpinskiCurve(writer);
s.currentAngle = 45;
s.currentX = 5;
s.currentY = 10;
s.lineLength = 7;
s.begin(545);
s.execute(rewrite(5));
s.end();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private SierpinskiCurve(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':
case 'G':
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+G+XF--F--XF+G+X";
private static final int ANGLE = 45;
}
| var rules = Hash(
x => 'xF+G+xF--F--xF+G+x',
)
var lsys = LSystem(
width: 550,
height: 550,
xoff: -9,
yoff: -271,
len: 5,
angle: 45,
color: 'dark green',
)
lsys.execute('F--xF--F--xF', 5, "sierpiński_curve.png", rules)
|
Produce a language-to-language conversion: from Java to Ruby, same semantics. | import java.io.*;
public class SierpinskiCurve {
public static void main(final String[] args) {
try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) {
SierpinskiCurve s = new SierpinskiCurve(writer);
s.currentAngle = 45;
s.currentX = 5;
s.currentY = 10;
s.lineLength = 7;
s.begin(545);
s.execute(rewrite(5));
s.end();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private SierpinskiCurve(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':
case 'G':
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+G+XF--F--XF+G+X";
private static final int ANGLE = 45;
}
| var rules = Hash(
x => 'xF+G+xF--F--xF+G+x',
)
var lsys = LSystem(
width: 550,
height: 550,
xoff: -9,
yoff: -271,
len: 5,
angle: 45,
color: 'dark green',
)
lsys.execute('F--xF--F--xF', 5, "sierpiński_curve.png", rules)
|
Keep all operations the same but rewrite the snippet in Ruby. | import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.*;
public class Backup {
public static void saveWithBackup(String filename, String... data)
throws IOException {
Path file = Paths.get(filename).toRealPath();
File backFile = new File(filename + ".backup");
if(!backFile.exists()) {
backFile.createNewFile();
}
Path back = Paths.get(filename + ".backup").toRealPath();
Files.move(file, back, StandardCopyOption.REPLACE_EXISTING);
try(PrintWriter out = new PrintWriter(file.toFile())){
for(int i = 0; i < data.length; i++) {
out.print(data[i]);
if(i < data.length - 1) {
out.println();
}
}
}
}
public static void main(String[] args) {
try {
saveWithBackup("original.txt", "fourth", "fifth", "sixth");
} catch (IOException e) {
System.err.println(e);
}
}
}
| def backup_and_open(filename)
filename = File.realpath(filename)
bkup = filename + ".backup"
backup_files = Dir.glob(bkup + "*").sort_by do |f|
f.match(/\d+$/)
$&.nil? ? 0 : $&.to_i
end
backup_files.reverse.each do |fname|
if m = fname.match(/\.backup\.(\d+)$/)
File.rename(fname, "%s.%d" % [bkup, m[1].to_i + 1])
elsif fname == bkup
File.rename(bkup, bkup + ".1")
end
end
File.rename(filename, bkup)
File.open(filename, "w") {|handle| yield handle}
end
1.upto(12) {|i| backup_and_open(ARGV[0]) {|fh| fh.puts "backup
|
Preserve the algorithm and functionality while converting the code from Java to Ruby. | import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.*;
public class Backup {
public static void saveWithBackup(String filename, String... data)
throws IOException {
Path file = Paths.get(filename).toRealPath();
File backFile = new File(filename + ".backup");
if(!backFile.exists()) {
backFile.createNewFile();
}
Path back = Paths.get(filename + ".backup").toRealPath();
Files.move(file, back, StandardCopyOption.REPLACE_EXISTING);
try(PrintWriter out = new PrintWriter(file.toFile())){
for(int i = 0; i < data.length; i++) {
out.print(data[i]);
if(i < data.length - 1) {
out.println();
}
}
}
}
public static void main(String[] args) {
try {
saveWithBackup("original.txt", "fourth", "fifth", "sixth");
} catch (IOException e) {
System.err.println(e);
}
}
}
| def backup_and_open(filename)
filename = File.realpath(filename)
bkup = filename + ".backup"
backup_files = Dir.glob(bkup + "*").sort_by do |f|
f.match(/\d+$/)
$&.nil? ? 0 : $&.to_i
end
backup_files.reverse.each do |fname|
if m = fname.match(/\.backup\.(\d+)$/)
File.rename(fname, "%s.%d" % [bkup, m[1].to_i + 1])
elsif fname == bkup
File.rename(bkup, bkup + ".1")
end
end
File.rename(filename, bkup)
File.open(filename, "w") {|handle| yield handle}
end
1.upto(12) {|i| backup_and_open(ARGV[0]) {|fh| fh.puts "backup
|
Change the following Java code into Ruby without altering its purpose. | import java.util.Map;
import java.util.Random;
public class Game {
private static final Map<Integer, Integer> snl = Map.ofEntries(
Map.entry(4, 14),
Map.entry(9, 31),
Map.entry(17, 7),
Map.entry(20, 38),
Map.entry(28, 84),
Map.entry(40, 59),
Map.entry(51, 67),
Map.entry(54, 34),
Map.entry(62, 19),
Map.entry(63, 81),
Map.entry(64, 60),
Map.entry(71, 91),
Map.entry(87, 24),
Map.entry(93, 73),
Map.entry(95, 75),
Map.entry(99, 78)
);
private static final boolean sixesThrowAgain = true;
private static Random rand = new Random();
private static int turn(int player, int square) {
int square2 = square;
while (true) {
int roll = rand.nextInt(6) + 1;
System.out.printf("Player %d, on square %d, rolls a %d", player, square2, roll);
if (square2 + roll > 100) {
System.out.println(" but cannot move.");
} else {
square2 += roll;
System.out.printf(" and moves to square %d\n", square2);
if (square2 == 100) return 100;
Integer next = snl.getOrDefault(square2, square2);
if (square2 < next) {
System.out.printf("Yay! Landed on a ladder. Climb up to %d.\n", next);
if (next == 100) return 100;
square2 = next;
} else if (square2 > next) {
System.out.printf("Oops! Landed on a snake. Slither down to %d.\n", next);
square2 = next;
}
}
if (roll < 6 || !sixesThrowAgain) return square2;
System.out.println("Rolled a 6 so roll again.");
}
}
public static void main(String[] args) {
int[] players = {1, 1, 1};
while (true) {
for (int i = 0; i < players.length; ++i) {
int ns = turn(i + 1, players[i]);
if (ns == 100) {
System.out.printf("Player %d wins!\n", i + 1);
return;
}
players[i] = ns;
System.out.println();
}
}
}
}
| NONE = 0; LADDER = 1; SNAKE = 2; STAY = 1; MOVE = 2; WIN = 3
class Cell
@type; @to; attr_reader :type, :to
def initialize; @type = NONE; @to = 0; end
def set( t, o ); @type = t; @to = o; end
end
class Player
@pos; @name; attr_accessor :pos; attr_reader :name
def initialize( n ); @pos = 0; @name = n; end
def play( dice )
s = dice.roll; return s, STAY if @pos + s > 99
@pos += s; return s, WIN if @pos == 99
return s, MOVE
end
end
class Die
@sides; def initialize( s = 6 ); @sides = s; end
def roll; return 1 + rand( @sides ); end
end
def initBoard
@board = Array.new( 100 ); for i in 0 .. 99; @board[i] = Cell.new(); end
@board[3].set( LADDER, 13 ); @board[8].set( LADDER, 30 ); @board[19].set( LADDER, 37 );
@board[27].set( LADDER, 83 );@board[39].set( LADDER, 58 ); @board[50].set( LADDER, 66 );
@board[62].set( LADDER, 80 ); @board[70].set( LADDER, 90 ); @board[16].set( SNAKE, 6 );
@board[61].set( SNAKE, 18 ); @board[86].set( SNAKE, 23 ); @board[53].set( SNAKE, 33 );
@board[63].set( SNAKE, 59 ); @board[92].set( SNAKE, 72 ); @board[94].set( SNAKE, 74 );
@board[98].set( SNAKE, 77 );
end
def initPlayers
@players = Array.new( 4 );
for i in 0 .. @playersCount - 1; @players[i] = Player.new( "player " << i + 49 ); end
end
def play
initBoard; initPlayers; @die = Die.new
while true
for p in 0 .. @playersCount - 1
puts; puts
if( 0 == p )
print "
"Press [RETURN] to roll the die."
gets; np = @players[p].play( @die ); print "You rolled a
if np[1] == WIN
print "You reached position
elsif np[1] == STAY; print "Sorry, you cannot move!\n"
else print "Your new position is cell
end
else
np = @players[p].play( @die ); print "
if np[1] == WIN
print "He reached position
elsif np[1] == STAY; print "But he cannot move....\n"
else print "His new position is cell
end
end
s = @board[@players[p].pos].type
next if s == NONE
@players[p].pos = @board[@players[p].pos].to
case s
when SNAKE; print "What a pitty, landed on a snake. "
when LADDER; print "Lucky move! Landed on a ladder. "
end
print "New position is cell
end
end
end
@playersCount = 4; @board; @players; @die
play
|
Generate a Ruby translation of this Java snippet without changing its computational steps. | import java.util.Map;
import java.util.Random;
public class Game {
private static final Map<Integer, Integer> snl = Map.ofEntries(
Map.entry(4, 14),
Map.entry(9, 31),
Map.entry(17, 7),
Map.entry(20, 38),
Map.entry(28, 84),
Map.entry(40, 59),
Map.entry(51, 67),
Map.entry(54, 34),
Map.entry(62, 19),
Map.entry(63, 81),
Map.entry(64, 60),
Map.entry(71, 91),
Map.entry(87, 24),
Map.entry(93, 73),
Map.entry(95, 75),
Map.entry(99, 78)
);
private static final boolean sixesThrowAgain = true;
private static Random rand = new Random();
private static int turn(int player, int square) {
int square2 = square;
while (true) {
int roll = rand.nextInt(6) + 1;
System.out.printf("Player %d, on square %d, rolls a %d", player, square2, roll);
if (square2 + roll > 100) {
System.out.println(" but cannot move.");
} else {
square2 += roll;
System.out.printf(" and moves to square %d\n", square2);
if (square2 == 100) return 100;
Integer next = snl.getOrDefault(square2, square2);
if (square2 < next) {
System.out.printf("Yay! Landed on a ladder. Climb up to %d.\n", next);
if (next == 100) return 100;
square2 = next;
} else if (square2 > next) {
System.out.printf("Oops! Landed on a snake. Slither down to %d.\n", next);
square2 = next;
}
}
if (roll < 6 || !sixesThrowAgain) return square2;
System.out.println("Rolled a 6 so roll again.");
}
}
public static void main(String[] args) {
int[] players = {1, 1, 1};
while (true) {
for (int i = 0; i < players.length; ++i) {
int ns = turn(i + 1, players[i]);
if (ns == 100) {
System.out.printf("Player %d wins!\n", i + 1);
return;
}
players[i] = ns;
System.out.println();
}
}
}
}
| NONE = 0; LADDER = 1; SNAKE = 2; STAY = 1; MOVE = 2; WIN = 3
class Cell
@type; @to; attr_reader :type, :to
def initialize; @type = NONE; @to = 0; end
def set( t, o ); @type = t; @to = o; end
end
class Player
@pos; @name; attr_accessor :pos; attr_reader :name
def initialize( n ); @pos = 0; @name = n; end
def play( dice )
s = dice.roll; return s, STAY if @pos + s > 99
@pos += s; return s, WIN if @pos == 99
return s, MOVE
end
end
class Die
@sides; def initialize( s = 6 ); @sides = s; end
def roll; return 1 + rand( @sides ); end
end
def initBoard
@board = Array.new( 100 ); for i in 0 .. 99; @board[i] = Cell.new(); end
@board[3].set( LADDER, 13 ); @board[8].set( LADDER, 30 ); @board[19].set( LADDER, 37 );
@board[27].set( LADDER, 83 );@board[39].set( LADDER, 58 ); @board[50].set( LADDER, 66 );
@board[62].set( LADDER, 80 ); @board[70].set( LADDER, 90 ); @board[16].set( SNAKE, 6 );
@board[61].set( SNAKE, 18 ); @board[86].set( SNAKE, 23 ); @board[53].set( SNAKE, 33 );
@board[63].set( SNAKE, 59 ); @board[92].set( SNAKE, 72 ); @board[94].set( SNAKE, 74 );
@board[98].set( SNAKE, 77 );
end
def initPlayers
@players = Array.new( 4 );
for i in 0 .. @playersCount - 1; @players[i] = Player.new( "player " << i + 49 ); end
end
def play
initBoard; initPlayers; @die = Die.new
while true
for p in 0 .. @playersCount - 1
puts; puts
if( 0 == p )
print "
"Press [RETURN] to roll the die."
gets; np = @players[p].play( @die ); print "You rolled a
if np[1] == WIN
print "You reached position
elsif np[1] == STAY; print "Sorry, you cannot move!\n"
else print "Your new position is cell
end
else
np = @players[p].play( @die ); print "
if np[1] == WIN
print "He reached position
elsif np[1] == STAY; print "But he cannot move....\n"
else print "His new position is cell
end
end
s = @board[@players[p].pos].type
next if s == NONE
@players[p].pos = @board[@players[p].pos].to
case s
when SNAKE; print "What a pitty, landed on a snake. "
when LADDER; print "Lucky move! Landed on a ladder. "
end
print "New position is cell
end
end
end
@playersCount = 4; @board; @players; @die
play
|
Translate the given Java code snippet into Ruby without altering its behavior. |
module shop.acme.com
{
const Point(Int x, Int y);
enum Color {Red, Green, Blue}
interface Callback
{
Boolean active;
void onEvent(String event);
void onError(Exception e);
}
String DefaultLogin = "guest";
Int MAX_QUANTITY = 100;
interface Bag<Element>
extends Iterable<Element>
{
void add(Element e);
}
}
| test_variable = [1, 9, 8, 3]
test_variable.sort
test_variable
test_variable.sort!
test_variable
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | import java.util.TreeSet;
public class Farey{
private static class Frac implements Comparable<Frac>{
int num;
int den;
public Frac(int num, int den){
this.num = num;
this.den = den;
}
@Override
public String toString(){
return num + "/" + den;
}
@Override
public int compareTo(Frac o){
return Double.compare((double)num / den, (double)o.num / o.den);
}
}
public static TreeSet<Frac> genFarey(int i){
TreeSet<Frac> farey = new TreeSet<Frac>();
for(int den = 1; den <= i; den++){
for(int num = 0; num <= den; num++){
farey.add(new Frac(num, den));
}
}
return farey;
}
public static void main(String[] args){
for(int i = 1; i <= 11; i++){
System.out.println("F" + i + ": " + genFarey(i));
}
for(int i = 100; i <= 1000; i += 100){
System.out.println("F" + i + ": " + genFarey(i).size() + " members");
}
}
}
| require "big"
def farey(n)
a, b, c, d = 0, 1, 1, n
fracs = [] of BigRational
fracs << BigRational.new(0,1)
while c <= n
k = (n + b) // d
a, b, c, d = c, d, k * c - a, k * d - b
fracs << BigRational.new(a,b)
end
fracs.uniq.sort
end
puts "Farey sequence for order 1 through 11 (inclusive):"
(1..11).each do |n|
puts "F(
end
puts "Number of fractions in the Farey sequence:"
(100..1000).step(100) do |i|
puts "F(%4d) =%7d" % [i, farey(i).size]
end
|
Translate the given Java code snippet into Ruby without altering its behavior. | import java.util.TreeSet;
public class Farey{
private static class Frac implements Comparable<Frac>{
int num;
int den;
public Frac(int num, int den){
this.num = num;
this.den = den;
}
@Override
public String toString(){
return num + "/" + den;
}
@Override
public int compareTo(Frac o){
return Double.compare((double)num / den, (double)o.num / o.den);
}
}
public static TreeSet<Frac> genFarey(int i){
TreeSet<Frac> farey = new TreeSet<Frac>();
for(int den = 1; den <= i; den++){
for(int num = 0; num <= den; num++){
farey.add(new Frac(num, den));
}
}
return farey;
}
public static void main(String[] args){
for(int i = 1; i <= 11; i++){
System.out.println("F" + i + ": " + genFarey(i));
}
for(int i = 100; i <= 1000; i += 100){
System.out.println("F" + i + ": " + genFarey(i).size() + " members");
}
}
}
| require "big"
def farey(n)
a, b, c, d = 0, 1, 1, n
fracs = [] of BigRational
fracs << BigRational.new(0,1)
while c <= n
k = (n + b) // d
a, b, c, d = c, d, k * c - a, k * d - b
fracs << BigRational.new(a,b)
end
fracs.uniq.sort
end
puts "Farey sequence for order 1 through 11 (inclusive):"
(1..11).each do |n|
puts "F(
end
puts "Number of fractions in the Farey sequence:"
(100..1000).step(100) do |i|
puts "F(%4d) =%7d" % [i, farey(i).size]
end
|
Transform the following Java implementation into Ruby, maintaining the same output and logic. | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.LongStream;
public class AliquotSequenceClassifications {
private static Long properDivsSum(long n) {
return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();
}
static boolean aliquot(long n, int maxLen, long maxTerm) {
List<Long> s = new ArrayList<>(maxLen);
s.add(n);
long newN = n;
while (s.size() <= maxLen && newN < maxTerm) {
newN = properDivsSum(s.get(s.size() - 1));
if (s.contains(newN)) {
if (s.get(0) == newN) {
switch (s.size()) {
case 1:
return report("Perfect", s);
case 2:
return report("Amicable", s);
default:
return report("Sociable of length " + s.size(), s);
}
} else if (s.get(s.size() - 1) == newN) {
return report("Aspiring", s);
} else
return report("Cyclic back to " + newN, s);
} else {
s.add(newN);
if (newN == 0)
return report("Terminating", s);
}
}
return report("Non-terminating", s);
}
static boolean report(String msg, List<Long> result) {
System.out.println(msg + ": " + result);
return false;
}
public static void main(String[] args) {
long[] arr = {
11, 12, 28, 496, 220, 1184, 12496, 1264460,
790, 909, 562, 1064, 1488};
LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));
System.out.println();
Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));
}
}
| def aliquot(n, maxlen=16, maxterm=2**47)
return "terminating", [0] if n == 0
s = []
while (s << n).size <= maxlen and n < maxterm
n = n.proper_divisors.inject(0, :+)
if s.include?(n)
case n
when s[0]
case s.size
when 1 then return "perfect", s
when 2 then return "amicable", s
else return "sociable of length
end
when s[-1] then return "aspiring", s
else return "cyclic back to
end
elsif n == 0 then return "terminating", s << 0
end
end
return "non-terminating", s
end
for n in 1..10
puts "%20s: %p" % aliquot(n)
end
puts
for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]
puts "%20s: %p" % aliquot(n)
end
|
Port the following code from Java to Ruby with equivalent syntax and logic. | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.LongStream;
public class AliquotSequenceClassifications {
private static Long properDivsSum(long n) {
return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();
}
static boolean aliquot(long n, int maxLen, long maxTerm) {
List<Long> s = new ArrayList<>(maxLen);
s.add(n);
long newN = n;
while (s.size() <= maxLen && newN < maxTerm) {
newN = properDivsSum(s.get(s.size() - 1));
if (s.contains(newN)) {
if (s.get(0) == newN) {
switch (s.size()) {
case 1:
return report("Perfect", s);
case 2:
return report("Amicable", s);
default:
return report("Sociable of length " + s.size(), s);
}
} else if (s.get(s.size() - 1) == newN) {
return report("Aspiring", s);
} else
return report("Cyclic back to " + newN, s);
} else {
s.add(newN);
if (newN == 0)
return report("Terminating", s);
}
}
return report("Non-terminating", s);
}
static boolean report(String msg, List<Long> result) {
System.out.println(msg + ": " + result);
return false;
}
public static void main(String[] args) {
long[] arr = {
11, 12, 28, 496, 220, 1184, 12496, 1264460,
790, 909, 562, 1064, 1488};
LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));
System.out.println();
Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));
}
}
| def aliquot(n, maxlen=16, maxterm=2**47)
return "terminating", [0] if n == 0
s = []
while (s << n).size <= maxlen and n < maxterm
n = n.proper_divisors.inject(0, :+)
if s.include?(n)
case n
when s[0]
case s.size
when 1 then return "perfect", s
when 2 then return "amicable", s
else return "sociable of length
end
when s[-1] then return "aspiring", s
else return "cyclic back to
end
elsif n == 0 then return "terminating", s << 0
end
end
return "non-terminating", s
end
for n in 1..10
puts "%20s: %p" % aliquot(n)
end
puts
for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]
puts "%20s: %p" % aliquot(n)
end
|
Keep all operations the same but rewrite the snippet in Ruby. | public class ImplicitTypeConversion{
public static void main(String...args){
System.out.println( "Primitive conversions" );
byte by = -1;
short sh = by;
int in = sh;
long lo = in;
System.out.println( "byte value -1 to 3 integral types: " + lo );
float fl = 0.1f;
double db = fl;
System.out.println( "float value 0.1 to double: " + db );
int in2 = -1;
float fl2 = in2;
double db2 = fl2;
System.out.println( "int value -1 to float and double: " + db2 );
int in3 = Integer.MAX_VALUE;
float fl3 = in3;
double db3 = fl3;
System.out.println( "int value " + Integer.MAX_VALUE + " to float and double: " + db3 );
char ch = 'a';
int in4 = ch;
double db4 = in4;
System.out.println( "char value '" + ch + "' to int and double: " + db4 );
System.out.println();
System.out.println( "Boxing and unboxing" );
Integer in5 = -1;
int in6 = in5;
System.out.println( "int value -1 to Integer and int: " + in6 );
Double db5 = 0.1;
double db6 = db5;
System.out.println( "double value 0.1 to Double and double: " + db6 );
}
}
| > 1+"2"
> "1"+2
> sqrt(-4)
> ("a" + [1,2])
> ('ha' * '3')
> ('ha' * true)
|
Rewrite the snippet below in Ruby so it works the same as the original Java code. | public class ImplicitTypeConversion{
public static void main(String...args){
System.out.println( "Primitive conversions" );
byte by = -1;
short sh = by;
int in = sh;
long lo = in;
System.out.println( "byte value -1 to 3 integral types: " + lo );
float fl = 0.1f;
double db = fl;
System.out.println( "float value 0.1 to double: " + db );
int in2 = -1;
float fl2 = in2;
double db2 = fl2;
System.out.println( "int value -1 to float and double: " + db2 );
int in3 = Integer.MAX_VALUE;
float fl3 = in3;
double db3 = fl3;
System.out.println( "int value " + Integer.MAX_VALUE + " to float and double: " + db3 );
char ch = 'a';
int in4 = ch;
double db4 = in4;
System.out.println( "char value '" + ch + "' to int and double: " + db4 );
System.out.println();
System.out.println( "Boxing and unboxing" );
Integer in5 = -1;
int in6 = in5;
System.out.println( "int value -1 to Integer and int: " + in6 );
Double db5 = 0.1;
double db6 = db5;
System.out.println( "double value 0.1 to Double and double: " + db6 );
}
}
| > 1+"2"
> "1"+2
> sqrt(-4)
> ("a" + [1,2])
> ('ha' * '3')
> ('ha' * true)
|
Generate a Ruby translation of this Java snippet without changing its computational steps. | import java.util.ArrayList;
import java.util.List;
public class MagnanimousNumbers {
public static void main(String[] args) {
runTask("Find and display the first 45 magnanimous numbers.", 1, 45);
runTask("241st through 250th magnanimous numbers.", 241, 250);
runTask("391st through 400th magnanimous numbers.", 391, 400);
}
private static void runTask(String message, int startN, int endN) {
int count = 0;
List<Integer> nums = new ArrayList<>();
for ( int n = 0 ; count < endN ; n++ ) {
if ( isMagnanimous(n) ) {
nums.add(n);
count++;
}
}
System.out.printf("%s%n", message);
System.out.printf("%s%n%n", nums.subList(startN-1, endN));
}
private static boolean isMagnanimous(long n) {
if ( n >= 0 && n <= 9 ) {
return true;
}
long q = 11;
for ( long div = 10 ; q >= 10 ; div *= 10 ) {
q = n / div;
long r = n % div;
if ( ! isPrime(q+r) ) {
return false;
}
}
return true;
}
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;
}
}
| require "prime"
magnanimouses = Enumerator.new do |y|
(0..).each {|n| y << n if (1..n.digits.size-1).all? {|k| n.divmod(10**k).sum.prime?} }
end
puts "First 45 magnanimous numbers:"
puts magnanimouses.first(45).join(' ')
puts "\n241st through 250th magnanimous numbers:"
puts magnanimouses.first(250).last(10).join(' ')
puts "\n391st through 400th magnanimous numbers:"
puts magnanimouses.first(400).last(10).join(' ')
|
Maintain the same structure and functionality when rewriting this code in Ruby. | import java.math.BigInteger;
public class MersennePrimes {
private static final int MAX = 20;
private static final BigInteger ONE = BigInteger.ONE;
private static final BigInteger TWO = BigInteger.valueOf(2);
private static boolean isPrime(int n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
int d = 5;
while (d * d <= n) {
if (n % d == 0) return false;
d += 2;
if (n % d == 0) return false;
d += 4;
}
return true;
}
public static void main(String[] args) {
int count = 0;
int p = 2;
while (true) {
BigInteger m = TWO.shiftLeft(p - 1).subtract(ONE);
if (m.isProbablePrime(10)) {
System.out.printf("2 ^ %d - 1\n", p);
if (++count == MAX) break;
}
do {
p = (p > 2) ? p + 2 : 3;
} while (!isPrime(p));
}
}
}
| require 'openssl'
(0..).each{|n| puts "2**
|
Generate a Ruby translation of this Java snippet without changing its computational steps. | import java.math.BigInteger;
public class MersennePrimes {
private static final int MAX = 20;
private static final BigInteger ONE = BigInteger.ONE;
private static final BigInteger TWO = BigInteger.valueOf(2);
private static boolean isPrime(int n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
int d = 5;
while (d * d <= n) {
if (n % d == 0) return false;
d += 2;
if (n % d == 0) return false;
d += 4;
}
return true;
}
public static void main(String[] args) {
int count = 0;
int p = 2;
while (true) {
BigInteger m = TWO.shiftLeft(p - 1).subtract(ONE);
if (m.isProbablePrime(10)) {
System.out.printf("2 ^ %d - 1\n", p);
if (++count == MAX) break;
}
do {
p = (p > 2) ? p + 2 : 3;
} while (!isPrime(p));
}
}
}
| require 'openssl'
(0..).each{|n| puts "2**
|
Produce a language-to-language conversion: from Java to Ruby, same semantics. | import java.util.ArrayList;
import java.util.List;
public class SexyPrimes {
public static void main(String[] args) {
sieve();
int pairs = 0;
List<String> pairList = new ArrayList<>();
int triples = 0;
List<String> tripleList = new ArrayList<>();
int quadruplets = 0;
List<String> quadrupletList = new ArrayList<>();
int unsexyCount = 1;
List<String> unsexyList = new ArrayList<>();
for ( int i = 3 ; i < MAX ; i++ ) {
if ( i-6 >= 3 && primes[i-6] && primes[i] ) {
pairs++;
pairList.add((i-6) + " " + i);
if ( pairList.size() > 5 ) {
pairList.remove(0);
}
}
else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) {
unsexyCount++;
unsexyList.add("" + i);
if ( unsexyList.size() > 10 ) {
unsexyList.remove(0);
}
}
if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) {
triples++;
tripleList.add((i-12) + " " + (i-6) + " " + i);
if ( tripleList.size() > 5 ) {
tripleList.remove(0);
}
}
if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) {
quadruplets++;
quadrupletList.add((i-18) + " " + (i-12) + " " + (i-6) + " " + i);
if ( quadrupletList.size() > 5 ) {
quadrupletList.remove(0);
}
}
}
System.out.printf("Count of sexy triples less than %,d = %,d%n", MAX, pairs);
System.out.printf("The last 5 sexy pairs:%n %s%n%n", pairList.toString().replaceAll(", ", "], ["));
System.out.printf("Count of sexy triples less than %,d = %,d%n", MAX, triples);
System.out.printf("The last 5 sexy triples:%n %s%n%n", tripleList.toString().replaceAll(", ", "], ["));
System.out.printf("Count of sexy quadruplets less than %,d = %,d%n", MAX, quadruplets);
System.out.printf("The last 5 sexy quadruplets:%n %s%n%n", quadrupletList.toString().replaceAll(", ", "], ["));
System.out.printf("Count of unsexy primes less than %,d = %,d%n", MAX, unsexyCount);
System.out.printf("The last 10 unsexy primes:%n %s%n%n", unsexyList.toString().replaceAll(", ", "], ["));
}
private static int MAX = 1_000_035;
private static boolean[] primes = new boolean[MAX];
private static final void sieve() {
for ( int i = 2 ; i < MAX ; i++ ) {
primes[i] = true;
}
for ( int i = 2 ; i < MAX ; i++ ) {
if ( primes[i] ) {
for ( int j = 2*i ; j < MAX ; j += i ) {
primes[j] = false;
}
}
}
}
}
| require 'prime'
prime_array, sppair2, sppair3, sppair4, sppair5 = Array.new(5) {Array.new()}
unsexy, i, start = [2], 0, Time.now
Prime.each(1_000_100) {|prime| prime_array.push prime}
while prime_array[i] < 1_000_035
i+=1
unsexy.push(i) if prime_array[(i+1)..(i+2)].include?(prime_array[i]+6) == false && prime_array[(i-2)..(i-1)].include?(prime_array[i]-6) == false && prime_array[i]+6 < 1_000_035
prime_array[(i+1)..(i+4)].include?(prime_array[i]+6) && prime_array[i]+6 < 1_000_035 ? sppair2.push(i) : next
prime_array[(i+2)..(i+5)].include?(prime_array[i]+12) && prime_array[i]+12 < 1_000_035 ? sppair3.push(i) : next
prime_array[(i+3)..(i+6)].include?(prime_array[i]+18) && prime_array[i]+18 < 1_000_035 ? sppair4.push(i) : next
prime_array[(i+4)..(i+7)].include?(prime_array[i]+24) && prime_array[i]+24 < 1_000_035 ? sppair5.push(i) : next
end
puts "\nSexy prime pairs:
sppair2.last(5).each {|prime| print [prime_array[prime], prime_array[prime]+6].join(" - "), "\n"}
puts "\nSexy prime triplets:
sppair3.last(5).each {|prime| print [prime_array[prime], prime_array[prime]+6, prime_array[prime]+12].join(" - "), "\n"}
puts "\nSexy prime quadruplets:
sppair4.last(5).each {|prime| print [prime_array[prime], prime_array[prime]+6, prime_array[prime]+12, prime_array[prime]+18].join(" - "), "\n"}
puts "\nSexy prime quintuplets:
sppair5.last(5).each {|prime| print [prime_array[prime], prime_array[prime]+6, prime_array[prime]+12, prime_array[prime]+18, prime_array[prime]+24].join(" - "), "\n"}
puts "\nUnSexy prime:
unsexy.last(10).each {|item| print prime_array[item], " "}
print "\n\n", Time.now - start, " seconds"
|
Translate the given Java code snippet into Ruby without altering its behavior. | import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
class CubeSum implements Comparable<CubeSum> {
public long x, y, value;
public CubeSum(long x, long y) {
this.x = x;
this.y = y;
this.value = x*x*x + y*y*y;
}
public String toString() {
return String.format("%4d^3 + %4d^3", x, y);
}
public int compareTo(CubeSum that) {
return value < that.value ? -1 : value > that.value ? 1 : 0;
}
}
class SumIterator implements Iterator<CubeSum> {
PriorityQueue<CubeSum> pq = new PriorityQueue<CubeSum>();
long n = 0;
public boolean hasNext() { return true; }
public CubeSum next() {
while (pq.size() == 0 || pq.peek().value >= n*n*n)
pq.add(new CubeSum(++n, 1));
CubeSum s = pq.remove();
if (s.x > s.y + 1) pq.add(new CubeSum(s.x, s.y+1));
return s;
}
}
class TaxiIterator implements Iterator<List<CubeSum>> {
Iterator<CubeSum> sumIterator = new SumIterator();
CubeSum last = sumIterator.next();
public boolean hasNext() { return true; }
public List<CubeSum> next() {
CubeSum s;
List<CubeSum> train = new ArrayList<CubeSum>();
while ((s = sumIterator.next()).value != last.value)
last = s;
train.add(last);
do { train.add(s); } while ((s = sumIterator.next()).value == last.value);
last = s;
return train;
}
}
public class Taxi {
public static final void main(String[] args) {
Iterator<List<CubeSum>> taxi = new TaxiIterator();
for (int i = 1; i <= 2006; i++) {
List<CubeSum> t = taxi.next();
if (i > 25 && i < 2000) continue;
System.out.printf("%4d: %10d", i, t.get(0).value);
for (CubeSum s: t)
System.out.print(" = " + s);
System.out.println();
}
}
}
| def taxicab_number(nmax=1200)
[*1..nmax].repeated_combination(2).group_by{|x,y| x**3 + y**3}.select{|k,v| v.size>1}.sort
end
t = [0] + taxicab_number
[*1..25, *2000...2007].each do |i|
puts "%4d: %10d" % [i, t[i][0]] + t[i][1].map{|a| " = %4d**3 + %4d**3" % a}.join
end
|
Can you help me rewrite this code in Ruby instead of Java, keeping it the same logically? | public class StrongAndWeakPrimes {
private static int MAX = 10_000_000 + 1000;
private static boolean[] primes = new boolean[MAX];
public static void main(String[] args) {
sieve();
System.out.println("First 36 strong primes:");
displayStrongPrimes(36);
for ( int n : new int[] {1_000_000, 10_000_000}) {
System.out.printf("Number of strong primes below %,d = %,d%n", n, strongPrimesBelow(n));
}
System.out.println("First 37 weak primes:");
displayWeakPrimes(37);
for ( int n : new int[] {1_000_000, 10_000_000}) {
System.out.printf("Number of weak primes below %,d = %,d%n", n, weakPrimesBelow(n));
}
}
private static int weakPrimesBelow(int maxPrime) {
int priorPrime = 2;
int currentPrime = 3;
int count = 0;
while ( currentPrime < maxPrime ) {
int nextPrime = getNextPrime(currentPrime);
if ( currentPrime * 2 < priorPrime + nextPrime ) {
count++;
}
priorPrime = currentPrime;
currentPrime = nextPrime;
}
return count;
}
private static void displayWeakPrimes(int maxCount) {
int priorPrime = 2;
int currentPrime = 3;
int count = 0;
while ( count < maxCount ) {
int nextPrime = getNextPrime(currentPrime);
if ( currentPrime * 2 < priorPrime + nextPrime) {
count++;
System.out.printf("%d ", currentPrime);
}
priorPrime = currentPrime;
currentPrime = nextPrime;
}
System.out.println();
}
private static int getNextPrime(int currentPrime) {
int nextPrime = currentPrime + 2;
while ( ! primes[nextPrime] ) {
nextPrime += 2;
}
return nextPrime;
}
private static int strongPrimesBelow(int maxPrime) {
int priorPrime = 2;
int currentPrime = 3;
int count = 0;
while ( currentPrime < maxPrime ) {
int nextPrime = getNextPrime(currentPrime);
if ( currentPrime * 2 > priorPrime + nextPrime ) {
count++;
}
priorPrime = currentPrime;
currentPrime = nextPrime;
}
return count;
}
private static void displayStrongPrimes(int maxCount) {
int priorPrime = 2;
int currentPrime = 3;
int count = 0;
while ( count < maxCount ) {
int nextPrime = getNextPrime(currentPrime);
if ( currentPrime * 2 > priorPrime + nextPrime) {
count++;
System.out.printf("%d ", currentPrime);
}
priorPrime = currentPrime;
currentPrime = nextPrime;
}
System.out.println();
}
private static final void sieve() {
for ( int i = 2 ; i < MAX ; i++ ) {
primes[i] = true;
}
for ( int i = 2 ; i < MAX ; i++ ) {
if ( primes[i] ) {
for ( int j = 2*i ; j < MAX ; j += i ) {
primes[j] = false;
}
}
}
}
}
| require 'prime'
strong_gen = Enumerator.new{|y| Prime.each_cons(3){|a,b,c|y << b if a+c-b<b} }
weak_gen = Enumerator.new{|y| Prime.each_cons(3){|a,b,c|y << b if a+c-b>b} }
puts "First 36 strong primes:"
puts strong_gen.take(36).join(" "), "\n"
puts "First 37 weak primes:"
puts weak_gen.take(37).join(" "), "\n"
[1_000_000, 10_000_000].each do |limit|
strongs, weaks = 0, 0
Prime.each_cons(3) do |a,b,c|
strongs += 1 if b > a+c-b
weaks += 1 if b < a+c-b
break if c > limit
end
puts "
end
|
Please provide an equivalent version of this Java code in Ruby. | import java.math.BigInteger;
public class LeftFac{
public static BigInteger factorial(BigInteger n){
BigInteger ans = BigInteger.ONE;
for(BigInteger x = BigInteger.ONE; x.compareTo(n) <= 0; x = x.add(BigInteger.ONE)){
ans = ans.multiply(x);
}
return ans;
}
public static BigInteger leftFact(BigInteger n){
BigInteger ans = BigInteger.ZERO;
for(BigInteger k = BigInteger.ZERO; k.compareTo(n.subtract(BigInteger.ONE)) <= 0; k = k.add(BigInteger.ONE)){
ans = ans.add(factorial(k));
}
return ans;
}
public static void main(String[] args){
for(int i = 0; i <= 10; i++){
System.out.println("!" + i + " = " + leftFact(BigInteger.valueOf(i)));
}
for(int i = 20; i <= 110; i += 10){
System.out.println("!" + i + " = " + leftFact(BigInteger.valueOf(i)));
}
for(int i = 1000; i <= 10000; i += 1000){
System.out.println("!" + i + " has " + leftFact(BigInteger.valueOf(i)).toString().length() + " digits");
}
}
}
| left_fact = Enumerator.new do |y|
f, lf = 1, 0
1.step do |n|
y << lf
lf += f
f *= n
end
end
|
Convert this Java snippet to Ruby and keep its semantics consistent. | import java.math.BigInteger;
public class LeftFac{
public static BigInteger factorial(BigInteger n){
BigInteger ans = BigInteger.ONE;
for(BigInteger x = BigInteger.ONE; x.compareTo(n) <= 0; x = x.add(BigInteger.ONE)){
ans = ans.multiply(x);
}
return ans;
}
public static BigInteger leftFact(BigInteger n){
BigInteger ans = BigInteger.ZERO;
for(BigInteger k = BigInteger.ZERO; k.compareTo(n.subtract(BigInteger.ONE)) <= 0; k = k.add(BigInteger.ONE)){
ans = ans.add(factorial(k));
}
return ans;
}
public static void main(String[] args){
for(int i = 0; i <= 10; i++){
System.out.println("!" + i + " = " + leftFact(BigInteger.valueOf(i)));
}
for(int i = 20; i <= 110; i += 10){
System.out.println("!" + i + " = " + leftFact(BigInteger.valueOf(i)));
}
for(int i = 1000; i <= 10000; i += 1000){
System.out.println("!" + i + " has " + leftFact(BigInteger.valueOf(i)).toString().length() + " digits");
}
}
}
| left_fact = Enumerator.new do |y|
f, lf = 1, 0
1.step do |n|
y << lf
lf += f
f *= n
end
end
|
Change the following Java code into Ruby without altering its purpose. | import java.util.*;
public class StrangeUniquePrimeTriplets {
public static void main(String[] args) {
strangeUniquePrimeTriplets(30, true);
strangeUniquePrimeTriplets(1000, false);
}
private static void strangeUniquePrimeTriplets(int limit, boolean verbose) {
boolean[] sieve = primeSieve(limit * 3);
List<Integer> primeList = new ArrayList<>();
for (int p = 3; p < limit; p += 2) {
if (sieve[p])
primeList.add(p);
}
int n = primeList.size();
int[] primes = new int[n];
for (int i = 0; i < n; ++i)
primes[i] = primeList.get(i);
int count = 0;
if (verbose)
System.out.printf("Strange unique prime triplets < %d:\n", limit);
for (int i = 0; i + 2 < n; ++i) {
for (int j = i + 1; j + 1 < n; ++j) {
int s = primes[i] + primes[j];
for (int k = j + 1; k < n; ++k) {
int sum = s + primes[k];
if (sieve[sum]) {
++count;
if (verbose)
System.out.printf("%2d + %2d + %2d = %2d\n", primes[i], primes[j], primes[k], sum);
}
}
}
}
System.out.printf("\nCount of strange unique prime triplets < %d is %d.\n", limit, count);
}
private static boolean[] primeSieve(int limit) {
boolean[] sieve = new boolean[limit];
Arrays.fill(sieve, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3; ; p += 2) {
int q = p * p;
if (q >= limit)
break;
if (sieve[p]) {
int inc = 2 * p;
for (; q < limit; q += inc)
sieve[q] = false;
}
}
return sieve;
}
}
| require 'prime'
Prime.each(30).to_a.combination(3).select{|trio| trio.sum.prime? }.each do |a,b,c|
puts "
end
m = 1000
count = Prime.each(m).to_a.combination(3).count{|trio| trio.sum.prime? }
puts "Count of strange unique prime triplets <
|
Produce a functionally identical Ruby code for the snippet given in Java. | import java.util.*;
public class StrangeUniquePrimeTriplets {
public static void main(String[] args) {
strangeUniquePrimeTriplets(30, true);
strangeUniquePrimeTriplets(1000, false);
}
private static void strangeUniquePrimeTriplets(int limit, boolean verbose) {
boolean[] sieve = primeSieve(limit * 3);
List<Integer> primeList = new ArrayList<>();
for (int p = 3; p < limit; p += 2) {
if (sieve[p])
primeList.add(p);
}
int n = primeList.size();
int[] primes = new int[n];
for (int i = 0; i < n; ++i)
primes[i] = primeList.get(i);
int count = 0;
if (verbose)
System.out.printf("Strange unique prime triplets < %d:\n", limit);
for (int i = 0; i + 2 < n; ++i) {
for (int j = i + 1; j + 1 < n; ++j) {
int s = primes[i] + primes[j];
for (int k = j + 1; k < n; ++k) {
int sum = s + primes[k];
if (sieve[sum]) {
++count;
if (verbose)
System.out.printf("%2d + %2d + %2d = %2d\n", primes[i], primes[j], primes[k], sum);
}
}
}
}
System.out.printf("\nCount of strange unique prime triplets < %d is %d.\n", limit, count);
}
private static boolean[] primeSieve(int limit) {
boolean[] sieve = new boolean[limit];
Arrays.fill(sieve, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3; ; p += 2) {
int q = p * p;
if (q >= limit)
break;
if (sieve[p]) {
int inc = 2 * p;
for (; q < limit; q += inc)
sieve[q] = false;
}
}
return sieve;
}
}
| require 'prime'
Prime.each(30).to_a.combination(3).select{|trio| trio.sum.prime? }.each do |a,b,c|
puts "
end
m = 1000
count = Prime.each(m).to_a.combination(3).count{|trio| trio.sum.prime? }
puts "Count of strange unique prime triplets <
|
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version. | public class Strange {
private static final boolean[] p = {
false, false, true, true, false,
true, false, true, false, false,
false, true, false, true, false,
false, false, true, false
};
public static boolean isstrange(long n) {
if (n < 10) return false;
for (; n >= 10; n /= 10) {
if (!p[(int)(n%10 + (n/10)%10)]) return false;
}
return true;
}
public static void main(String[] args) {
long nMin = Long.parseLong(args[0]);
long nMax = Long.parseLong(args[1]);
int k = 0;
for (long n = nMin; n <= nMax; n++) {
if (isstrange(n)) {
System.out.print(n + (++k%10 != 0 ? " " : "\n"));
}
}
}
}
| $p = [
false, false, true, true, false,
true, false, true, false, false,
false, true, false, true, false,
false, false, true, false
]
def isStrange(n)
if n < 10 then
return false
end
while n >= 10 do
if not $p[n % 10 + (n / 10).floor % 10] then
return false
end
n = (n / 10).floor
end
return true
end
def test(nMin, nMax)
k = 0
for n in nMin .. nMax
if isStrange(n) then
print n
k = k + 1
if k % 10 != 0 then
print ' '
else
print "\n"
end
end
end
end
test(101, 499)
|
Generate an equivalent Ruby version of this Java code. | public class Strange {
private static final boolean[] p = {
false, false, true, true, false,
true, false, true, false, false,
false, true, false, true, false,
false, false, true, false
};
public static boolean isstrange(long n) {
if (n < 10) return false;
for (; n >= 10; n /= 10) {
if (!p[(int)(n%10 + (n/10)%10)]) return false;
}
return true;
}
public static void main(String[] args) {
long nMin = Long.parseLong(args[0]);
long nMax = Long.parseLong(args[1]);
int k = 0;
for (long n = nMin; n <= nMax; n++) {
if (isstrange(n)) {
System.out.print(n + (++k%10 != 0 ? " " : "\n"));
}
}
}
}
| $p = [
false, false, true, true, false,
true, false, true, false, false,
false, true, false, true, false,
false, false, true, false
]
def isStrange(n)
if n < 10 then
return false
end
while n >= 10 do
if not $p[n % 10 + (n / 10).floor % 10] then
return false
end
n = (n / 10).floor
end
return true
end
def test(nMin, nMax)
k = 0
for n in nMin .. nMax
if isStrange(n) then
print n
k = k + 1
if k % 10 != 0 then
print ' '
else
print "\n"
end
end
end
end
test(101, 499)
|
Port the provided Java code into Ruby while preserving the original functionality. | public class SmarandachePrimeDigitalSequence {
public static void main(String[] args) {
long s = getNextSmarandache(7);
System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 ");
for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {
if ( isPrime(s) ) {
System.out.printf("%d ", s);
count++;
}
}
System.out.printf("%n%n");
for (int i = 2 ; i <=5 ; i++ ) {
long n = (long) Math.pow(10, i);
System.out.printf("%,dth Smarandache prime-digital sequence number = %d%n", n, getSmarandachePrime(n));
}
}
private static final long getSmarandachePrime(long n) {
if ( n < 10 ) {
switch ((int) n) {
case 1: return 2;
case 2: return 3;
case 3: return 5;
case 4: return 7;
}
}
long s = getNextSmarandache(7);
long result = 0;
for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {
if ( isPrime(s) ) {
count++;
result = s;
}
}
return result;
}
private static final boolean isPrime(long test) {
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 long getNextSmarandache(long n) {
if ( n % 10 == 3 ) {
return n+4;
}
long retVal = n-4;
int k = 0;
while ( n % 10 == 7 ) {
k++;
n /= 10;
}
long digit = n % 10;
long coeff = (digit == 2 ? 1 : 2);
retVal += coeff * Math.pow(10, k);
while ( k > 1 ) {
retVal -= 5 * Math.pow(10, k-1);
k--;
}
return retVal;
}
}
| require "prime"
smarandache = Enumerator.new do|y|
prime_digits = [2,3,5,7]
prime_digits.each{|pr| y << pr}
(1..).each do |n|
prime_digits.repeated_permutation(n).each do |perm|
c = perm.join.to_i * 10
y << c + 3 if (c+3).prime?
y << c + 7 if (c+7).prime?
end
end
end
seq = smarandache.take(100)
p seq.first(25)
p seq.last
|
Rewrite the snippet below in Ruby so it works the same as the original Java code. | public class MagicSquareDoublyEven {
public static void main(String[] args) {
int n = 8;
for (int[] row : magicSquareDoublyEven(n)) {
for (int x : row)
System.out.printf("%2s ", x);
System.out.println();
}
System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2);
}
static int[][] magicSquareDoublyEven(final int n) {
if (n < 4 || n % 4 != 0)
throw new IllegalArgumentException("base must be a positive "
+ "multiple of 4");
int bits = 0b1001_0110_0110_1001;
int size = n * n;
int mult = n / 4;
int[][] result = new int[n][n];
for (int r = 0, i = 0; r < n; r++) {
for (int c = 0; c < n; c++, i++) {
int bitPos = c / mult + (r / mult) * 4;
result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
}
}
| def double_even_magic_square(n)
raise ArgumentError, "Need multiple of four" if n%4 > 0
block_size, max = n/4, n*n
pre_pat = [true, false, false, true,
false, true, true, false]
pre_pat += pre_pat.reverse
pattern = pre_pat.flat_map{|b| [b] * block_size} * block_size
flat_ar = pattern.each_with_index.map{|yes, num| yes ? num+1 : max-num}
flat_ar.each_slice(n).to_a
end
def to_string(square)
n = square.size
fmt = "%
square.inject(""){|str,row| str << fmt % row << "\n"}
end
puts to_string(double_even_magic_square(8))
|
Produce a language-to-language conversion: from Java to Ruby, same semantics. | import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import static java.awt.image.BufferedImage.*;
import static java.lang.Math.*;
import javax.swing.*;
public class PlasmaEffect extends JPanel {
float[][] plasma;
float hueShift = 0;
BufferedImage img;
public PlasmaEffect() {
Dimension dim = new Dimension(640, 640);
setPreferredSize(dim);
setBackground(Color.white);
img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);
plasma = createPlasma(dim.height, dim.width);
new Timer(42, (ActionEvent e) -> {
hueShift = (hueShift + 0.02f) % 1;
repaint();
}).start();
}
float[][] createPlasma(int w, int h) {
float[][] buffer = new float[h][w];
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
double value = sin(x / 16.0);
value += sin(y / 8.0);
value += sin((x + y) / 16.0);
value += sin(sqrt(x * x + y * y) / 8.0);
value += 4;
value /= 8;
assert (value >= 0.0 && value <= 1.0) : "Hue value out of bounds";
buffer[y][x] = (float) value;
}
return buffer;
}
void drawPlasma(Graphics2D g) {
int h = plasma.length;
int w = plasma[0].length;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
float hue = hueShift + plasma[y][x] % 1;
img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));
}
g.drawImage(img, 0, 0, null);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawPlasma(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Plasma Effect");
f.setResizable(false);
f.add(new PlasmaEffect(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
| attr_reader :buffer, :palette, :r, :g, :b, :rd, :gd, :bd, :dim
def settings
size(600, 600)
end
def setup
sketch_title 'Plasma Effect'
frame_rate 25
@r = 42
@g = 84
@b = 126
@rd = true
@gd = true
@bd = true
@dim = width * height
@buffer = Array.new(dim)
grid(width, height) do |x, y|
buffer[x + y * width] = (
(
(128 + (128 * sin(x / 32.0))) +
(128 + (128 * cos(y / 32.0))) +
(128 + (128 * sin(Math.hypot(x, y) / 32.0)))
) / 4
).to_i
end
load_pixels
end
def draw
if rd
@r -= 1
@rd = false if r.negative?
else
@r += 1
@rd = true if r > 128
end
if gd
@g -= 1
@gd = false if g.negative?
else
@g += 1
@gd = true if g > 128
end
if bd
@b -= 1
@bd = false if b.negative?
else
@b += 1
@bd = true if b > 128
end
@palette = (0..127).map do |col|
s1 = sin(col * Math::PI / 25)
s2 = sin(col * Math::PI / 50 + Math::PI / 4)
color(r + s1 * 128, g + s2 * 128, b + s1 * 128)
end
dim.times do |idx|
pixels[idx] = palette[(buffer[idx] + frame_count) & 127]
end
update_pixels
end
|
Translate this program into Ruby but keep the logic exactly as in Java. | import java.util.ArrayList;
import java.util.List;
public class SquareFree
{
private static List<Long> sieve(long limit) {
List<Long> primes = new ArrayList<Long>();
primes.add(2L);
boolean[] c = new boolean[(int)limit + 1];
long p = 3;
for (;;) {
long p2 = p * p;
if (p2 > limit) break;
for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;
for (;;) {
p += 2;
if (!c[(int)p]) break;
}
}
for (long i = 3; i <= limit; i += 2) {
if (!c[(int)i]) primes.add(i);
}
return primes;
}
private static List<Long> squareFree(long from, long to) {
long limit = (long)Math.sqrt((double)to);
List<Long> primes = sieve(limit);
List<Long> results = new ArrayList<Long>();
outer: for (long i = from; i <= to; i++) {
for (long p : primes) {
long p2 = p * p;
if (p2 > i) break;
if (i % p2 == 0) continue outer;
}
results.add(i);
}
return results;
}
private final static long TRILLION = 1000000000000L;
public static void main(String[] args) {
System.out.println("Square-free integers from 1 to 145:");
List<Long> sf = squareFree(1, 145);
for (int i = 0; i < sf.size(); i++) {
if (i > 0 && i % 20 == 0) {
System.out.println();
}
System.out.printf("%4d", sf.get(i));
}
System.out.print("\n\nSquare-free integers");
System.out.printf(" from %d to %d:\n", TRILLION, TRILLION + 145);
sf = squareFree(TRILLION, TRILLION + 145);
for (int i = 0; i < sf.size(); i++) {
if (i > 0 && i % 5 == 0) System.out.println();
System.out.printf("%14d", sf.get(i));
}
System.out.println("\n\nNumber of square-free integers:\n");
long[] tos = {100, 1000, 10000, 100000, 1000000};
for (long to : tos) {
System.out.printf(" from %d to %d = %d\n", 1, to, squareFree(1, to).size());
}
}
}
| require "prime"
class Integer
def square_free?
prime_division.none?{|pr, exp| exp > 1}
end
end
puts (1..145).select(&:square_free?).each_slice(20).map{|a| a.join(" ")}
puts
m = 10**12
puts (m..m+145).select(&:square_free?).each_slice(6).map{|a| a.join(" ")}
puts
markers = [100, 1000, 10_000, 100_000, 1_000_000]
count = 0
(1..1_000_000).each do |n|
count += 1 if n.square_free?
puts "
end
|
Rewrite this program in Ruby while keeping its functionality equivalent to the Java version. | public class SelfNumbers {
private static final int MC = 103 * 1000 * 10000 + 11 * 9 + 1;
private static final boolean[] SV = new boolean[MC + 1];
private static void sieve() {
int[] dS = new int[10_000];
for (int a = 9, i = 9999; a >= 0; a--) {
for (int b = 9; b >= 0; b--) {
for (int c = 9, s = a + b; c >= 0; c--) {
for (int d = 9, t = s + c; d >= 0; d--) {
dS[i--] = t + d;
}
}
}
}
for (int a = 0, n = 0; a < 103; a++) {
for (int b = 0, d = dS[a]; b < 1000; b++, n += 10000) {
for (int c = 0, s = d + dS[b] + n; c < 10000; c++) {
SV[dS[c] + s++] = true;
}
}
}
}
public static void main(String[] args) {
sieve();
System.out.println("The first 50 self numbers are:");
for (int i = 0, count = 0; count <= 50; i++) {
if (!SV[i]) {
count++;
if (count <= 50) {
System.out.printf("%d ", i);
} else {
System.out.printf("%n%n Index Self number%n");
}
}
}
for (int i = 0, limit = 1, count = 0; i < MC; i++) {
if (!SV[i]) {
if (++count == limit) {
System.out.printf("%,12d %,13d%n", count, i);
limit *= 10;
}
}
}
}
}
| func is_self_number(n) {
if (n < 30) {
return (((n < 10) && (n.is_odd)) || (n == 20))
}
var qd = (1 + n.ilog10)
var r = (1 + (n-1)%9)
var h = (r + 9*(r%2))/2
var ld = 10
while (h + 9*qd >= n%ld) {
ld *= 10
}
var vs = idiv(n, ld).sumdigits
n %= ld
0..qd -> none { |i|
vs + sumdigits(n - h - 9*i) == (h + 9*i)
}
}
say is_self_number.first(50).join(' ')
|
Rewrite the snippet below in Ruby so it works the same as the original Java code. | public class NivenNumberGaps {
public static void main(String[] args) {
long prevGap = 0;
long prevN = 1;
long index = 0;
System.out.println("Gap Gap Index Starting Niven");
for ( long n = 2 ; n < 20_000_000_000l ; n++ ) {
if ( isNiven(n) ) {
index++;
long curGap = n - prevN;
if ( curGap > prevGap ) {
System.out.printf("%3d %,13d %,15d%n", curGap, index, prevN);
prevGap = curGap;
}
prevN = n;
}
}
}
public static boolean isNiven(long n) {
long sum = 0;
long nSave = n;
while ( n > 0 ) {
sum += n % 10;
n /= 10;
}
return nSave % sum == 0;
}
}
| nivens = Enumerator.new {|y| (1..).each {|n| y << n if n.remainder(n.digits.sum).zero?} }
cur_gap = 0
puts 'Gap Index of gap Starting Niven'
nivens.each_cons(2).with_index(1) do |(n1, n2), i|
break if i > 10_000_000
if n2-n1 > cur_gap then
printf "%3d %15s %15s\n", n2-n1, i, n1
cur_gap = n2-n1
end
end
|
Preserve the algorithm and functionality while converting the code from Java to Ruby. | public class OldRussianMeasures {
final static String[] keys = {"tochka", "liniya", "centimeter", "diuym",
"vershok", "piad", "fut", "arshin", "meter", "sazhen", "kilometer",
"versta", "milia"};
final static double[] values = {0.000254, 0.00254, 0.01,0.0254,
0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0,
1066.8, 7467.6};
public static void main(String[] a) {
if (a.length == 2 && a[0].matches("[+-]?\\d*(\\.\\d+)?")) {
double inputVal = lookup(a[1]);
if (!Double.isNaN(inputVal)) {
double magnitude = Double.parseDouble(a[0]);
double meters = magnitude * inputVal;
System.out.printf("%s %s to: %n%n", a[0], a[1]);
for (String k: keys)
System.out.printf("%10s: %g%n", k, meters / lookup(k));
return;
}
}
System.out.println("Please provide a number and unit");
}
public static double lookup(String key) {
for (int i = 0; i < keys.length; i++)
if (keys[i].equals(key))
return values[i];
return Double.NaN;
}
}
| module Distances
RATIOS =
{arshin: 0.7112, centimeter: 0.01, diuym: 0.0254,
fut: 0.3048, kilometer: 1000.0, liniya: 0.00254,
meter: 1.0, milia: 7467.6, piad: 0.1778,
sazhen: 2.1336, tochka: 0.000254, vershok: 0.04445,
versta: 1066.8}
def self.method_missing(meth, arg)
from, to = meth.to_s.split("2").map(&:to_sym)
raise NoMethodError, meth if ([from,to]-RATIOS.keys).size > 0
RATIOS[from] * arg / RATIOS[to]
end
def self.print_others(name, num)
puts "
RATIOS.except(name.to_sym).each {|k,v| puts "
end
end
Distances.print_others("meter", 2)
puts
p Distances.meter2centimeter(3)
p Distances.arshin2meter(1)
p Distances.versta2kilometer(20)
p Distances.mile2piad(1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.