Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Produce a language-to-language conversion: from Python to Java, same semantics. | 'c' == "c"
'text' == "text"
' " '
" ' "
'\x20' == ' '
u'unicode string'
u'\u05d0'
| char a = 'a';
String b = "abc";
char doubleQuote = '"';
char singleQuote = '\'';
String singleQuotes = "''";
String doubleQuotes = "\"\"";
|
Generate an equivalent Java version of this Python code. | from collections import defaultdict, Counter
def getwords(minlength=11, fname='unixdict.txt'):
"Return set of lowercased words of > given number of characters"
with open(fname) as f:
words = f.read().strip().lower().split()
return {w for w in words if len(w) > minlength}
words11 = getwords()
word_minus_1 = defaultdict(list)
minus_1_to_word = defaultdict(list)
for w in words11:
for i in range(len(w)):
minus_1 = w[:i] + w[i+1:]
word_minus_1[minus_1].append((w, i))
if minus_1 in words11:
minus_1_to_word[minus_1].append(w)
cwords = set()
for _, v in word_minus_1.items():
if len(v) >1:
change_indices = Counter(i for wrd, i in v)
change_words = set(wrd for wrd, i in v)
words_changed = None
if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:
words_changed = [wrd for wrd, i in v
if change_indices[i] > 1]
if words_changed:
cwords.add(tuple(sorted(words_changed)))
print(f"{len(minus_1_to_word)} words that are from deleting a char from other words:")
for k, v in sorted(minus_1_to_word.items()):
print(f" {k:12} From {', '.join(v)}")
print(f"\n{len(cwords)} words that are from changing a char from other words:")
for v in sorted(cwords):
print(f" {v[0]:12} From {', '.join(v[1:])}")
| import java.io.*;
import java.util.*;
public class ChangeableWords {
public static void main(String[] args) {
try {
final String fileName = "unixdict.txt";
List<String> dictionary = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.length() > 11)
dictionary.add(line);
}
}
System.out.printf("Changeable words in %s:\n", fileName);
int n = 1;
for (String word1 : dictionary) {
for (String word2 : dictionary) {
if (word1 != word2 && hammingDistance(word1, word2) == 1)
System.out.printf("%2d: %-14s -> %s\n", n++, word1, word2);
}
}
} catch (Exception e) {
e.printStackTtexture();
}
}
private static int hammingDistance(String str1, String str2) {
int len1 = str1.length();
int len2 = str2.length();
if (len1 != len2)
return 0;
int count = 0;
for (int i = 0; i < len1; ++i) {
if (str1.charAt(i) != str2.charAt(i))
++count;
if (count == 2)
break;
}
return count;
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | from tkinter import *
import tkinter.messagebox
def maximise():
root.geometry("{}x{}+{}+{}".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))
def minimise():
root.iconify()
def delete():
if tkinter.messagebox.askokcancel("OK/Cancel","Are you sure?"):
root.quit()
root = Tk()
mx=Button(root,text="maximise",command=maximise)
mx.grid()
mx.bind(maximise)
mn=Button(root,text="minimise",command=minimise)
mn.grid()
mn.bind(minimise)
root.protocol("WM_DELETE_WINDOW",delete)
mainloop()
| import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.lang.reflect.InvocationTargetException;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class WindowController extends JFrame {
public static void main( final String[] args ) {
EventQueue.invokeLater( () -> new WindowController() );
}
private JComboBox<ControlledWindow> list;
private class ControlButton extends JButton {
private ControlButton( final String name ) {
super(
new AbstractAction( name ) {
public void actionPerformed( final ActionEvent e ) {
try {
WindowController.class.getMethod( "do" + name )
.invoke ( WindowController.this );
} catch ( final Exception x ) {
x.printStackTrace();
}
}
}
);
}
}
public WindowController() {
super( "Controller" );
final JPanel main = new JPanel();
final JPanel controls = new JPanel();
setLocationByPlatform( true );
setResizable( false );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setLayout( new BorderLayout( 3, 3 ) );
getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );
add( new JLabel( "Add windows and control them." ), BorderLayout.NORTH );
main.add( list = new JComboBox<>() );
add( main, BorderLayout.CENTER );
controls.setLayout( new GridLayout( 0, 1, 3, 3 ) );
controls.add( new ControlButton( "Add" ) );
controls.add( new ControlButton( "Hide" ) );
controls.add( new ControlButton( "Show" ) );
controls.add( new ControlButton( "Close" ) );
controls.add( new ControlButton( "Maximise" ) );
controls.add( new ControlButton( "Minimise" ) );
controls.add( new ControlButton( "Move" ) );
controls.add( new ControlButton( "Resize" ) );
add( controls, BorderLayout.EAST );
pack();
setVisible( true );
}
private static class ControlledWindow extends JFrame {
private int num;
public ControlledWindow( final int num ) {
super( Integer.toString( num ) );
this.num = num;
setLocationByPlatform( true );
getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );
setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
add( new JLabel( "I am window " + num + ". Use the controller to control me." ) );
pack();
setVisible( true );
}
public String toString() {
return "Window " + num;
}
}
public void doAdd() {
list.addItem( new ControlledWindow( list.getItemCount () + 1 ) );
pack();
}
public void doHide() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.setVisible( false );
}
public void doShow() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.setVisible( true );
}
public void doClose() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.dispose();
}
public void doMinimise() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.setState( Frame.ICONIFIED );
}
public void doMaximise() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.setExtendedState( Frame.MAXIMIZED_BOTH );
}
public void doMove() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
final int hPos = getInt( "Horizontal position?" );
if ( -1 == hPos ) {
return;
}
final int vPos = getInt( "Vertical position?" );
if ( -1 == vPos ) {
return;
}
window.setLocation ( hPos, vPos );
}
public void doResize() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
final int width = getInt( "Width?" );
if ( -1 == width ) {
return;
}
final int height = getInt( "Height?" );
if ( -1 == height ) {
return;
}
window.setBounds ( window.getX(), window.getY(), width, height );
}
private JFrame getWindow() {
final JFrame window = ( JFrame ) list.getSelectedItem();
if ( null == window ) {
JOptionPane.showMessageDialog( this, "Add a window first" );
}
return window;
}
private int getInt(final String prompt) {
final String s = JOptionPane.showInputDialog( prompt );
if ( null == s ) {
return -1;
}
try {
return Integer.parseInt( s );
} catch ( final NumberFormatException x ) {
JOptionPane.showMessageDialog( this, "Not a number" );
return -1;
}
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | from tkinter import *
import tkinter.messagebox
def maximise():
root.geometry("{}x{}+{}+{}".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))
def minimise():
root.iconify()
def delete():
if tkinter.messagebox.askokcancel("OK/Cancel","Are you sure?"):
root.quit()
root = Tk()
mx=Button(root,text="maximise",command=maximise)
mx.grid()
mx.bind(maximise)
mn=Button(root,text="minimise",command=minimise)
mn.grid()
mn.bind(minimise)
root.protocol("WM_DELETE_WINDOW",delete)
mainloop()
| import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.lang.reflect.InvocationTargetException;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class WindowController extends JFrame {
public static void main( final String[] args ) {
EventQueue.invokeLater( () -> new WindowController() );
}
private JComboBox<ControlledWindow> list;
private class ControlButton extends JButton {
private ControlButton( final String name ) {
super(
new AbstractAction( name ) {
public void actionPerformed( final ActionEvent e ) {
try {
WindowController.class.getMethod( "do" + name )
.invoke ( WindowController.this );
} catch ( final Exception x ) {
x.printStackTrace();
}
}
}
);
}
}
public WindowController() {
super( "Controller" );
final JPanel main = new JPanel();
final JPanel controls = new JPanel();
setLocationByPlatform( true );
setResizable( false );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setLayout( new BorderLayout( 3, 3 ) );
getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );
add( new JLabel( "Add windows and control them." ), BorderLayout.NORTH );
main.add( list = new JComboBox<>() );
add( main, BorderLayout.CENTER );
controls.setLayout( new GridLayout( 0, 1, 3, 3 ) );
controls.add( new ControlButton( "Add" ) );
controls.add( new ControlButton( "Hide" ) );
controls.add( new ControlButton( "Show" ) );
controls.add( new ControlButton( "Close" ) );
controls.add( new ControlButton( "Maximise" ) );
controls.add( new ControlButton( "Minimise" ) );
controls.add( new ControlButton( "Move" ) );
controls.add( new ControlButton( "Resize" ) );
add( controls, BorderLayout.EAST );
pack();
setVisible( true );
}
private static class ControlledWindow extends JFrame {
private int num;
public ControlledWindow( final int num ) {
super( Integer.toString( num ) );
this.num = num;
setLocationByPlatform( true );
getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );
setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
add( new JLabel( "I am window " + num + ". Use the controller to control me." ) );
pack();
setVisible( true );
}
public String toString() {
return "Window " + num;
}
}
public void doAdd() {
list.addItem( new ControlledWindow( list.getItemCount () + 1 ) );
pack();
}
public void doHide() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.setVisible( false );
}
public void doShow() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.setVisible( true );
}
public void doClose() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.dispose();
}
public void doMinimise() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.setState( Frame.ICONIFIED );
}
public void doMaximise() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
window.setExtendedState( Frame.MAXIMIZED_BOTH );
}
public void doMove() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
final int hPos = getInt( "Horizontal position?" );
if ( -1 == hPos ) {
return;
}
final int vPos = getInt( "Vertical position?" );
if ( -1 == vPos ) {
return;
}
window.setLocation ( hPos, vPos );
}
public void doResize() {
final JFrame window = getWindow();
if ( null == window ) {
return;
}
final int width = getInt( "Width?" );
if ( -1 == width ) {
return;
}
final int height = getInt( "Height?" );
if ( -1 == height ) {
return;
}
window.setBounds ( window.getX(), window.getY(), width, height );
}
private JFrame getWindow() {
final JFrame window = ( JFrame ) list.getSelectedItem();
if ( null == window ) {
JOptionPane.showMessageDialog( this, "Add a window first" );
}
return window;
}
private int getInt(final String prompt) {
final String s = JOptionPane.showInputDialog( prompt );
if ( null == s ) {
return -1;
}
try {
return Integer.parseInt( s );
} catch ( final NumberFormatException x ) {
JOptionPane.showMessageDialog( this, "Not a number" );
return -1;
}
}
}
|
Produce a functionally identical Java code for the snippet given in Python. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
p = 3
i = 2
print("2 3", end = " ");
while True:
if isPrime(p + i) == 1:
p += i
print(p, end = " ");
i += 2
if p + i >= 1050:
break
| class SpecialPrimes {
private static boolean isPrime(int n) {
if (n < 2) return false;
if (n%2 == 0) return n == 2;
if (n%3 == 0) return n == 3;
int d = 5;
while (d*d <= n) {
if (n%d == 0) return false;
d += 2;
if (n%d == 0) return false;
d += 4;
}
return true;
}
public static void main(String[] args) {
System.out.println("Special primes under 1,050:");
System.out.println("Prime1 Prime2 Gap");
int lastSpecial = 3;
int lastGap = 1;
System.out.printf("%6d %6d %3d\n", 2, 3, lastGap);
for (int i = 5; i < 1050; i += 2) {
if (isPrime(i) && (i-lastSpecial) > lastGap) {
lastGap = i - lastSpecial;
System.out.printf("%6d %6d %3d\n", lastSpecial, i, lastGap);
lastSpecial = i;
}
}
}
}
|
Convert this Python snippet to Java and keep its semantics consistent. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
p = 3
i = 2
print("2 3", end = " ");
while True:
if isPrime(p + i) == 1:
p += i
print(p, end = " ");
i += 2
if p + i >= 1050:
break
| class SpecialPrimes {
private static boolean isPrime(int n) {
if (n < 2) return false;
if (n%2 == 0) return n == 2;
if (n%3 == 0) return n == 3;
int d = 5;
while (d*d <= n) {
if (n%d == 0) return false;
d += 2;
if (n%d == 0) return false;
d += 4;
}
return true;
}
public static void main(String[] args) {
System.out.println("Special primes under 1,050:");
System.out.println("Prime1 Prime2 Gap");
int lastSpecial = 3;
int lastGap = 1;
System.out.printf("%6d %6d %3d\n", 2, 3, lastGap);
for (int i = 5; i < 1050; i += 2) {
if (isPrime(i) && (i-lastSpecial) > lastGap) {
lastGap = i - lastSpecial;
System.out.printf("%6d %6d %3d\n", lastSpecial, i, lastGap);
lastSpecial = i;
}
}
}
}
|
Port the provided Python code into Java while preserving the original functionality. |
from functools import (reduce)
def mayanNumerals(n):
return showIntAtBase(20)(
mayanDigit
)(n)([])
def mayanDigit(n):
if 0 < n:
r = n % 5
return [
(['●' * r] if 0 < r else []) +
(['━━'] * (n // 5))
]
else:
return ['Θ']
def mayanFramed(n):
return 'Mayan ' + str(n) + ':\n\n' + (
wikiTable({
'class': 'wikitable',
'style': cssFromDict({
'text-align': 'center',
'background-color': '
'color': '
'border': '2px solid silver'
}),
'colwidth': '3em',
'cell': 'vertical-align: bottom;'
})([[
'<br>'.join(col) for col in mayanNumerals(n)
]])
)
def main():
print(
main.__doc__ + ':\n\n' +
'\n'.join(mayanFramed(n) for n in [
4005, 8017, 326205, 886205, 1081439556,
1000000, 1000000000
])
)
def wikiTable(opts):
def colWidth():
return 'width:' + opts['colwidth'] + '; ' if (
'colwidth' in opts
) else ''
def cellStyle():
return opts['cell'] if 'cell' in opts else ''
return lambda rows: '{| ' + reduce(
lambda a, k: (
a + k + '="' + opts[k] + '" ' if (
k in opts
) else a
),
['class', 'style'],
''
) + '\n' + '\n|-\n'.join(
'\n'.join(
('|' if (
0 != i and ('cell' not in opts)
) else (
'|style="' + colWidth() + cellStyle() + '"|'
)) + (
str(x) or ' '
) for x in row
) for i, row in enumerate(rows)
) + '\n|}\n\n'
def cssFromDict(dct):
return reduce(
lambda a, k: a + k + ':' + dct[k] + '; ',
dct.keys(),
''
)
def showIntAtBase(base):
def wrap(toChr, n, rs):
def go(nd, r):
n, d = nd
r_ = toChr(d) + r
return go(divmod(n, base), r_) if 0 != n else r_
return 'unsupported base' if 1 >= base else (
'negative number' if 0 > n else (
go(divmod(n, base), rs))
)
return lambda toChr: lambda n: lambda rs: (
wrap(toChr, n, rs)
)
if __name__ == '__main__':
main()
| import java.math.BigInteger;
public class MayanNumerals {
public static void main(String[] args) {
for ( long base10 : new long[] {4005, 8017, 326205, 886205, 1000000000, 1081439556L, 26960840421L, 503491211079L }) {
displayMyan(BigInteger.valueOf(base10));
System.out.printf("%n");
}
}
private static char[] digits = "0123456789ABCDEFGHJK".toCharArray();
private static BigInteger TWENTY = BigInteger.valueOf(20);
private static void displayMyan(BigInteger numBase10) {
System.out.printf("As base 10: %s%n", numBase10);
String numBase20 = "";
while ( numBase10.compareTo(BigInteger.ZERO) > 0 ) {
numBase20 = digits[numBase10.mod(TWENTY).intValue()] + numBase20;
numBase10 = numBase10.divide(TWENTY);
}
System.out.printf("As base 20: %s%nAs Mayan:%n", numBase20);
displayMyanLine1(numBase20);
displayMyanLine2(numBase20);
displayMyanLine3(numBase20);
displayMyanLine4(numBase20);
displayMyanLine5(numBase20);
displayMyanLine6(numBase20);
}
private static char boxUL = Character.toChars(9556)[0];
private static char boxTeeUp = Character.toChars(9574)[0];
private static char boxUR = Character.toChars(9559)[0];
private static char boxHorz = Character.toChars(9552)[0];
private static char boxVert = Character.toChars(9553)[0];
private static char theta = Character.toChars(952)[0];
private static char boxLL = Character.toChars(9562)[0];
private static char boxLR = Character.toChars(9565)[0];
private static char boxTeeLow = Character.toChars(9577)[0];
private static char bullet = Character.toChars(8729)[0];
private static char dash = Character.toChars(9472)[0];
private static void displayMyanLine1(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxUL);
}
for ( int j = 0 ; j < 4 ; j++ ) {
sb.append(boxHorz);
}
sb.append(i < chars.length-1 ? boxTeeUp : boxUR);
}
System.out.println(sb.toString());
}
private static String getBullet(int count) {
StringBuilder sb = new StringBuilder();
switch ( count ) {
case 1: sb.append(" " + bullet + " "); break;
case 2: sb.append(" " + bullet + bullet + " "); break;
case 3: sb.append("" + bullet + bullet + bullet + " "); break;
case 4: sb.append("" + bullet + bullet + bullet + bullet); break;
default: throw new IllegalArgumentException("Must be 1-4: " + count);
}
return sb.toString();
}
private static void displayMyanLine2(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxVert);
}
switch ( chars[i] ) {
case 'G': sb.append(getBullet(1)); break;
case 'H': sb.append(getBullet(2)); break;
case 'J': sb.append(getBullet(3)); break;
case 'K': sb.append(getBullet(4)); break;
default : sb.append(" ");
}
sb.append(boxVert);
}
System.out.println(sb.toString());
}
private static String DASH = getDash();
private static String getDash() {
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < 4 ; i++ ) {
sb.append(dash);
}
return sb.toString();
}
private static void displayMyanLine3(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxVert);
}
switch ( chars[i] ) {
case 'B': sb.append(getBullet(1)); break;
case 'C': sb.append(getBullet(2)); break;
case 'D': sb.append(getBullet(3)); break;
case 'E': sb.append(getBullet(4)); break;
case 'F': case 'G': case 'H': case 'J': case 'K':
sb.append(DASH); break;
default : sb.append(" ");
}
sb.append(boxVert);
}
System.out.println(sb.toString());
}
private static void displayMyanLine4(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxVert);
}
switch ( chars[i] ) {
case '6': sb.append(getBullet(1)); break;
case '7': sb.append(getBullet(2)); break;
case '8': sb.append(getBullet(3)); break;
case '9': sb.append(getBullet(4)); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'J': case 'K':
sb.append(DASH); break;
default : sb.append(" ");
}
sb.append(boxVert);
}
System.out.println(sb.toString());
}
private static void displayMyanLine5(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxVert);
}
switch ( chars[i] ) {
case '0': sb.append(" " + theta + " "); break;
case '1': sb.append(getBullet(1)); break;
case '2': sb.append(getBullet(2)); break;
case '3': sb.append(getBullet(3)); break;
case '4': sb.append(getBullet(4)); break;
case '5': case '6': case '7': case '8': case '9':
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'J': case 'K':
sb.append(DASH); break;
default : sb.append(" ");
}
sb.append(boxVert);
}
System.out.println(sb.toString());
}
private static void displayMyanLine6(String base20) {
char[] chars = base20.toCharArray();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < chars.length ; i++ ) {
if ( i == 0 ) {
sb.append(boxLL);
}
for ( int j = 0 ; j < 4 ; j++ ) {
sb.append(boxHorz);
}
sb.append(i < chars.length-1 ? boxTeeLow : boxLR);
}
System.out.println(sb.toString());
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | range17 = range(17)
a = [['0'] * 17 for i in range17]
idx = [0] * 4
def find_group(mark, min_n, max_n, depth=1):
if (depth == 4):
prefix = "" if (mark == '1') else "un"
print("Fail, found totally {}connected group:".format(prefix))
for i in range(4):
print(idx[i])
return True
for i in range(min_n, max_n):
n = 0
while (n < depth):
if (a[idx[n]][i] != mark):
break
n += 1
if (n == depth):
idx[n] = i
if (find_group(mark, 1, max_n, depth + 1)):
return True
return False
if __name__ == '__main__':
for i in range17:
a[i][i] = '-'
for k in range(4):
for i in range17:
j = (i + pow(2, k)) % 17
a[i][j] = a[j][i] = '1'
for row in a:
print(' '.join(row))
for i in range17:
idx[0] = i
if (find_group('1', i + 1, 17) or find_group('0', i + 1, 17)):
print("no good")
exit()
print("all good")
| import java.util.Arrays;
import java.util.stream.IntStream;
public class RamseysTheorem {
static char[][] createMatrix() {
String r = "-" + Integer.toBinaryString(53643);
int len = r.length();
return IntStream.range(0, len)
.mapToObj(i -> r.substring(len - i) + r.substring(0, len - i))
.map(String::toCharArray)
.toArray(char[][]::new);
}
static String ramseyCheck(char[][] mat) {
int len = mat.length;
char[] connectivity = "------".toCharArray();
for (int a = 0; a < len; a++) {
for (int b = 0; b < len; b++) {
if (a == b)
continue;
connectivity[0] = mat[a][b];
for (int c = 0; c < len; c++) {
if (a == c || b == c)
continue;
connectivity[1] = mat[a][c];
connectivity[2] = mat[b][c];
for (int d = 0; d < len; d++) {
if (a == d || b == d || c == d)
continue;
connectivity[3] = mat[a][d];
connectivity[4] = mat[b][d];
connectivity[5] = mat[c][d];
String conn = new String(connectivity);
if (conn.indexOf('0') == -1)
return String.format("Fail, found wholly connected: "
+ "%d %d %d %d", a, b, c, d);
else if (conn.indexOf('1') == -1)
return String.format("Fail, found wholly unconnected: "
+ "%d %d %d %d", a, b, c, d);
}
}
}
}
return "Satisfies Ramsey condition.";
}
public static void main(String[] a) {
char[][] mat = createMatrix();
for (char[] s : mat)
System.out.println(Arrays.toString(s));
System.out.println(ramseyCheck(mat));
}
}
|
Port the provided Python code into Java while preserving the original functionality. |
import tkinter as tk
root = tk.Tk()
root.state('zoomed')
root.update_idletasks()
tk.Label(root, text=(str(root.winfo_width())+ " x " +str(root.winfo_height())),
font=("Helvetica", 25)).pack()
root.mainloop()
| import java.awt.*;
import javax.swing.JFrame;
public class Test extends JFrame {
public static void main(String[] args) {
new Test();
}
Test() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
System.out.println("Physical screen size: " + screenSize);
Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());
System.out.println("Insets: " + insets);
screenSize.width -= (insets.left + insets.right);
screenSize.height -= (insets.top + insets.bottom);
System.out.println("Max available: " + screenSize);
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | import random
from collections import OrderedDict
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',
10 ** 36: 'undecillion',
10 ** 39: 'duodecillion',
10 ** 42: 'tredecillion',
10 ** 45: 'quattuordecillion',
10 ** 48: 'quinquadecillion',
10 ** 51: 'sedecillion',
10 ** 54: 'septendecillion',
10 ** 57: 'octodecillion',
10 ** 60: 'novendecillion',
10 ** 63: 'vigintillion',
10 ** 66: 'unvigintillion',
10 ** 69: 'duovigintillion',
10 ** 72: 'tresvigintillion',
10 ** 75: 'quattuorvigintillion',
10 ** 78: 'quinquavigintillion',
10 ** 81: 'sesvigintillion',
10 ** 84: 'septemvigintillion',
10 ** 87: 'octovigintillion',
10 ** 90: 'novemvigintillion',
10 ** 93: 'trigintillion',
10 ** 96: 'untrigintillion',
10 ** 99: 'duotrigintillion',
10 ** 102: 'trestrigintillion',
10 ** 105: 'quattuortrigintillion',
10 ** 108: 'quinquatrigintillion',
10 ** 111: 'sestrigintillion',
10 ** 114: 'septentrigintillion',
10 ** 117: 'octotrigintillion',
10 ** 120: 'noventrigintillion',
10 ** 123: 'quadragintillion',
10 ** 153: 'quinquagintillion',
10 ** 183: 'sexagintillion',
10 ** 213: 'septuagintillion',
10 ** 243: 'octogintillion',
10 ** 273: 'nonagintillion',
10 ** 303: 'centillion',
10 ** 306: 'uncentillion',
10 ** 309: 'duocentillion',
10 ** 312: 'trescentillion',
10 ** 333: 'decicentillion',
10 ** 336: 'undecicentillion',
10 ** 363: 'viginticentillion',
10 ** 366: 'unviginticentillion',
10 ** 393: 'trigintacentillion',
10 ** 423: 'quadragintacentillion',
10 ** 453: 'quinquagintacentillion',
10 ** 483: 'sexagintacentillion',
10 ** 513: 'septuagintacentillion',
10 ** 543: 'octogintacentillion',
10 ** 573: 'nonagintacentillion',
10 ** 603: 'ducentillion',
10 ** 903: 'trecentillion',
10 ** 1203: 'quadringentillion',
10 ** 1503: 'quingentillion',
10 ** 1803: 'sescentillion',
10 ** 2103: 'septingentillion',
10 ** 2403: 'octingentillion',
10 ** 2703: 'nongentillion',
10 ** 3003: 'millinillion'
}
numbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True))
def string_representation(i: int) -> str:
if i == 0:
return 'zero'
words = ['negative'] if i < 0 else []
working_copy = abs(i)
for key, value in numbers.items():
if key <= working_copy:
times = int(working_copy / key)
if key >= 100:
words.append(string_representation(times))
words.append(value)
working_copy -= times * key
if working_copy == 0:
break
return ' '.join(words)
def next_phrase(i: int):
while not i == 4:
str_i = string_representation(i)
len_i = len(str_i)
yield str_i, 'is', string_representation(len_i)
i = len_i
yield string_representation(i), 'is', 'magic'
def magic(i: int) -> str:
phrases = []
for phrase in next_phrase(i):
phrases.append(' '.join(phrase))
return f'{", ".join(phrases)}.'.capitalize()
if __name__ == '__main__':
for j in (random.randint(0, 10 ** 3) for i in range(5)):
print(j, ':\n', magic(j), '\n')
for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)):
print(j, ':\n', magic(j), '\n')
| 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 ) : "");
}
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. | In [6]: def dec(n):
...: return len(n.rsplit('.')[-1]) if '.' in n else 0
In [7]: dec('12.345')
Out[7]: 3
In [8]: dec('12.3450')
Out[8]: 4
In [9]:
| 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);
}
|
Translate the given Python code snippet into Java without altering its behavior. | >>> from enum import Enum
>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')
>>> Contact.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))
>>>
>>>
>>> class Contact2(Enum):
FIRST_NAME = 1
LAST_NAME = 2
PHONE = 3
>>> Contact2.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))
>>>
| enum Fruits{
APPLE, BANANA, CHERRY
}
|
Write a version of this Python function in Java with identical behavior. | try:
import psyco
psyco.full()
except ImportError:
pass
MAX_N = 300
BRANCH = 4
ra = [0] * MAX_N
unrooted = [0] * MAX_N
def tree(br, n, l, sum = 1, cnt = 1):
global ra, unrooted, MAX_N, BRANCH
for b in xrange(br + 1, BRANCH + 1):
sum += n
if sum >= MAX_N:
return
if l * 2 >= sum and b >= BRANCH:
return
if b == br + 1:
c = ra[n] * cnt
else:
c = c * (ra[n] + (b - br - 1)) / (b - br)
if l * 2 < sum:
unrooted[sum] += c
if b < BRANCH:
ra[sum] += c;
for m in range(1, n):
tree(b, m, l, sum, c)
def bicenter(s):
global ra, unrooted
if not (s & 1):
aux = ra[s / 2]
unrooted[s] += aux * (aux + 1) / 2
def main():
global ra, unrooted, MAX_N
ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1
for n in xrange(1, MAX_N):
tree(0, n, n)
bicenter(n)
print "%d: %d" % (n, unrooted[n])
main()
| import java.math.BigInteger;
import java.util.Arrays;
class Test {
final static int nMax = 250;
final static int nBranches = 4;
static BigInteger[] rooted = new BigInteger[nMax + 1];
static BigInteger[] unrooted = new BigInteger[nMax + 1];
static BigInteger[] c = new BigInteger[nBranches];
static void tree(int br, int n, int l, int inSum, BigInteger cnt) {
int sum = inSum;
for (int b = br + 1; b <= nBranches; b++) {
sum += n;
if (sum > nMax || (l * 2 >= sum && b >= nBranches))
return;
BigInteger tmp = rooted[n];
if (b == br + 1) {
c[br] = tmp.multiply(cnt);
} else {
c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));
c[br] = c[br].divide(BigInteger.valueOf(b - br));
}
if (l * 2 < sum)
unrooted[sum] = unrooted[sum].add(c[br]);
if (b < nBranches)
rooted[sum] = rooted[sum].add(c[br]);
for (int m = n - 1; m > 0; m--)
tree(b, m, l, sum, c[br]);
}
}
static void bicenter(int s) {
if ((s & 1) == 0) {
BigInteger tmp = rooted[s / 2];
tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);
unrooted[s] = unrooted[s].add(tmp.shiftRight(1));
}
}
public static void main(String[] args) {
Arrays.fill(rooted, BigInteger.ZERO);
Arrays.fill(unrooted, BigInteger.ZERO);
rooted[0] = rooted[1] = BigInteger.ONE;
unrooted[0] = unrooted[1] = BigInteger.ONE;
for (int n = 1; n <= nMax; n++) {
tree(0, n, n, 1, BigInteger.ONE);
bicenter(n);
System.out.printf("%d: %s%n", n, unrooted[n]);
}
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | try:
import psyco
psyco.full()
except ImportError:
pass
MAX_N = 300
BRANCH = 4
ra = [0] * MAX_N
unrooted = [0] * MAX_N
def tree(br, n, l, sum = 1, cnt = 1):
global ra, unrooted, MAX_N, BRANCH
for b in xrange(br + 1, BRANCH + 1):
sum += n
if sum >= MAX_N:
return
if l * 2 >= sum and b >= BRANCH:
return
if b == br + 1:
c = ra[n] * cnt
else:
c = c * (ra[n] + (b - br - 1)) / (b - br)
if l * 2 < sum:
unrooted[sum] += c
if b < BRANCH:
ra[sum] += c;
for m in range(1, n):
tree(b, m, l, sum, c)
def bicenter(s):
global ra, unrooted
if not (s & 1):
aux = ra[s / 2]
unrooted[s] += aux * (aux + 1) / 2
def main():
global ra, unrooted, MAX_N
ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1
for n in xrange(1, MAX_N):
tree(0, n, n)
bicenter(n)
print "%d: %d" % (n, unrooted[n])
main()
| import java.math.BigInteger;
import java.util.Arrays;
class Test {
final static int nMax = 250;
final static int nBranches = 4;
static BigInteger[] rooted = new BigInteger[nMax + 1];
static BigInteger[] unrooted = new BigInteger[nMax + 1];
static BigInteger[] c = new BigInteger[nBranches];
static void tree(int br, int n, int l, int inSum, BigInteger cnt) {
int sum = inSum;
for (int b = br + 1; b <= nBranches; b++) {
sum += n;
if (sum > nMax || (l * 2 >= sum && b >= nBranches))
return;
BigInteger tmp = rooted[n];
if (b == br + 1) {
c[br] = tmp.multiply(cnt);
} else {
c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));
c[br] = c[br].divide(BigInteger.valueOf(b - br));
}
if (l * 2 < sum)
unrooted[sum] = unrooted[sum].add(c[br]);
if (b < nBranches)
rooted[sum] = rooted[sum].add(c[br]);
for (int m = n - 1; m > 0; m--)
tree(b, m, l, sum, c[br]);
}
}
static void bicenter(int s) {
if ((s & 1) == 0) {
BigInteger tmp = rooted[s / 2];
tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);
unrooted[s] = unrooted[s].add(tmp.shiftRight(1));
}
}
public static void main(String[] args) {
Arrays.fill(rooted, BigInteger.ZERO);
Arrays.fill(unrooted, BigInteger.ZERO);
rooted[0] = rooted[1] = BigInteger.ONE;
unrooted[0] = unrooted[1] = BigInteger.ONE;
for (int n = 1; n <= nMax; n++) {
tree(0, n, n, 1, BigInteger.ONE);
bicenter(n);
System.out.printf("%d: %s%n", n, unrooted[n]);
}
}
}
|
Please provide an equivalent version of this Python code in Java. | import turtle
turtle.bgcolor("green")
t = turtle.Turtle()
t.color("red", "blue")
t.begin_fill()
for i in range(0, 5):
t.forward(200)
t.right(144)
t.end_fill()
| import java.awt.*;
import java.awt.geom.Path2D;
import javax.swing.*;
public class Pentagram extends JPanel {
final double degrees144 = Math.toRadians(144);
public Pentagram() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
}
private void drawPentagram(Graphics2D g, int len, int x, int y,
Color fill, Color stroke) {
double angle = 0;
Path2D p = new Path2D.Float();
p.moveTo(x, y);
for (int i = 0; i < 5; i++) {
int x2 = x + (int) (Math.cos(angle) * len);
int y2 = y + (int) (Math.sin(-angle) * len);
p.lineTo(x2, y2);
x = x2;
y = y2;
angle -= degrees144;
}
p.closePath();
g.setColor(fill);
g.fill(p);
g.setColor(stroke);
g.draw(p);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));
drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Pentagram");
f.setResizable(false);
f.add(new Pentagram(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | import turtle
turtle.bgcolor("green")
t = turtle.Turtle()
t.color("red", "blue")
t.begin_fill()
for i in range(0, 5):
t.forward(200)
t.right(144)
t.end_fill()
| import java.awt.*;
import java.awt.geom.Path2D;
import javax.swing.*;
public class Pentagram extends JPanel {
final double degrees144 = Math.toRadians(144);
public Pentagram() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
}
private void drawPentagram(Graphics2D g, int len, int x, int y,
Color fill, Color stroke) {
double angle = 0;
Path2D p = new Path2D.Float();
p.moveTo(x, y);
for (int i = 0; i < 5; i++) {
int x2 = x + (int) (Math.cos(angle) * len);
int y2 = y + (int) (Math.sin(-angle) * len);
p.lineTo(x2, y2);
x = x2;
y = y2;
angle -= degrees144;
}
p.closePath();
g.setColor(fill);
g.fill(p);
g.setColor(stroke);
g.draw(p);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));
drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Pentagram");
f.setResizable(false);
f.add(new Pentagram(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Change the following Python code into Java without altering its purpose. | import turtle
turtle.bgcolor("green")
t = turtle.Turtle()
t.color("red", "blue")
t.begin_fill()
for i in range(0, 5):
t.forward(200)
t.right(144)
t.end_fill()
| import java.awt.*;
import java.awt.geom.Path2D;
import javax.swing.*;
public class Pentagram extends JPanel {
final double degrees144 = Math.toRadians(144);
public Pentagram() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
}
private void drawPentagram(Graphics2D g, int len, int x, int y,
Color fill, Color stroke) {
double angle = 0;
Path2D p = new Path2D.Float();
p.moveTo(x, y);
for (int i = 0; i < 5; i++) {
int x2 = x + (int) (Math.cos(angle) * len);
int y2 = y + (int) (Math.sin(-angle) * len);
p.lineTo(x2, y2);
x = x2;
y = y2;
angle -= degrees144;
}
p.closePath();
g.setColor(fill);
g.fill(p);
g.setColor(stroke);
g.draw(p);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));
drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Pentagram");
f.setResizable(false);
f.add(new Pentagram(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | from ipaddress import ip_address
from urllib.parse import urlparse
tests = [
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:80",
"::192.168.0.1",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80" ]
def parse_ip_port(netloc):
try:
ip = ip_address(netloc)
port = None
except ValueError:
parsed = urlparse('//{}'.format(netloc))
ip = ip_address(parsed.hostname)
port = parsed.port
return ip, port
for address in tests:
ip, port = parse_ip_port(address)
hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))
print("{:39s} {:>32s} IPv{} port={}".format(
str(ip), hex_ip, ip.version, port ))
| 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;
}
}
|
Generate an equivalent Java version of this Python code. | from collections import defaultdict
import urllib.request
CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}
URL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
def getwords(url):
return urllib.request.urlopen(url).read().decode("utf-8").lower().split()
def mapnum2words(words):
number2words = defaultdict(list)
reject = 0
for word in words:
try:
number2words[''.join(CH2NUM[ch] for ch in word)].append(word)
except KeyError:
reject += 1
return dict(number2words), reject
def interactiveconversions():
global inp, ch, num
while True:
inp = input("\nType a number or a word to get the translation and textonyms: ").strip().lower()
if inp:
if all(ch in '23456789' for ch in inp):
if inp in num2words:
print(" Number {0} has the following textonyms in the dictionary: {1}".format(inp, ', '.join(
num2words[inp])))
else:
print(" Number {0} has no textonyms in the dictionary.".format(inp))
elif all(ch in CH2NUM for ch in inp):
num = ''.join(CH2NUM[ch] for ch in inp)
print(" Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}".format(
inp, ('' if inp in wordset else "n't"), num, ', '.join(num2words[num])))
else:
print(" I don't understand %r" % inp)
else:
print("Thank you")
break
if __name__ == '__main__':
words = getwords(URL)
print("Read %i words from %r" % (len(words), URL))
wordset = set(words)
num2words, reject = mapnum2words(words)
morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)
maxwordpernum = max(len(values) for values in num2words.values())
print(.format(len(words) - reject, URL, len(num2words), morethan1word))
print("\nThe numbers mapping to the most words map to %i words each:" % maxwordpernum)
maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)
for num, wrds in maxwpn:
print(" %s maps to: %s" % (num, ', '.join(wrds)))
interactiveconversions()
| import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Vector;
public class RTextonyms {
private static final Map<Character, Character> mapping;
private int total, elements, textonyms, max_found;
private String filename, mappingResult;
private Vector<String> max_strings;
private Map<String, Vector<String>> values;
static {
mapping = new HashMap<Character, Character>();
mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2');
mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3');
mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4');
mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5');
mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6');
mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7');
mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8');
mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9');
}
public RTextonyms(String filename) {
this.filename = filename;
this.total = this.elements = this.textonyms = this.max_found = 0;
this.values = new HashMap<String, Vector<String>>();
this.max_strings = new Vector<String>();
return;
}
public void add(String line) {
String mapping = "";
total++;
if (!get_mapping(line)) {
return;
}
mapping = mappingResult;
if (values.get(mapping) == null) {
values.put(mapping, new Vector<String>());
}
int num_strings;
num_strings = values.get(mapping).size();
textonyms += num_strings == 1 ? 1 : 0;
elements++;
if (num_strings > max_found) {
max_strings.clear();
max_strings.add(mapping);
max_found = num_strings;
}
else if (num_strings == max_found) {
max_strings.add(mapping);
}
values.get(mapping).add(line);
return;
}
public void results() {
System.out.printf("Read %,d words from %s%n%n", total, filename);
System.out.printf("There are %,d words in %s which can be represented by the digit key mapping.%n", elements,
filename);
System.out.printf("They require %,d digit combinations to represent them.%n", values.size());
System.out.printf("%,d digit combinations represent Textonyms.%n", textonyms);
System.out.printf("The numbers mapping to the most words map to %,d words each:%n", max_found + 1);
for (String key : max_strings) {
System.out.printf("%16s maps to: %s%n", key, values.get(key).toString());
}
System.out.println();
return;
}
public void match(String key) {
Vector<String> match;
match = values.get(key);
if (match == null) {
System.out.printf("Key %s not found%n", key);
}
else {
System.out.printf("Key %s matches: %s%n", key, match.toString());
}
return;
}
private boolean get_mapping(String line) {
mappingResult = line;
StringBuilder mappingBuilder = new StringBuilder();
for (char cc : line.toCharArray()) {
if (Character.isAlphabetic(cc)) {
mappingBuilder.append(mapping.get(Character.toUpperCase(cc)));
}
else if (Character.isDigit(cc)) {
mappingBuilder.append(cc);
}
else {
return false;
}
}
mappingResult = mappingBuilder.toString();
return true;
}
public static void main(String[] args) {
String filename;
if (args.length > 0) {
filename = args[0];
}
else {
filename = "./unixdict.txt";
}
RTextonyms tc;
tc = new RTextonyms(filename);
Path fp = Paths.get(filename);
try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) {
while (fs.hasNextLine()) {
tc.add(fs.nextLine());
}
}
catch (IOException ex) {
ex.printStackTrace();
}
List<String> numbers = Arrays.asList(
"001", "228", "27484247", "7244967473642",
"."
);
tc.results();
for (String number : numbers) {
if (number.equals(".")) {
System.out.println();
}
else {
tc.match(number);
}
}
return;
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | from __future__ import print_function
import matplotlib.pyplot as plt
class AStarGraph(object):
def __init__(self):
self.barriers = []
self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])
def heuristic(self, start, goal):
D = 1
D2 = 1
dx = abs(start[0] - goal[0])
dy = abs(start[1] - goal[1])
return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)
def get_vertex_neighbours(self, pos):
n = []
for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:
x2 = pos[0] + dx
y2 = pos[1] + dy
if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:
continue
n.append((x2, y2))
return n
def move_cost(self, a, b):
for barrier in self.barriers:
if b in barrier:
return 100
return 1
def AStarSearch(start, end, graph):
G = {}
F = {}
G[start] = 0
F[start] = graph.heuristic(start, end)
closedVertices = set()
openVertices = set([start])
cameFrom = {}
while len(openVertices) > 0:
current = None
currentFscore = None
for pos in openVertices:
if current is None or F[pos] < currentFscore:
currentFscore = F[pos]
current = pos
if current == end:
path = [current]
while current in cameFrom:
current = cameFrom[current]
path.append(current)
path.reverse()
return path, F[end]
openVertices.remove(current)
closedVertices.add(current)
for neighbour in graph.get_vertex_neighbours(current):
if neighbour in closedVertices:
continue
candidateG = G[current] + graph.move_cost(current, neighbour)
if neighbour not in openVertices:
openVertices.add(neighbour)
elif candidateG >= G[neighbour]:
continue
cameFrom[neighbour] = current
G[neighbour] = candidateG
H = graph.heuristic(neighbour, end)
F[neighbour] = G[neighbour] + H
raise RuntimeError("A* failed to find a solution")
if __name__=="__main__":
graph = AStarGraph()
result, cost = AStarSearch((0,0), (7,7), graph)
print ("route", result)
print ("cost", cost)
plt.plot([v[0] for v in result], [v[1] for v in result])
for barrier in graph.barriers:
plt.plot([v[0] for v in barrier], [v[1] for v in barrier])
plt.xlim(-1,8)
plt.ylim(-1,8)
plt.show()
| package astar;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;
class AStar {
private final List<Node> open;
private final List<Node> closed;
private final List<Node> path;
private final int[][] maze;
private Node now;
private final int xstart;
private final int ystart;
private int xend, yend;
private final boolean diag;
static class Node implements Comparable {
public Node parent;
public int x, y;
public double g;
public double h;
Node(Node parent, int xpos, int ypos, double g, double h) {
this.parent = parent;
this.x = xpos;
this.y = ypos;
this.g = g;
this.h = h;
}
@Override
public int compareTo(Object o) {
Node that = (Node) o;
return (int)((this.g + this.h) - (that.g + that.h));
}
}
AStar(int[][] maze, int xstart, int ystart, boolean diag) {
this.open = new ArrayList<>();
this.closed = new ArrayList<>();
this.path = new ArrayList<>();
this.maze = maze;
this.now = new Node(null, xstart, ystart, 0, 0);
this.xstart = xstart;
this.ystart = ystart;
this.diag = diag;
}
public List<Node> findPathTo(int xend, int yend) {
this.xend = xend;
this.yend = yend;
this.closed.add(this.now);
addNeigborsToOpenList();
while (this.now.x != this.xend || this.now.y != this.yend) {
if (this.open.isEmpty()) {
return null;
}
this.now = this.open.get(0);
this.open.remove(0);
this.closed.add(this.now);
addNeigborsToOpenList();
}
this.path.add(0, this.now);
while (this.now.x != this.xstart || this.now.y != this.ystart) {
this.now = this.now.parent;
this.path.add(0, this.now);
}
return this.path;
}
public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){
Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();
if(maze[stateNode.getR()][stateNode.getC()] == 2){
if(isNodeILegal(stateNode, stateNode.expandDirection())){
exploreNodes.add(stateNode.expandDirection());
}
}
public void AStarSearch(){
this.start.setCostToGoal(this.start.calculateCost(this.goal));
this.start.setPathCost(0);
this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());
Mazecoord intialNode = this.start;
Mazecoord stateNode = intialNode;
frontier.add(intialNode);
while (true){
if(frontier.isEmpty()){
System.out.println("fail");
System.out.println(explored.size());
System.exit(-1);
}
}
public int calculateCost(Mazecoord goal){
int rState = this.getR();
int rGoal = goal.getR();
int diffR = rState - rGoal;
int diffC = this.getC() - goal.getC();
if(diffR * diffC > 0) {
return Math.abs(diffR) + Math.abs(diffC);
} else {
return Math.max(Math.abs(diffR), Math.abs(diffC));
}
}
public Coord getFather(){
return this.father;
}
public void setFather(Mazecoord node){
this.father = node;
}
public int getAStartCost() {
return AStartCost;
}
public void setAStartCost(int aStartCost) {
AStartCost = aStartCost;
}
public int getCostToGoal() {
return costToGoal;
}
public void setCostToGoal(int costToGoal) {
this.costToGoal = costToGoal;
}
private double distance(int dx, int dy) {
if (this.diag) {
return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend);
} else {
return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend);
}
}
private void addNeigborsToOpenList() {
Node node;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
if (!this.diag && x != 0 && y != 0) {
continue;
}
node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));
if ((x != 0 || y != 0)
&& this.now.x + x >= 0 && this.now.x + x < this.maze[0].length
&& this.now.y + y >= 0 && this.now.y + y < this.maze.length
&& this.maze[this.now.y + y][this.now.x + x] != -1
&& !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) {
node.g = node.parent.g + 1.;
node.g += maze[this.now.y + y][this.now.x + x];
this.open.add(node);
}
}
}
Collections.sort(this.open);
}
public static void main(String[] args) {
int[][] maze = {
{ 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0,100,100,100, 0, 0},
{ 0, 0, 0, 0, 0,100, 0, 0},
{ 0, 0,100, 0, 0,100, 0, 0},
{ 0, 0,100, 0, 0,100, 0, 0},
{ 0, 0,100,100,100,100, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0},
};
AStar as = new AStar(maze, 0, 0, true);
List<Node> path = as.findPathTo(7, 7);
if (path != null) {
path.forEach((n) -> {
System.out.print("[" + n.x + ", " + n.y + "] ");
maze[n.y][n.x] = -1;
});
System.out.printf("\nTotal cost: %.02f\n", path.get(path.size() - 1).g);
for (int[] maze_row : maze) {
for (int maze_entry : maze_row) {
switch (maze_entry) {
case 0:
System.out.print("_");
break;
case -1:
System.out.print("*");
break;
default:
System.out.print("#");
}
}
System.out.println();
}
}
}
}
|
Write a version of this Python function in Java with identical behavior. | from __future__ import print_function
import matplotlib.pyplot as plt
class AStarGraph(object):
def __init__(self):
self.barriers = []
self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])
def heuristic(self, start, goal):
D = 1
D2 = 1
dx = abs(start[0] - goal[0])
dy = abs(start[1] - goal[1])
return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)
def get_vertex_neighbours(self, pos):
n = []
for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:
x2 = pos[0] + dx
y2 = pos[1] + dy
if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:
continue
n.append((x2, y2))
return n
def move_cost(self, a, b):
for barrier in self.barriers:
if b in barrier:
return 100
return 1
def AStarSearch(start, end, graph):
G = {}
F = {}
G[start] = 0
F[start] = graph.heuristic(start, end)
closedVertices = set()
openVertices = set([start])
cameFrom = {}
while len(openVertices) > 0:
current = None
currentFscore = None
for pos in openVertices:
if current is None or F[pos] < currentFscore:
currentFscore = F[pos]
current = pos
if current == end:
path = [current]
while current in cameFrom:
current = cameFrom[current]
path.append(current)
path.reverse()
return path, F[end]
openVertices.remove(current)
closedVertices.add(current)
for neighbour in graph.get_vertex_neighbours(current):
if neighbour in closedVertices:
continue
candidateG = G[current] + graph.move_cost(current, neighbour)
if neighbour not in openVertices:
openVertices.add(neighbour)
elif candidateG >= G[neighbour]:
continue
cameFrom[neighbour] = current
G[neighbour] = candidateG
H = graph.heuristic(neighbour, end)
F[neighbour] = G[neighbour] + H
raise RuntimeError("A* failed to find a solution")
if __name__=="__main__":
graph = AStarGraph()
result, cost = AStarSearch((0,0), (7,7), graph)
print ("route", result)
print ("cost", cost)
plt.plot([v[0] for v in result], [v[1] for v in result])
for barrier in graph.barriers:
plt.plot([v[0] for v in barrier], [v[1] for v in barrier])
plt.xlim(-1,8)
plt.ylim(-1,8)
plt.show()
| package astar;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;
class AStar {
private final List<Node> open;
private final List<Node> closed;
private final List<Node> path;
private final int[][] maze;
private Node now;
private final int xstart;
private final int ystart;
private int xend, yend;
private final boolean diag;
static class Node implements Comparable {
public Node parent;
public int x, y;
public double g;
public double h;
Node(Node parent, int xpos, int ypos, double g, double h) {
this.parent = parent;
this.x = xpos;
this.y = ypos;
this.g = g;
this.h = h;
}
@Override
public int compareTo(Object o) {
Node that = (Node) o;
return (int)((this.g + this.h) - (that.g + that.h));
}
}
AStar(int[][] maze, int xstart, int ystart, boolean diag) {
this.open = new ArrayList<>();
this.closed = new ArrayList<>();
this.path = new ArrayList<>();
this.maze = maze;
this.now = new Node(null, xstart, ystart, 0, 0);
this.xstart = xstart;
this.ystart = ystart;
this.diag = diag;
}
public List<Node> findPathTo(int xend, int yend) {
this.xend = xend;
this.yend = yend;
this.closed.add(this.now);
addNeigborsToOpenList();
while (this.now.x != this.xend || this.now.y != this.yend) {
if (this.open.isEmpty()) {
return null;
}
this.now = this.open.get(0);
this.open.remove(0);
this.closed.add(this.now);
addNeigborsToOpenList();
}
this.path.add(0, this.now);
while (this.now.x != this.xstart || this.now.y != this.ystart) {
this.now = this.now.parent;
this.path.add(0, this.now);
}
return this.path;
}
public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){
Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();
if(maze[stateNode.getR()][stateNode.getC()] == 2){
if(isNodeILegal(stateNode, stateNode.expandDirection())){
exploreNodes.add(stateNode.expandDirection());
}
}
public void AStarSearch(){
this.start.setCostToGoal(this.start.calculateCost(this.goal));
this.start.setPathCost(0);
this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());
Mazecoord intialNode = this.start;
Mazecoord stateNode = intialNode;
frontier.add(intialNode);
while (true){
if(frontier.isEmpty()){
System.out.println("fail");
System.out.println(explored.size());
System.exit(-1);
}
}
public int calculateCost(Mazecoord goal){
int rState = this.getR();
int rGoal = goal.getR();
int diffR = rState - rGoal;
int diffC = this.getC() - goal.getC();
if(diffR * diffC > 0) {
return Math.abs(diffR) + Math.abs(diffC);
} else {
return Math.max(Math.abs(diffR), Math.abs(diffC));
}
}
public Coord getFather(){
return this.father;
}
public void setFather(Mazecoord node){
this.father = node;
}
public int getAStartCost() {
return AStartCost;
}
public void setAStartCost(int aStartCost) {
AStartCost = aStartCost;
}
public int getCostToGoal() {
return costToGoal;
}
public void setCostToGoal(int costToGoal) {
this.costToGoal = costToGoal;
}
private double distance(int dx, int dy) {
if (this.diag) {
return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend);
} else {
return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend);
}
}
private void addNeigborsToOpenList() {
Node node;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
if (!this.diag && x != 0 && y != 0) {
continue;
}
node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));
if ((x != 0 || y != 0)
&& this.now.x + x >= 0 && this.now.x + x < this.maze[0].length
&& this.now.y + y >= 0 && this.now.y + y < this.maze.length
&& this.maze[this.now.y + y][this.now.x + x] != -1
&& !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) {
node.g = node.parent.g + 1.;
node.g += maze[this.now.y + y][this.now.x + x];
this.open.add(node);
}
}
}
Collections.sort(this.open);
}
public static void main(String[] args) {
int[][] maze = {
{ 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0,100,100,100, 0, 0},
{ 0, 0, 0, 0, 0,100, 0, 0},
{ 0, 0,100, 0, 0,100, 0, 0},
{ 0, 0,100, 0, 0,100, 0, 0},
{ 0, 0,100,100,100,100, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0},
};
AStar as = new AStar(maze, 0, 0, true);
List<Node> path = as.findPathTo(7, 7);
if (path != null) {
path.forEach((n) -> {
System.out.print("[" + n.x + ", " + n.y + "] ");
maze[n.y][n.x] = -1;
});
System.out.printf("\nTotal cost: %.02f\n", path.get(path.size() - 1).g);
for (int[] maze_row : maze) {
for (int maze_entry : maze_row) {
switch (maze_entry) {
case 0:
System.out.print("_");
break;
case -1:
System.out.print("*");
break;
default:
System.out.print("#");
}
}
System.out.println();
}
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | from __future__ import print_function
import matplotlib.pyplot as plt
class AStarGraph(object):
def __init__(self):
self.barriers = []
self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])
def heuristic(self, start, goal):
D = 1
D2 = 1
dx = abs(start[0] - goal[0])
dy = abs(start[1] - goal[1])
return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)
def get_vertex_neighbours(self, pos):
n = []
for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:
x2 = pos[0] + dx
y2 = pos[1] + dy
if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:
continue
n.append((x2, y2))
return n
def move_cost(self, a, b):
for barrier in self.barriers:
if b in barrier:
return 100
return 1
def AStarSearch(start, end, graph):
G = {}
F = {}
G[start] = 0
F[start] = graph.heuristic(start, end)
closedVertices = set()
openVertices = set([start])
cameFrom = {}
while len(openVertices) > 0:
current = None
currentFscore = None
for pos in openVertices:
if current is None or F[pos] < currentFscore:
currentFscore = F[pos]
current = pos
if current == end:
path = [current]
while current in cameFrom:
current = cameFrom[current]
path.append(current)
path.reverse()
return path, F[end]
openVertices.remove(current)
closedVertices.add(current)
for neighbour in graph.get_vertex_neighbours(current):
if neighbour in closedVertices:
continue
candidateG = G[current] + graph.move_cost(current, neighbour)
if neighbour not in openVertices:
openVertices.add(neighbour)
elif candidateG >= G[neighbour]:
continue
cameFrom[neighbour] = current
G[neighbour] = candidateG
H = graph.heuristic(neighbour, end)
F[neighbour] = G[neighbour] + H
raise RuntimeError("A* failed to find a solution")
if __name__=="__main__":
graph = AStarGraph()
result, cost = AStarSearch((0,0), (7,7), graph)
print ("route", result)
print ("cost", cost)
plt.plot([v[0] for v in result], [v[1] for v in result])
for barrier in graph.barriers:
plt.plot([v[0] for v in barrier], [v[1] for v in barrier])
plt.xlim(-1,8)
plt.ylim(-1,8)
plt.show()
| package astar;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;
class AStar {
private final List<Node> open;
private final List<Node> closed;
private final List<Node> path;
private final int[][] maze;
private Node now;
private final int xstart;
private final int ystart;
private int xend, yend;
private final boolean diag;
static class Node implements Comparable {
public Node parent;
public int x, y;
public double g;
public double h;
Node(Node parent, int xpos, int ypos, double g, double h) {
this.parent = parent;
this.x = xpos;
this.y = ypos;
this.g = g;
this.h = h;
}
@Override
public int compareTo(Object o) {
Node that = (Node) o;
return (int)((this.g + this.h) - (that.g + that.h));
}
}
AStar(int[][] maze, int xstart, int ystart, boolean diag) {
this.open = new ArrayList<>();
this.closed = new ArrayList<>();
this.path = new ArrayList<>();
this.maze = maze;
this.now = new Node(null, xstart, ystart, 0, 0);
this.xstart = xstart;
this.ystart = ystart;
this.diag = diag;
}
public List<Node> findPathTo(int xend, int yend) {
this.xend = xend;
this.yend = yend;
this.closed.add(this.now);
addNeigborsToOpenList();
while (this.now.x != this.xend || this.now.y != this.yend) {
if (this.open.isEmpty()) {
return null;
}
this.now = this.open.get(0);
this.open.remove(0);
this.closed.add(this.now);
addNeigborsToOpenList();
}
this.path.add(0, this.now);
while (this.now.x != this.xstart || this.now.y != this.ystart) {
this.now = this.now.parent;
this.path.add(0, this.now);
}
return this.path;
}
public void expandAStar(int[][] maze, int xstart, int ystart, boolean diag){
Queue<Mazecoord> exploreNodes = new LinkedList<Mazecoord>();
if(maze[stateNode.getR()][stateNode.getC()] == 2){
if(isNodeILegal(stateNode, stateNode.expandDirection())){
exploreNodes.add(stateNode.expandDirection());
}
}
public void AStarSearch(){
this.start.setCostToGoal(this.start.calculateCost(this.goal));
this.start.setPathCost(0);
this.start.setAStartCost(this.start.getPathCost() + this.start.getCostToGoal());
Mazecoord intialNode = this.start;
Mazecoord stateNode = intialNode;
frontier.add(intialNode);
while (true){
if(frontier.isEmpty()){
System.out.println("fail");
System.out.println(explored.size());
System.exit(-1);
}
}
public int calculateCost(Mazecoord goal){
int rState = this.getR();
int rGoal = goal.getR();
int diffR = rState - rGoal;
int diffC = this.getC() - goal.getC();
if(diffR * diffC > 0) {
return Math.abs(diffR) + Math.abs(diffC);
} else {
return Math.max(Math.abs(diffR), Math.abs(diffC));
}
}
public Coord getFather(){
return this.father;
}
public void setFather(Mazecoord node){
this.father = node;
}
public int getAStartCost() {
return AStartCost;
}
public void setAStartCost(int aStartCost) {
AStartCost = aStartCost;
}
public int getCostToGoal() {
return costToGoal;
}
public void setCostToGoal(int costToGoal) {
this.costToGoal = costToGoal;
}
private double distance(int dx, int dy) {
if (this.diag) {
return Math.hypot(this.now.x + dx - this.xend, this.now.y + dy - this.yend);
} else {
return Math.abs(this.now.x + dx - this.xend) + Math.abs(this.now.y + dy - this.yend);
}
}
private void addNeigborsToOpenList() {
Node node;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
if (!this.diag && x != 0 && y != 0) {
continue;
}
node = new Node(this.now, this.now.x + x, this.now.y + y, this.now.g, this.distance(x, y));
if ((x != 0 || y != 0)
&& this.now.x + x >= 0 && this.now.x + x < this.maze[0].length
&& this.now.y + y >= 0 && this.now.y + y < this.maze.length
&& this.maze[this.now.y + y][this.now.x + x] != -1
&& !findNeighborInList(this.open, node) && !findNeighborInList(this.closed, node)) {
node.g = node.parent.g + 1.;
node.g += maze[this.now.y + y][this.now.x + x];
this.open.add(node);
}
}
}
Collections.sort(this.open);
}
public static void main(String[] args) {
int[][] maze = {
{ 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0,100,100,100, 0, 0},
{ 0, 0, 0, 0, 0,100, 0, 0},
{ 0, 0,100, 0, 0,100, 0, 0},
{ 0, 0,100, 0, 0,100, 0, 0},
{ 0, 0,100,100,100,100, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0},
};
AStar as = new AStar(maze, 0, 0, true);
List<Node> path = as.findPathTo(7, 7);
if (path != null) {
path.forEach((n) -> {
System.out.print("[" + n.x + ", " + n.y + "] ");
maze[n.y][n.x] = -1;
});
System.out.printf("\nTotal cost: %.02f\n", path.get(path.size() - 1).g);
for (int[] maze_row : maze) {
for (int maze_entry : maze_row) {
switch (maze_entry) {
case 0:
System.out.print("_");
break;
case -1:
System.out.print("*");
break;
default:
System.out.print("#");
}
}
System.out.println();
}
}
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. |
from itertools import chain, groupby
from os.path import expanduser
from functools import reduce
def main():
print('\n'.join(
concatMap(circularGroup)(
anagrams(3)(
lines(readFile('~/mitWords.txt'))
)
)
))
def anagrams(n):
def go(ws):
def f(xs):
return [
[snd(x) for x in xs]
] if n <= len(xs) >= len(xs[0][0]) else []
return concatMap(f)(groupBy(fst)(sorted(
[(''.join(sorted(w)), w) for w in ws],
key=fst
)))
return go
def circularGroup(ws):
lex = set(ws)
iLast = len(ws) - 1
(i, blnCircular) = until(
lambda tpl: tpl[1] or (tpl[0] > iLast)
)(
lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))
)(
(0, False)
)
return [' -> '.join(allRotations(ws[i]))] if blnCircular else []
def isCircular(lexicon):
def go(w):
def f(tpl):
(i, _, x) = tpl
return (1 + i, x in lexicon, rotated(x))
iLast = len(w) - 1
return until(
lambda tpl: iLast < tpl[0] or (not tpl[1])
)(f)(
(0, True, rotated(w))
)[1]
return go
def allRotations(w):
return takeIterate(len(w) - 1)(
rotated
)(w)
def concatMap(f):
def go(xs):
return chain.from_iterable(map(f, xs))
return go
def fst(tpl):
return tpl[0]
def groupBy(f):
def go(xs):
return [
list(x[1]) for x in groupby(xs, key=f)
]
return go
def lines(s):
return s.splitlines()
def mapAccumL(f):
def go(a, x):
tpl = f(a[0], x)
return (tpl[0], a[1] + [tpl[1]])
return lambda acc: lambda xs: (
reduce(go, xs, (acc, []))
)
def readFile(fp):
with open(expanduser(fp), 'r', encoding='utf-8') as f:
return f.read()
def rotated(s):
return s[1:] + s[0]
def snd(tpl):
return tpl[1]
def takeIterate(n):
def go(f):
def g(x):
def h(a, i):
v = f(a) if i else x
return (v, v)
return mapAccumL(h)(x)(
range(0, 1 + n)
)[1]
return g
return go
def until(p):
def go(f):
def g(x):
v = x
while not p(v):
v = f(v)
return v
return g
return go
if __name__ == '__main__':
main()
| import java.io.*;
import java.util.*;
public class Teacup {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("usage: java Teacup dictionary");
System.exit(1);
}
try {
findTeacupWords(loadDictionary(args[0]));
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
private static Set<String> loadDictionary(String fileName) throws IOException {
Set<String> words = new TreeSet<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String word;
while ((word = reader.readLine()) != null)
words.add(word);
return words;
}
}
private static void findTeacupWords(Set<String> words) {
List<String> teacupWords = new ArrayList<>();
Set<String> found = new HashSet<>();
for (String word : words) {
int len = word.length();
if (len < 3 || found.contains(word))
continue;
teacupWords.clear();
teacupWords.add(word);
char[] chars = word.toCharArray();
for (int i = 0; i < len - 1; ++i) {
String rotated = new String(rotate(chars));
if (rotated.equals(word) || !words.contains(rotated))
break;
teacupWords.add(rotated);
}
if (teacupWords.size() == len) {
found.addAll(teacupWords);
System.out.print(word);
for (int i = 1; i < len; ++i)
System.out.print(" " + teacupWords.get(i));
System.out.println();
}
}
}
private static char[] rotate(char[] ch) {
char c = ch[0];
System.arraycopy(ch, 1, ch, 0, ch.length - 1);
ch[ch.length - 1] = c;
return ch;
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. |
def digit_sum(n, sum):
sum += 1
while n > 0 and n % 10 == 0:
sum -= 9
n /= 10
return sum
previous = 1
gap = 0
sum = 0
niven_index = 0
gap_index = 1
print("Gap index Gap Niven index Niven number")
niven = 1
while gap_index <= 22:
sum = digit_sum(niven, sum)
if niven % sum == 0:
if niven > previous + gap:
gap = niven - previous;
print('{0:9d} {1:4d} {2:13d} {3:11d}'.format(gap_index, gap, niven_index, previous))
gap_index += 1
previous = niven
niven_index += 1
niven += 1
| 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;
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. | import logging, logging.handlers
LOG_FILENAME = "logdemo.log"
FORMAT_STRING = "%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s"
LOGLEVEL = logging.DEBUG
def print_squares(number):
logger.info("In print_squares")
for i in range(number):
print("square of {0} is {1}".format(i , i*i))
logger.debug(f'square of {i} is {i*i}')
def print_cubes(number):
logger.info("In print_cubes")
for j in range(number):
print("cube of {0} is {1}".format(j, j*j*j))
logger.debug(f'cube of {j} is {j*j*j}')
if __name__ == "__main__":
logger = logging.getLogger("logdemo")
logger.setLevel(LOGLEVEL)
handler = logging.FileHandler(LOG_FILENAME)
handler.setFormatter(logging.Formatter(FORMAT_STRING))
logger.addHandler(handler)
print_squares(10)
print_cubes(10)
logger.info("All done")
| import java.util.Objects;
public class PrintDebugStatement {
private static void printDebug(String message) {
Objects.requireNonNull(message);
RuntimeException exception = new RuntimeException();
StackTraceElement[] stackTrace = exception.getStackTrace();
StackTraceElement stackTraceElement = stackTrace[1];
String fileName = stackTraceElement.getFileName();
String className = stackTraceElement.getClassName();
String methodName = stackTraceElement.getMethodName();
int lineNumber = stackTraceElement.getLineNumber();
System.out.printf("[DEBUG][%s %s.%s#%d] %s\n", fileName, className, methodName, lineNumber, message);
}
private static void blah() {
printDebug("Made It!");
}
public static void main(String[] args) {
printDebug("Hello world.");
blah();
Runnable oops = () -> printDebug("oops");
oops.run();
}
}
|
Translate this program into Java but keep the logic exactly as in Python. |
import matplotlib.pyplot as plt
from math import sin, cos, pi
def sgn(x):
return ((x>0)-(x<0))*1
a,b,n=200,200,2.5
na=2/n
step=100
piece=(pi*2)/step
xp=[];yp=[]
t=0
for t1 in range(step+1):
x=(abs((cos(t)))**na)*a*sgn(cos(t))
y=(abs((sin(t)))**na)*b*sgn(sin(t))
xp.append(x);yp.append(y)
t+=piece
plt.plot(xp,yp)
plt.title("Superellipse with parameter "+str(n))
plt.show()
| import java.awt.*;
import java.awt.geom.Path2D;
import static java.lang.Math.pow;
import java.util.Hashtable;
import javax.swing.*;
import javax.swing.event.*;
public class SuperEllipse extends JPanel implements ChangeListener {
private double exp = 2.5;
public SuperEllipse() {
setPreferredSize(new Dimension(650, 650));
setBackground(Color.white);
setFont(new Font("Serif", Font.PLAIN, 18));
}
void drawGrid(Graphics2D g) {
g.setStroke(new BasicStroke(2));
g.setColor(new Color(0xEEEEEE));
int w = getWidth();
int h = getHeight();
int spacing = 25;
for (int i = 0; i < w / spacing; i++) {
g.drawLine(0, i * spacing, w, i * spacing);
g.drawLine(i * spacing, 0, i * spacing, w);
}
g.drawLine(0, h - 1, w, h - 1);
g.setColor(new Color(0xAAAAAA));
g.drawLine(0, w / 2, w, w / 2);
g.drawLine(w / 2, 0, w / 2, w);
}
void drawLegend(Graphics2D g) {
g.setColor(Color.black);
g.setFont(getFont());
g.drawString("n = " + String.valueOf(exp), getWidth() - 150, 45);
g.drawString("a = b = 200", getWidth() - 150, 75);
}
void drawEllipse(Graphics2D g) {
final int a = 200;
double[] points = new double[a + 1];
Path2D p = new Path2D.Double();
p.moveTo(a, 0);
for (int x = a; x >= 0; x--) {
points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp);
p.lineTo(x, -points[x]);
}
for (int x = 0; x <= a; x++)
p.lineTo(x, points[x]);
for (int x = a; x >= 0; x--)
p.lineTo(-x, points[x]);
for (int x = 0; x <= a; x++)
p.lineTo(-x, -points[x]);
g.translate(getWidth() / 2, getHeight() / 2);
g.setStroke(new BasicStroke(2));
g.setColor(new Color(0x25B0C4DE, true));
g.fill(p);
g.setColor(new Color(0xB0C4DE));
g.draw(p);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
drawGrid(g);
drawLegend(g);
drawEllipse(g);
}
@Override
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
exp = source.getValue() / 2.0;
repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Super Ellipse");
f.setResizable(false);
SuperEllipse panel = new SuperEllipse();
f.add(panel, BorderLayout.CENTER);
JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5);
exponent.addChangeListener(panel);
exponent.setMajorTickSpacing(1);
exponent.setPaintLabels(true);
exponent.setBackground(Color.white);
exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
Hashtable<Integer, JLabel> labelTable = new Hashtable<>();
for (int i = 1; i < 10; i++)
labelTable.put(i, new JLabel(String.valueOf(i * 0.5)));
exponent.setLabelTable(labelTable);
f.add(exponent, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Generate an equivalent Java version of this Python code. | from math import factorial as fact
from random import randrange
from textwrap import wrap
def identity_perm(n):
return list(range(n))
def unranker1(n, r, pi):
while n > 0:
n1, (rdivn, rmodn) = n-1, divmod(r, n)
pi[n1], pi[rmodn] = pi[rmodn], pi[n1]
n = n1
r = rdivn
return pi
def init_pi1(n, pi):
pi1 = [-1] * n
for i in range(n):
pi1[pi[i]] = i
return pi1
def ranker1(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s + n * ranker1(n1, pi, pi1)
def unranker2(n, r, pi):
while n > 0:
n1 = n-1
s, rmodf = divmod(r, fact(n1))
pi[n1], pi[s] = pi[s], pi[n1]
n = n1
r = rmodf
return pi
def ranker2(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s * fact(n1) + ranker2(n1, pi, pi1)
def get_random_ranks(permsize, samplesize):
perms = fact(permsize)
ranks = set()
while len(ranks) < samplesize:
ranks |= set( randrange(perms)
for r in range(samplesize - len(ranks)) )
return ranks
def test1(comment, unranker, ranker):
n, samplesize, n2 = 3, 4, 12
print(comment)
perms = []
for r in range(fact(n)):
pi = identity_perm(n)
perm = unranker(n, r, pi)
perms.append((r, perm))
for r, pi in perms:
pi1 = init_pi1(n, pi)
print(' From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))
print('\n %i random individual samples of %i items:' % (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))
print('')
def test2(comment, unranker):
samplesize, n2 = 4, 144
print(comment)
print(' %i random individual samples of %i items:' % (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + '\n '.join(wrap(repr(unranker(n2, r, pi)))))
print('')
if __name__ == '__main__':
test1('First ordering:', unranker1, ranker1)
test1('Second ordering:', unranker2, ranker2)
test2('First ordering, large number of perms:', unranker1)
| import java.math.BigInteger;
import java.util.*;
class RankPermutation
{
public static BigInteger getRank(int[] permutation)
{
int n = permutation.length;
BitSet usedDigits = new BitSet();
BigInteger rank = BigInteger.ZERO;
for (int i = 0; i < n; i++)
{
rank = rank.multiply(BigInteger.valueOf(n - i));
int digit = 0;
int v = -1;
while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])
digit++;
usedDigits.set(v);
rank = rank.add(BigInteger.valueOf(digit));
}
return rank;
}
public static int[] getPermutation(int n, BigInteger rank)
{
int[] digits = new int[n];
for (int digit = 2; digit <= n; digit++)
{
BigInteger divisor = BigInteger.valueOf(digit);
digits[n - digit] = rank.mod(divisor).intValue();
if (digit < n)
rank = rank.divide(divisor);
}
BitSet usedDigits = new BitSet();
int[] permutation = new int[n];
for (int i = 0; i < n; i++)
{
int v = usedDigits.nextClearBit(0);
for (int j = 0; j < digits[i]; j++)
v = usedDigits.nextClearBit(v + 1);
permutation[i] = v;
usedDigits.set(v);
}
return permutation;
}
public static void main(String[] args)
{
for (int i = 0; i < 6; i++)
{
int[] permutation = getPermutation(3, BigInteger.valueOf(i));
System.out.println(String.valueOf(i) + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation));
}
Random rnd = new Random();
for (int n : new int[] { 12, 144 })
{
BigInteger factorial = BigInteger.ONE;
for (int i = 2; i <= n; i++)
factorial = factorial.multiply(BigInteger.valueOf(i));
System.out.println("n = " + n);
for (int i = 0; i < 5; i++)
{
BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);
rank = rank.mod(factorial);
int[] permutation = getPermutation(n, rank);
System.out.println(" " + rank + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation));
}
}
}
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. | from math import factorial as fact
from random import randrange
from textwrap import wrap
def identity_perm(n):
return list(range(n))
def unranker1(n, r, pi):
while n > 0:
n1, (rdivn, rmodn) = n-1, divmod(r, n)
pi[n1], pi[rmodn] = pi[rmodn], pi[n1]
n = n1
r = rdivn
return pi
def init_pi1(n, pi):
pi1 = [-1] * n
for i in range(n):
pi1[pi[i]] = i
return pi1
def ranker1(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s + n * ranker1(n1, pi, pi1)
def unranker2(n, r, pi):
while n > 0:
n1 = n-1
s, rmodf = divmod(r, fact(n1))
pi[n1], pi[s] = pi[s], pi[n1]
n = n1
r = rmodf
return pi
def ranker2(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s * fact(n1) + ranker2(n1, pi, pi1)
def get_random_ranks(permsize, samplesize):
perms = fact(permsize)
ranks = set()
while len(ranks) < samplesize:
ranks |= set( randrange(perms)
for r in range(samplesize - len(ranks)) )
return ranks
def test1(comment, unranker, ranker):
n, samplesize, n2 = 3, 4, 12
print(comment)
perms = []
for r in range(fact(n)):
pi = identity_perm(n)
perm = unranker(n, r, pi)
perms.append((r, perm))
for r, pi in perms:
pi1 = init_pi1(n, pi)
print(' From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))
print('\n %i random individual samples of %i items:' % (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))
print('')
def test2(comment, unranker):
samplesize, n2 = 4, 144
print(comment)
print(' %i random individual samples of %i items:' % (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + '\n '.join(wrap(repr(unranker(n2, r, pi)))))
print('')
if __name__ == '__main__':
test1('First ordering:', unranker1, ranker1)
test1('Second ordering:', unranker2, ranker2)
test2('First ordering, large number of perms:', unranker1)
| import java.math.BigInteger;
import java.util.*;
class RankPermutation
{
public static BigInteger getRank(int[] permutation)
{
int n = permutation.length;
BitSet usedDigits = new BitSet();
BigInteger rank = BigInteger.ZERO;
for (int i = 0; i < n; i++)
{
rank = rank.multiply(BigInteger.valueOf(n - i));
int digit = 0;
int v = -1;
while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])
digit++;
usedDigits.set(v);
rank = rank.add(BigInteger.valueOf(digit));
}
return rank;
}
public static int[] getPermutation(int n, BigInteger rank)
{
int[] digits = new int[n];
for (int digit = 2; digit <= n; digit++)
{
BigInteger divisor = BigInteger.valueOf(digit);
digits[n - digit] = rank.mod(divisor).intValue();
if (digit < n)
rank = rank.divide(divisor);
}
BitSet usedDigits = new BitSet();
int[] permutation = new int[n];
for (int i = 0; i < n; i++)
{
int v = usedDigits.nextClearBit(0);
for (int j = 0; j < digits[i]; j++)
v = usedDigits.nextClearBit(v + 1);
permutation[i] = v;
usedDigits.set(v);
}
return permutation;
}
public static void main(String[] args)
{
for (int i = 0; i < 6; i++)
{
int[] permutation = getPermutation(3, BigInteger.valueOf(i));
System.out.println(String.valueOf(i) + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation));
}
Random rnd = new Random();
for (int n : new int[] { 12, 144 })
{
BigInteger factorial = BigInteger.ONE;
for (int i = 2; i <= n; i++)
factorial = factorial.multiply(BigInteger.valueOf(i));
System.out.println("n = " + n);
for (int i = 0; i < 5; i++)
{
BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd);
rank = rank.mod(factorial);
int[] permutation = getPermutation(n, rank);
System.out.println(" " + rank + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation));
}
}
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | def range_extract(lst):
'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'
lenlst = len(lst)
i = 0
while i< lenlst:
low = lst[i]
while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1
hi = lst[i]
if hi - low >= 2:
yield (low, hi)
elif hi - low == 1:
yield (low,)
yield (hi,)
else:
yield (low,)
i += 1
def printr(ranges):
print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)
for r in ranges ) )
if __name__ == '__main__':
for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,
8, 9, 10, 11, 14, 15, 17, 18, 19, 20],
[0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:
printr(range_extract(lst))
| public class RangeExtraction {
public static void main(String[] args) {
int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39};
int len = arr.length;
int idx = 0, idx2 = 0;
while (idx < len) {
while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);
if (idx2 - idx > 2) {
System.out.printf("%s-%s,", arr[idx], arr[idx2 - 1]);
idx = idx2;
} else {
for (; idx < idx2; idx++)
System.out.printf("%s,", arr[idx]);
}
}
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | fun maxpathsum(t):
let a = val t
for i in a.length-1..-1..1, c in linearindices a[r]:
a[r, c] += max(a[r+1, c], a[r=1, c+1])
return a[1, 1]
let test = [
[55],
[94, 48],
[95, 30, 96],
[77, 71, 26, 67],
[97, 13, 76, 38, 45],
[07, 36, 79, 16, 37, 68],
[48, 07, 09, 18, 70, 26, 06],
[18, 72, 79, 46, 59, 79, 29, 90],
[20, 76, 87, 11, 32, 07, 07, 49, 18],
[27, 83, 58, 35, 71, 11, 25, 57, 29, 85],
[14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],
[02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],
[92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],
[56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],
[44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],
[85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],
[06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],
[27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]
]
@print maxpathsum test
| import java.nio.file.*;
import static java.util.Arrays.stream;
public class MaxPathSum {
public static void main(String[] args) throws Exception {
int[][] data = Files.lines(Paths.get("triangle.txt"))
.map(s -> stream(s.trim().split("\\s+"))
.mapToInt(Integer::parseInt)
.toArray())
.toArray(int[][]::new);
for (int r = data.length - 1; r > 0; r--)
for (int c = 0; c < data[r].length - 1; c++)
data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);
System.out.println(data[0][0]);
}
}
|
Write the same algorithm in Java as shown in this Python implementation. |
beforeTxt =
smallrc01 =
rc01 =
def intarray(binstring):
return [[1 if ch == '1' else 0 for ch in line]
for line in binstring.strip().split()]
def chararray(intmatrix):
return '\n'.join(''.join(str(p) for p in row) for row in intmatrix)
def toTxt(intmatrix):
Return 8-neighbours of point p1 of picture, in order'''
i = image
x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1
return [i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1],
i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]
def transitions(neighbours):
n = neighbours + neighbours[0:1]
return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))
def zhangSuen(image):
changing1 = changing2 = [(-1, -1)]
while changing1 or changing2:
changing1 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and
P4 * P6 * P8 == 0 and
P2 * P4 * P6 == 0 and
transitions(n) == 1 and
2 <= sum(n) <= 6):
changing1.append((x,y))
for x, y in changing1: image[y][x] = 0
changing2 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and
P2 * P6 * P8 == 0 and
P2 * P4 * P8 == 0 and
transitions(n) == 1 and
2 <= sum(n) <= 6):
changing2.append((x,y))
for x, y in changing2: image[y][x] = 0
return image
if __name__ == '__main__':
for picture in (beforeTxt, smallrc01, rc01):
image = intarray(picture)
print('\nFrom:\n%s' % toTxt(image))
after = zhangSuen(image)
print('\nTo thinned:\n%s' % toTxt(after))
| 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);
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | s = [1, 2, 2, 3, 4, 4, 5]
for i in range(len(s)):
curr = s[i]
if i > 0 and curr == prev:
print(i)
prev = curr
| public class VariableDeclarationReset {
public static void main(String[] args) {
int[] s = {1, 2, 2, 3, 4, 4, 5};
for (int i = 0; i < s.length; ++i) {
int curr = s[i];
int prev = 0;
if (i > 0 && curr == prev) System.out.println(i);
prev = curr;
}
int gprev = 0;
for (int i = 0; i < s.length; ++i) {
int curr = s[i];
if (i > 0 && curr == gprev) System.out.println(i);
gprev = curr;
}
}
}
|
Generate an equivalent Java version of this Python code. | def msb(x):
return x.bit_length() - 1
def lsb(x):
return msb(x & -x)
for i in range(6):
x = 42 ** i
print("%10d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
for i in range(6):
x = 1302 ** i
print("%20d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
| public class FirstLastBits {
public static int mssb(int x) {
return Integer.highestOneBit(x);
}
public static long mssb(long x) {
return Long.highestOneBit(x);
}
public static int mssb_idx(int x) {
return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);
}
public static int mssb_idx(long x) {
return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);
}
public static int mssb_idx(BigInteger x) {
return x.bitLength() - 1;
}
public static int lssb(int x) {
return Integer.lowestOneBit(x);
}
public static long lssb(long x) {
return Long.lowestOneBit(x);
}
public static int lssb_idx(int x) {
return Integer.numberOfTrailingZeros(x);
}
public static int lssb_idx(long x) {
return Long.numberOfTrailingZeros(x);
}
public static int lssb_idx(BigInteger x) {
return x.getLowestSetBit();
}
public static void main(String[] args) {
System.out.println("int:");
int n1 = 1;
for (int i = 0; ; i++, n1 *= 42) {
System.out.printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n",
i, n1, n1,
mssb(n1), mssb_idx(n1),
lssb(n1), lssb_idx(n1));
if (n1 >= Integer.MAX_VALUE / 42)
break;
}
System.out.println();
System.out.println("long:");
long n2 = 1;
for (int i = 0; ; i++, n2 *= 42) {
System.out.printf("42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\n",
i, n2, n2,
mssb(n2), mssb_idx(n2),
lssb(n2), lssb_idx(n2));
if (n2 >= Long.MAX_VALUE / 42)
break;
}
System.out.println();
System.out.println("BigInteger:");
BigInteger n3 = BigInteger.ONE;
BigInteger k = BigInteger.valueOf(1302);
for (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {
System.out.printf("1302**%02d = %30d(x%28x): M %2d L %2d\n",
i, n3, n3,
mssb_idx(n3),
lssb_idx(n3));
}
}
}
|
Convert this Python snippet to Java and keep its semantics consistent. | def msb(x):
return x.bit_length() - 1
def lsb(x):
return msb(x & -x)
for i in range(6):
x = 42 ** i
print("%10d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
for i in range(6):
x = 1302 ** i
print("%20d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
| public class FirstLastBits {
public static int mssb(int x) {
return Integer.highestOneBit(x);
}
public static long mssb(long x) {
return Long.highestOneBit(x);
}
public static int mssb_idx(int x) {
return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);
}
public static int mssb_idx(long x) {
return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);
}
public static int mssb_idx(BigInteger x) {
return x.bitLength() - 1;
}
public static int lssb(int x) {
return Integer.lowestOneBit(x);
}
public static long lssb(long x) {
return Long.lowestOneBit(x);
}
public static int lssb_idx(int x) {
return Integer.numberOfTrailingZeros(x);
}
public static int lssb_idx(long x) {
return Long.numberOfTrailingZeros(x);
}
public static int lssb_idx(BigInteger x) {
return x.getLowestSetBit();
}
public static void main(String[] args) {
System.out.println("int:");
int n1 = 1;
for (int i = 0; ; i++, n1 *= 42) {
System.out.printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n",
i, n1, n1,
mssb(n1), mssb_idx(n1),
lssb(n1), lssb_idx(n1));
if (n1 >= Integer.MAX_VALUE / 42)
break;
}
System.out.println();
System.out.println("long:");
long n2 = 1;
for (int i = 0; ; i++, n2 *= 42) {
System.out.printf("42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\n",
i, n2, n2,
mssb(n2), mssb_idx(n2),
lssb(n2), lssb_idx(n2));
if (n2 >= Long.MAX_VALUE / 42)
break;
}
System.out.println();
System.out.println("BigInteger:");
BigInteger n3 = BigInteger.ONE;
BigInteger k = BigInteger.valueOf(1302);
for (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {
System.out.printf("1302**%02d = %30d(x%28x): M %2d L %2d\n",
i, n3, n3,
mssb_idx(n3),
lssb_idx(n3));
}
}
}
|
Preserve the algorithm and functionality while converting the code from Python to Java. | def msb(x):
return x.bit_length() - 1
def lsb(x):
return msb(x & -x)
for i in range(6):
x = 42 ** i
print("%10d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
for i in range(6):
x = 1302 ** i
print("%20d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
| public class FirstLastBits {
public static int mssb(int x) {
return Integer.highestOneBit(x);
}
public static long mssb(long x) {
return Long.highestOneBit(x);
}
public static int mssb_idx(int x) {
return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);
}
public static int mssb_idx(long x) {
return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);
}
public static int mssb_idx(BigInteger x) {
return x.bitLength() - 1;
}
public static int lssb(int x) {
return Integer.lowestOneBit(x);
}
public static long lssb(long x) {
return Long.lowestOneBit(x);
}
public static int lssb_idx(int x) {
return Integer.numberOfTrailingZeros(x);
}
public static int lssb_idx(long x) {
return Long.numberOfTrailingZeros(x);
}
public static int lssb_idx(BigInteger x) {
return x.getLowestSetBit();
}
public static void main(String[] args) {
System.out.println("int:");
int n1 = 1;
for (int i = 0; ; i++, n1 *= 42) {
System.out.printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n",
i, n1, n1,
mssb(n1), mssb_idx(n1),
lssb(n1), lssb_idx(n1));
if (n1 >= Integer.MAX_VALUE / 42)
break;
}
System.out.println();
System.out.println("long:");
long n2 = 1;
for (int i = 0; ; i++, n2 *= 42) {
System.out.printf("42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\n",
i, n2, n2,
mssb(n2), mssb_idx(n2),
lssb(n2), lssb_idx(n2));
if (n2 >= Long.MAX_VALUE / 42)
break;
}
System.out.println();
System.out.println("BigInteger:");
BigInteger n3 = BigInteger.ONE;
BigInteger k = BigInteger.valueOf(1302);
for (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {
System.out.printf("1302**%02d = %30d(x%28x): M %2d L %2d\n",
i, n3, n3,
mssb_idx(n3),
lssb_idx(n3));
}
}
}
|
Convert this Python snippet to Java and keep its semantics consistent. | import itertools
def riseEqFall(num):
height = 0
d1 = num % 10
num //= 10
while num:
d2 = num % 10
height += (d1<d2) - (d1>d2)
d1 = d2
num //= 10
return height == 0
def sequence(start, fn):
num=start-1
while True:
num += 1
while not fn(num): num += 1
yield num
a296712 = sequence(1, riseEqFall)
print("The first 200 numbers are:")
print(*itertools.islice(a296712, 200))
print("The 10,000,000th number is:")
print(*itertools.islice(a296712, 10000000-200-1, 10000000-200))
| public class EqualRisesFalls {
public static void main(String[] args) {
final int limit1 = 200;
final int limit2 = 10000000;
System.out.printf("The first %d numbers in the sequence are:\n", limit1);
int n = 0;
for (int count = 0; count < limit2; ) {
if (equalRisesAndFalls(++n)) {
++count;
if (count <= limit1)
System.out.printf("%3d%c", n, count % 20 == 0 ? '\n' : ' ');
}
}
System.out.printf("\nThe %dth number in the sequence is %d.\n", limit2, n);
}
private static boolean equalRisesAndFalls(int n) {
int total = 0;
for (int previousDigit = -1; n > 0; n /= 10) {
int digit = n % 10;
if (previousDigit > digit)
++total;
else if (previousDigit >= 0 && previousDigit < digit)
--total;
previousDigit = digit;
}
return total == 0;
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | l = 300
def setup():
size(400, 400)
background(0, 0, 255)
stroke(255)
translate(width / 2.0, height / 2.0)
translate(-l / 2.0, l * sqrt(3) / 6.0)
for i in range(4):
kcurve(0, l)
rotate(radians(120))
translate(-l, 0)
def kcurve(x1, x2):
s = (x2 - x1) / 3.0
if s < 5:
pushMatrix()
translate(x1, 0)
line(0, 0, s, 0)
line(2 * s, 0, 3 * s, 0)
translate(s, 0)
rotate(radians(60))
line(0, 0, s, 0)
translate(s, 0)
rotate(radians(-120))
line(0, 0, s, 0)
popMatrix()
return
pushMatrix()
translate(x1, 0)
kcurve(0, s)
kcurve(2 * s, 3 * s)
translate(s, 0)
rotate(radians(60))
kcurve(0, s)
translate(s, 0)
rotate(radians(-120))
kcurve(0, s)
popMatrix()
| int l = 300;
void setup() {
size(400, 400);
background(0, 0, 255);
stroke(255);
translate(width/2.0, height/2.0);
translate(-l/2.0, l*sqrt(3)/6.0);
for (int i = 1; i <= 3; i++) {
kcurve(0, l);
rotate(radians(120));
translate(-l, 0);
}
}
void kcurve(float x1, float x2) {
float s = (x2-x1)/3;
if (s < 5) {
pushMatrix();
translate(x1, 0);
line(0, 0, s, 0);
line(2*s, 0, 3*s, 0);
translate(s, 0);
rotate(radians(60));
line(0, 0, s, 0);
translate(s, 0);
rotate(radians(-120));
line(0, 0, s, 0);
popMatrix();
return;
}
pushMatrix();
translate(x1, 0);
kcurve(0, s);
kcurve(2*s, 3*s);
translate(s, 0);
rotate(radians(60));
kcurve(0, s);
translate(s, 0);
rotate(radians(-120));
kcurve(0, s);
popMatrix();
}
|
Keep all operations the same but rewrite the snippet in Java. | import Tkinter,random
def draw_pixel_2 ( sizex=640,sizey=480 ):
pos = random.randint( 0,sizex-1 ),random.randint( 0,sizey-1 )
root = Tkinter.Tk()
can = Tkinter.Canvas( root,width=sizex,height=sizey,bg='black' )
can.create_rectangle( pos*2,outline='yellow' )
can.pack()
root.title('press ESCAPE to quit')
root.bind('<Escape>',lambda e : root.quit())
root.mainloop()
draw_pixel_2()
|
size(640,480);
stroke(#ffff00);
ellipse(random(640),random(480),1,1);
|
Generate an equivalent Java version of this Python code. | from PIL import Image
img = Image.new('RGB', (320, 240))
pixels = img.load()
pixels[100,100] = (255,0,0)
img.show()
| import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class DrawAPixel extends JFrame{
public DrawAPixel() {
super("Red Pixel");
setSize(320, 240);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
@Override
public void paint(Graphics g) {
g.setColor(new Color(255, 0, 0));
g.drawRect(100, 100, 1, 1);
}
public static void main(String[] args) {
new DrawAPixel();
}
}
|
Preserve the algorithm and functionality while converting the code from Python to Java. |
import urllib.request
from collections import Counter
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")
dictionary = open("unixdict.txt","r")
wordList = dictionary.read().split('\n')
dictionary.close()
filteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]
for word in filteredWords[:-9]:
position = filteredWords.index(word)
newWord = "".join([filteredWords[position+i][i] for i in range(0,9)])
if newWord in filteredWords:
print(newWord)
| import java.io.*;
import java.util.*;
public class NeighbourWords {
public static void main(String[] args) {
try {
int minLength = 9;
List<String> words = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.length() >= minLength)
words.add(line);
}
}
Collections.sort(words);
String previousWord = null;
int count = 0;
for (int i = 0, n = words.size(); i + minLength <= n; ++i) {
StringBuilder sb = new StringBuilder(minLength);
for (int j = 0; j < minLength; ++j)
sb.append(words.get(i + j).charAt(j));
String word = sb.toString();
if (word.equals(previousWord))
continue;
if (Collections.binarySearch(words, word) >= 0)
System.out.printf("%2d. %s\n", ++count, word);
previousWord = word;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
Translate the given Python code snippet into Java without altering its behavior. |
from myhdl import *
@block
def NOTgate( a, q ):
@always_comb
def NOTgateLogic():
q.next = not a
return NOTgateLogic
@block
def ANDgate( a, b, q ):
@always_comb
def ANDgateLogic():
q.next = a and b
return ANDgateLogic
@block
def ORgate( a, b, q ):
@always_comb
def ORgateLogic():
q.next = a or b
return ORgateLogic
@block
def XORgate( a, b, q ):
nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]
inv0 = NOTgate( a, nota )
inv1 = NOTgate( b, notb )
and2a = ANDgate( a, notb, annotb )
and2b = ANDgate( b, nota, bnnota )
or2a = ORgate( annotb, bnnota, q )
return inv0, inv1, and2a, and2b, or2a
@block
def HalfAdder( in_a, in_b, summ, carry ):
and2a = ANDgate(in_a, in_b, carry)
xor2a = XORgate(in_a, in_b, summ)
return and2a, xor2a
@block
def FullAdder( fa_c0, fa_a, fa_b, fa_s, fa_c1 ):
ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]
HalfAdder01 = HalfAdder( fa_c0, fa_a, ha1_s, ha1_c1 )
HalfAdder02 = HalfAdder( ha1_s, fa_b, fa_s, ha2_c1 )
or2a = ORgate(ha1_c1, ha2_c1, fa_c1)
return HalfAdder01, HalfAdder02, or2a
@block
def Adder4b( ina, inb, cOut, sum4):
cl = [Signal(bool()) for i in range(0,4)]
sl = [Signal(bool()) for i in range(4)]
HalfAdder0 = HalfAdder( ina(0), inb(0), sl[0], cl[1] )
FullAdder1 = FullAdder( cl[1], ina(1), inb(1), sl[1], cl[2] )
FullAdder2 = FullAdder( cl[2], ina(2), inb(2), sl[2], cl[3] )
FullAdder3 = FullAdder( cl[3], ina(3), inb(3), sl[3], cOut )
sc = ConcatSignal(*reversed(sl))
@always_comb
def list2intbv():
sum4.next = sc
return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv
t_co, t_s, t_a, t_b, dbug = [Signal(bool(0)) for i in range(5)]
ina4, inb4, sum4 = [Signal(intbv(0)[4:]) for i in range(3)]
from random import randrange
@block
def Test_Adder4b():
dut = Adder4b( ina4, inb4, t_co, sum4 )
@instance
def check():
print( "\n b a | c1 s \n -------------------" )
for i in range(15):
ina4.next, inb4.next = randrange(2**4), randrange(2**4)
yield delay(5)
print( " %2d %2d | %2d %2d " \
% (ina4,inb4, t_co,sum4) )
assert t_co * 16 + sum4 == ina4 + inb4
print()
return dut, check
def main():
simInst = Test_Adder4b()
simInst.name = "mySimInst"
simInst.config_sim(trace=True)
simInst.run_sim(duration=None)
inst = Adder4b( ina4, inb4, t_co, sum4 )
inst.convert(hdl='VHDL')
inst.convert(hdl='Verilog')
if __name__ == '__main__':
main()
| public class GateLogic
{
public interface OneInputGate
{ boolean eval(boolean input); }
public interface TwoInputGate
{ boolean eval(boolean input1, boolean input2); }
public interface MultiGate
{ boolean[] eval(boolean... inputs); }
public static OneInputGate NOT = new OneInputGate() {
public boolean eval(boolean input)
{ return !input; }
};
public static TwoInputGate AND = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{ return input1 && input2; }
};
public static TwoInputGate OR = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{ return input1 || input2; }
};
public static TwoInputGate XOR = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{
return OR.eval(
AND.eval(input1, NOT.eval(input2)),
AND.eval(NOT.eval(input1), input2)
);
}
};
public static MultiGate HALF_ADDER = new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != 2)
throw new IllegalArgumentException();
return new boolean[] {
XOR.eval(inputs[0], inputs[1]),
AND.eval(inputs[0], inputs[1])
};
}
};
public static MultiGate FULL_ADDER = new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != 3)
throw new IllegalArgumentException();
boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);
boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);
return new boolean[] {
haOutputs2[0],
OR.eval(haOutputs1[1], haOutputs2[1])
};
}
};
public static MultiGate buildAdder(final int numBits)
{
return new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != (numBits << 1))
throw new IllegalArgumentException();
boolean[] outputs = new boolean[numBits + 1];
boolean[] faInputs = new boolean[3];
boolean[] faOutputs = null;
for (int i = 0; i < numBits; i++)
{
faInputs[0] = (faOutputs == null) ? false : faOutputs[1];
faInputs[1] = inputs[i];
faInputs[2] = inputs[numBits + i];
faOutputs = FULL_ADDER.eval(faInputs);
outputs[i] = faOutputs[0];
}
if (faOutputs != null)
outputs[numBits] = faOutputs[1];
return outputs;
}
};
}
public static void main(String[] args)
{
int numBits = Integer.parseInt(args[0]);
int firstNum = Integer.parseInt(args[1]);
int secondNum = Integer.parseInt(args[2]);
int maxNum = 1 << numBits;
if ((firstNum < 0) || (firstNum >= maxNum))
{
System.out.println("First number is out of range");
return;
}
if ((secondNum < 0) || (secondNum >= maxNum))
{
System.out.println("Second number is out of range");
return;
}
MultiGate multiBitAdder = buildAdder(numBits);
boolean[] inputs = new boolean[numBits << 1];
String firstNumDisplay = "";
String secondNumDisplay = "";
for (int i = 0; i < numBits; i++)
{
boolean firstBit = ((firstNum >>> i) & 1) == 1;
boolean secondBit = ((secondNum >>> i) & 1) == 1;
inputs[i] = firstBit;
inputs[numBits + i] = secondBit;
firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay;
secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay;
}
boolean[] outputs = multiBitAdder.eval(inputs);
int outputNum = 0;
String outputNumDisplay = "";
String outputCarryDisplay = null;
for (int i = numBits; i >= 0; i--)
{
outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);
if (i == numBits)
outputCarryDisplay = outputs[i] ? "1" : "0";
else
outputNumDisplay += (outputs[i] ? "1" : "0");
}
System.out.println("numBits=" + numBits);
System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")");
return;
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. |
from myhdl import *
@block
def NOTgate( a, q ):
@always_comb
def NOTgateLogic():
q.next = not a
return NOTgateLogic
@block
def ANDgate( a, b, q ):
@always_comb
def ANDgateLogic():
q.next = a and b
return ANDgateLogic
@block
def ORgate( a, b, q ):
@always_comb
def ORgateLogic():
q.next = a or b
return ORgateLogic
@block
def XORgate( a, b, q ):
nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]
inv0 = NOTgate( a, nota )
inv1 = NOTgate( b, notb )
and2a = ANDgate( a, notb, annotb )
and2b = ANDgate( b, nota, bnnota )
or2a = ORgate( annotb, bnnota, q )
return inv0, inv1, and2a, and2b, or2a
@block
def HalfAdder( in_a, in_b, summ, carry ):
and2a = ANDgate(in_a, in_b, carry)
xor2a = XORgate(in_a, in_b, summ)
return and2a, xor2a
@block
def FullAdder( fa_c0, fa_a, fa_b, fa_s, fa_c1 ):
ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]
HalfAdder01 = HalfAdder( fa_c0, fa_a, ha1_s, ha1_c1 )
HalfAdder02 = HalfAdder( ha1_s, fa_b, fa_s, ha2_c1 )
or2a = ORgate(ha1_c1, ha2_c1, fa_c1)
return HalfAdder01, HalfAdder02, or2a
@block
def Adder4b( ina, inb, cOut, sum4):
cl = [Signal(bool()) for i in range(0,4)]
sl = [Signal(bool()) for i in range(4)]
HalfAdder0 = HalfAdder( ina(0), inb(0), sl[0], cl[1] )
FullAdder1 = FullAdder( cl[1], ina(1), inb(1), sl[1], cl[2] )
FullAdder2 = FullAdder( cl[2], ina(2), inb(2), sl[2], cl[3] )
FullAdder3 = FullAdder( cl[3], ina(3), inb(3), sl[3], cOut )
sc = ConcatSignal(*reversed(sl))
@always_comb
def list2intbv():
sum4.next = sc
return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv
t_co, t_s, t_a, t_b, dbug = [Signal(bool(0)) for i in range(5)]
ina4, inb4, sum4 = [Signal(intbv(0)[4:]) for i in range(3)]
from random import randrange
@block
def Test_Adder4b():
dut = Adder4b( ina4, inb4, t_co, sum4 )
@instance
def check():
print( "\n b a | c1 s \n -------------------" )
for i in range(15):
ina4.next, inb4.next = randrange(2**4), randrange(2**4)
yield delay(5)
print( " %2d %2d | %2d %2d " \
% (ina4,inb4, t_co,sum4) )
assert t_co * 16 + sum4 == ina4 + inb4
print()
return dut, check
def main():
simInst = Test_Adder4b()
simInst.name = "mySimInst"
simInst.config_sim(trace=True)
simInst.run_sim(duration=None)
inst = Adder4b( ina4, inb4, t_co, sum4 )
inst.convert(hdl='VHDL')
inst.convert(hdl='Verilog')
if __name__ == '__main__':
main()
| public class GateLogic
{
public interface OneInputGate
{ boolean eval(boolean input); }
public interface TwoInputGate
{ boolean eval(boolean input1, boolean input2); }
public interface MultiGate
{ boolean[] eval(boolean... inputs); }
public static OneInputGate NOT = new OneInputGate() {
public boolean eval(boolean input)
{ return !input; }
};
public static TwoInputGate AND = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{ return input1 && input2; }
};
public static TwoInputGate OR = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{ return input1 || input2; }
};
public static TwoInputGate XOR = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{
return OR.eval(
AND.eval(input1, NOT.eval(input2)),
AND.eval(NOT.eval(input1), input2)
);
}
};
public static MultiGate HALF_ADDER = new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != 2)
throw new IllegalArgumentException();
return new boolean[] {
XOR.eval(inputs[0], inputs[1]),
AND.eval(inputs[0], inputs[1])
};
}
};
public static MultiGate FULL_ADDER = new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != 3)
throw new IllegalArgumentException();
boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);
boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);
return new boolean[] {
haOutputs2[0],
OR.eval(haOutputs1[1], haOutputs2[1])
};
}
};
public static MultiGate buildAdder(final int numBits)
{
return new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != (numBits << 1))
throw new IllegalArgumentException();
boolean[] outputs = new boolean[numBits + 1];
boolean[] faInputs = new boolean[3];
boolean[] faOutputs = null;
for (int i = 0; i < numBits; i++)
{
faInputs[0] = (faOutputs == null) ? false : faOutputs[1];
faInputs[1] = inputs[i];
faInputs[2] = inputs[numBits + i];
faOutputs = FULL_ADDER.eval(faInputs);
outputs[i] = faOutputs[0];
}
if (faOutputs != null)
outputs[numBits] = faOutputs[1];
return outputs;
}
};
}
public static void main(String[] args)
{
int numBits = Integer.parseInt(args[0]);
int firstNum = Integer.parseInt(args[1]);
int secondNum = Integer.parseInt(args[2]);
int maxNum = 1 << numBits;
if ((firstNum < 0) || (firstNum >= maxNum))
{
System.out.println("First number is out of range");
return;
}
if ((secondNum < 0) || (secondNum >= maxNum))
{
System.out.println("Second number is out of range");
return;
}
MultiGate multiBitAdder = buildAdder(numBits);
boolean[] inputs = new boolean[numBits << 1];
String firstNumDisplay = "";
String secondNumDisplay = "";
for (int i = 0; i < numBits; i++)
{
boolean firstBit = ((firstNum >>> i) & 1) == 1;
boolean secondBit = ((secondNum >>> i) & 1) == 1;
inputs[i] = firstBit;
inputs[numBits + i] = secondBit;
firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay;
secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay;
}
boolean[] outputs = multiBitAdder.eval(inputs);
int outputNum = 0;
String outputNumDisplay = "";
String outputCarryDisplay = null;
for (int i = numBits; i >= 0; i--)
{
outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);
if (i == numBits)
outputCarryDisplay = outputs[i] ? "1" : "0";
else
outputNumDisplay += (outputs[i] ? "1" : "0");
}
System.out.println("numBits=" + numBits);
System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")");
return;
}
}
|
Translate this program into Java but keep the logic exactly as in Python. | import math
from sys import stdout
LOG_10 = 2.302585092994
def build_oms(s):
if s % 2 == 0:
s += 1
q = [[0 for j in range(s)] for i in range(s)]
p = 1
i = s // 2
j = 0
while p <= (s * s):
q[i][j] = p
ti = i + 1
if ti >= s: ti = 0
tj = j - 1
if tj < 0: tj = s - 1
if q[ti][tj] != 0:
ti = i
tj = j + 1
i = ti
j = tj
p = p + 1
return q, s
def build_sems(s):
if s % 2 == 1:
s += 1
while s % 4 == 0:
s += 2
q = [[0 for j in range(s)] for i in range(s)]
z = s // 2
b = z * z
c = 2 * b
d = 3 * b
o = build_oms(z)
for j in range(0, z):
for i in range(0, z):
a = o[0][i][j]
q[i][j] = a
q[i + z][j + z] = a + b
q[i + z][j] = a + c
q[i][j + z] = a + d
lc = z // 2
rc = lc
for j in range(0, z):
for i in range(0, s):
if i < lc or i > s - rc or (i == lc and j == lc):
if not (i == 0 and j == lc):
t = q[i][j]
q[i][j] = q[i][j + z]
q[i][j + z] = t
return q, s
def format_sqr(s, l):
for i in range(0, l - len(s)):
s = "0" + s
return s + " "
def display(q):
s = q[1]
print(" - {0} x {1}\n".format(s, s))
k = 1 + math.floor(math.log(s * s) / LOG_10)
for j in range(0, s):
for i in range(0, s):
stdout.write(format_sqr("{0}".format(q[0][i][j]), k))
print()
print("Magic sum: {0}\n".format(s * ((s * s) + 1) // 2))
stdout.write("Singly Even Magic Square")
display(build_sems(6))
| public class MagicSquareSinglyEven {
public static void main(String[] args) {
int n = 6;
for (int[] row : magicSquareSinglyEven(n)) {
for (int x : row)
System.out.printf("%2s ", x);
System.out.println();
}
System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2);
}
public static int[][] magicSquareOdd(final int n) {
if (n < 3 || n % 2 == 0)
throw new IllegalArgumentException("base must be odd and > 2");
int value = 0;
int gridSize = n * n;
int c = n / 2, r = 0;
int[][] result = new int[n][n];
while (++value <= gridSize) {
result[r][c] = value;
if (r == 0) {
if (c == n - 1) {
r++;
} else {
r = n - 1;
c++;
}
} else if (c == n - 1) {
r--;
c = 0;
} else if (result[r - 1][c + 1] == 0) {
r--;
c++;
} else {
r++;
}
}
return result;
}
static int[][] magicSquareSinglyEven(final int n) {
if (n < 6 || (n - 2) % 4 != 0)
throw new IllegalArgumentException("base must be a positive "
+ "multiple of 4 plus 2");
int size = n * n;
int halfN = n / 2;
int subSquareSize = size / 4;
int[][] subSquare = magicSquareOdd(halfN);
int[] quadrantFactors = {0, 2, 3, 1};
int[][] result = new int[n][n];
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
int quadrant = (r / halfN) * 2 + (c / halfN);
result[r][c] = subSquare[r % halfN][c % halfN];
result[r][c] += quadrantFactors[quadrant] * subSquareSize;
}
}
int nColsLeft = halfN / 2;
int nColsRight = nColsLeft - 1;
for (int r = 0; r < halfN; r++)
for (int c = 0; c < n; c++) {
if (c < nColsLeft || c >= n - nColsRight
|| (c == nColsLeft && r == nColsLeft)) {
if (c == 0 && r == nColsLeft)
continue;
int tmp = result[r][c];
result[r][c] = result[r + halfN][c];
result[r + halfN][c] = tmp;
}
}
return result;
}
}
|
Change the following Python code into Java without altering its purpose. | >>> from itertools import permutations
>>> pieces = 'KQRrBbNN'
>>> starts = {''.join(p).upper() for p in permutations(pieces)
if p.index('B') % 2 != p.index('b') % 2
and ( p.index('r') < p.index('K') < p.index('R')
or p.index('R') < p.index('K') < p.index('r') ) }
>>> len(starts)
960
>>> starts.pop()
'QNBRNKRB'
>>>
| 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());
}
}
}
|
Write the same code in Java as shown below in Python. |
def meaning_of_life():
return 42
if __name__ == "__main__":
print("Main: The meaning of life is %s" % meaning_of_life())
| public class ScriptedMain {
public static int meaningOfLife() {
return 42;
}
public static void main(String[] args) {
System.out.println("Main: The meaning of life is " + meaningOfLife());
}
}
|
Translate this program into Java but keep the logic exactly as in Python. |
def meaning_of_life():
return 42
if __name__ == "__main__":
print("Main: The meaning of life is %s" % meaning_of_life())
| public class ScriptedMain {
public static int meaningOfLife() {
return 42;
}
public static void main(String[] args) {
System.out.println("Main: The meaning of life is " + meaningOfLife());
}
}
|
Write the same algorithm in Java as shown in this Python implementation. | import math
def perlin_noise(x, y, z):
X = math.floor(x) & 255
Y = math.floor(y) & 255
Z = math.floor(z) & 255
x -= math.floor(x)
y -= math.floor(y)
z -= math.floor(z)
u = fade(x)
v = fade(y)
w = fade(z)
A = p[X ]+Y; AA = p[A]+Z; AB = p[A+1]+Z
B = p[X+1]+Y; BA = p[B]+Z; BB = p[B+1]+Z
return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ),
grad(p[BA ], x-1, y , z )),
lerp(u, grad(p[AB ], x , y-1, z ),
grad(p[BB ], x-1, y-1, z ))),
lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ),
grad(p[BA+1], x-1, y , z-1 )),
lerp(u, grad(p[AB+1], x , y-1, z-1 ),
grad(p[BB+1], x-1, y-1, z-1 ))))
def fade(t):
return t ** 3 * (t * (t * 6 - 15) + 10)
def lerp(t, a, b):
return a + t * (b - a)
def grad(hash, x, y, z):
h = hash & 15
u = x if h<8 else y
v = y if h<4 else (x if h in (12, 14) else z)
return (u if (h&1) == 0 else -u) + (v if (h&2) == 0 else -v)
p = [None] * 512
permutation = [151,160,137,91,90,15,
131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]
for i in range(256):
p[256+i] = p[i] = permutation[i]
if __name__ == '__main__':
print("%1.17f" % perlin_noise(3.14, 42, 7))
|
public final class ImprovedNoise {
static public double noise(double x, double y, double z) {
int X = (int)Math.floor(x) & 255,
Y = (int)Math.floor(y) & 255,
Z = (int)Math.floor(z) & 255;
x -= Math.floor(x);
y -= Math.floor(y);
z -= Math.floor(z);
double u = fade(x),
v = fade(y),
w = fade(z);
int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,
B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;
return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ),
grad(p[BA ], x-1, y , z )),
lerp(u, grad(p[AB ], x , y-1, z ),
grad(p[BB ], x-1, y-1, z ))),
lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ),
grad(p[BA+1], x-1, y , z-1 )),
lerp(u, grad(p[AB+1], x , y-1, z-1 ),
grad(p[BB+1], x-1, y-1, z-1 ))));
}
static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }
static double lerp(double t, double a, double b) { return a + t * (b - a); }
static double grad(int hash, double x, double y, double z) {
int h = hash & 15;
double u = h<8 ? x : y,
v = h<4 ? y : h==12||h==14 ? x : z;
return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);
}
static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15,
131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180
};
static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; }
}
|
Write the same algorithm in Java as shown in this Python implementation. | >>> import os
>>> print('\n'.join(sorted(os.listdir('.'))))
DLLs
Doc
LICENSE.txt
Lib
NEWS.txt
README.txt
Scripts
Tools
include
libs
python.exe
pythonw.exe
tcl
>>>
| package rosetta;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class UnixLS {
public static void main(String[] args) throws IOException {
Files.list(Path.of("")).sorted().forEach(System.out::println);
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? |
from unicodedata import name
def unicode_code(ch):
return 'U+{:04x}'.format(ord(ch))
def utf8hex(ch):
return " ".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()
if __name__ == "__main__":
print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))
chars = ['A', 'ö', 'Ж', '€', '𝄞']
for char in chars:
print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))
| import java.nio.charset.StandardCharsets;
import java.util.Formatter;
public class UTF8EncodeDecode {
public static byte[] utf8encode(int codepoint) {
return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);
}
public static int utf8decode(byte[] bytes) {
return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);
}
public static void main(String[] args) {
System.out.printf("%-7s %-43s %7s\t%s\t%7s%n",
"Char", "Name", "Unicode", "UTF-8 encoded", "Decoded");
for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {
byte[] encoded = utf8encode(codepoint);
Formatter formatter = new Formatter();
for (byte b : encoded) {
formatter.format("%02X ", b);
}
String encodedHex = formatter.toString();
int decoded = utf8decode(encoded);
System.out.printf("%-7c %-43s U+%04X\t%-12s\tU+%04X%n",
codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);
}
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. |
from __future__ import division
import sys
from PIL import Image
def _fpart(x):
return x - int(x)
def _rfpart(x):
return 1 - _fpart(x)
def putpixel(img, xy, color, alpha=1):
compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg))
c = compose_color(img.getpixel(xy), color)
img.putpixel(xy, c)
def draw_line(img, p1, p2, color):
x1, y1 = p1
x2, y2 = p2
dx, dy = x2-x1, y2-y1
steep = abs(dx) < abs(dy)
p = lambda px, py: ((px,py), (py,px))[steep]
if steep:
x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx
if x2 < x1:
x1, x2, y1, y2 = x2, x1, y2, y1
grad = dy/dx
intery = y1 + _rfpart(x1) * grad
def draw_endpoint(pt):
x, y = pt
xend = round(x)
yend = y + grad * (xend - x)
xgap = _rfpart(x + 0.5)
px, py = int(xend), int(yend)
putpixel(img, p(px, py), color, _rfpart(yend) * xgap)
putpixel(img, p(px, py+1), color, _fpart(yend) * xgap)
return px
xstart = draw_endpoint(p(*p1)) + 1
xend = draw_endpoint(p(*p2))
for x in range(xstart, xend):
y = int(intery)
putpixel(img, p(x, y), color, _rfpart(intery))
putpixel(img, p(x, y+1), color, _fpart(intery))
intery += grad
if __name__ == '__main__':
if len(sys.argv) != 2:
print 'usage: python xiaolinwu.py [output-file]'
sys.exit(-1)
blue = (0, 0, 255)
yellow = (255, 255, 0)
img = Image.new("RGB", (500,500), blue)
for a in range(10, 431, 60):
draw_line(img, (10, 10), (490, a), yellow)
draw_line(img, (10, 10), (a, 490), yellow)
draw_line(img, (10, 10), (490, 490), yellow)
filename = sys.argv[1]
img.save(filename)
print 'image saved to', filename
| 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);
});
}
}
|
Translate this program into Java but keep the logic exactly as in Python. |
import curses
def print_message():
stdscr.addstr('This is the message.\n')
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
stdscr.addstr('CTRL+P for message or q to quit.\n')
while True:
c = stdscr.getch()
if c == 16: print_message()
elif c == ord('q'): break
curses.nocbreak()
stdscr.keypad(0)
curses.echo()
curses.endwin()
| package keybord.macro.demo;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
class KeyboardMacroDemo {
public static void main( String [] args ) {
final JFrame frame = new JFrame();
String directions = "<html><b>Ctrl-S</b> to show frame title<br>"
+"<b>Ctrl-H</b> to hide it</html>";
frame.add( new JLabel(directions));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addKeyListener( new KeyAdapter(){
public void keyReleased( KeyEvent e ) {
if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){
frame.setTitle("Hello there");
}else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){
frame.setTitle("");
}
}
});
frame.pack();
frame.setVisible(true);
}
}
|
Preserve the algorithm and functionality while converting the code from Python to Java. |
import curses
def print_message():
stdscr.addstr('This is the message.\n')
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
stdscr.addstr('CTRL+P for message or q to quit.\n')
while True:
c = stdscr.getch()
if c == 16: print_message()
elif c == ord('q'): break
curses.nocbreak()
stdscr.keypad(0)
curses.echo()
curses.endwin()
| package keybord.macro.demo;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
class KeyboardMacroDemo {
public static void main( String [] args ) {
final JFrame frame = new JFrame();
String directions = "<html><b>Ctrl-S</b> to show frame title<br>"
+"<b>Ctrl-H</b> to hide it</html>";
frame.add( new JLabel(directions));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addKeyListener( new KeyAdapter(){
public void keyReleased( KeyEvent e ) {
if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){
frame.setTitle("Hello there");
}else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){
frame.setTitle("");
}
}
});
frame.pack();
frame.setVisible(true);
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | >>> from itertools import product
>>> nuggets = set(range(101))
>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):
nuggets.discard(6*s + 9*n + 20*t)
>>> max(nuggets)
43
>>>
| public class McNuggets {
public static void main(String... args) {
int[] SIZES = new int[] { 6, 9, 20 };
int MAX_TOTAL = 100;
int numSizes = SIZES.length;
int[] counts = new int[numSizes];
int maxFound = MAX_TOTAL + 1;
boolean[] found = new boolean[maxFound];
int numFound = 0;
int total = 0;
boolean advancedState = false;
do {
if (!found[total]) {
found[total] = true;
numFound++;
}
advancedState = false;
for (int i = 0; i < numSizes; i++) {
int curSize = SIZES[i];
if ((total + curSize) > MAX_TOTAL) {
total -= counts[i] * curSize;
counts[i] = 0;
}
else {
counts[i]++;
total += curSize;
advancedState = true;
break;
}
}
} while ((numFound < maxFound) && advancedState);
if (numFound < maxFound) {
for (int i = MAX_TOTAL; i >= 0; i--) {
if (!found[i]) {
System.out.println("Largest non-McNugget number in the search space is " + i);
break;
}
}
}
else {
System.out.println("All numbers in the search space are McNugget numbers");
}
return;
}
}
|
Write the same code in Java as shown below in Python. | def MagicSquareDoublyEven(order):
sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]
n1 = order/4
for r in range(n1):
r1 = sq[r][n1:-n1]
r2 = sq[order -r - 1][n1:-n1]
r1.reverse()
r2.reverse()
sq[r][n1:-n1] = r2
sq[order -r - 1][n1:-n1] = r1
for r in range(n1, order-n1):
r1 = sq[r][:n1]
r2 = sq[order -r - 1][order-n1:]
r1.reverse()
r2.reverse()
sq[r][:n1] = r2
sq[order -r - 1][order-n1:] = r1
return sq
def printsq(s):
n = len(s)
bl = len(str(n**2))+1
for i in range(n):
print ''.join( [ ("%"+str(bl)+"s")%(str(x)) for x in s[i]] )
print "\nMagic constant = %d"%sum(s[0])
printsq(MagicSquareDoublyEven(8))
| 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;
}
}
|
Change the following Python code into Java without altering its purpose. | def MagicSquareDoublyEven(order):
sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]
n1 = order/4
for r in range(n1):
r1 = sq[r][n1:-n1]
r2 = sq[order -r - 1][n1:-n1]
r1.reverse()
r2.reverse()
sq[r][n1:-n1] = r2
sq[order -r - 1][n1:-n1] = r1
for r in range(n1, order-n1):
r1 = sq[r][:n1]
r2 = sq[order -r - 1][order-n1:]
r1.reverse()
r2.reverse()
sq[r][:n1] = r2
sq[order -r - 1][order-n1:] = r1
return sq
def printsq(s):
n = len(s)
bl = len(str(n**2))+1
for i in range(n):
print ''.join( [ ("%"+str(bl)+"s")%(str(x)) for x in s[i]] )
print "\nMagic constant = %d"%sum(s[0])
printsq(MagicSquareDoublyEven(8))
| 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;
}
}
|
Translate this program into Java but keep the logic exactly as in Python. | >>>
>>> inf = 1e234 * 1e234
>>> _inf = 1e234 * -1e234
>>> _zero = 1 / _inf
>>> nan = inf + _inf
>>> inf, _inf, _zero, nan
(inf, -inf, -0.0, nan)
>>>
>>> for value in (inf, _inf, _zero, nan): print (value)
inf
-inf
-0.0
nan
>>>
>>> float('nan')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> -0.
-0.0
>>>
>>> nan == nan
False
>>> nan is nan
True
>>> 0. == -0.
True
>>> 0. is -0.
False
>>> inf + _inf
nan
>>> 0.0 * nan
nan
>>> nan * 0.0
nan
>>> 0.0 * inf
nan
>>> inf * 0.0
nan
| public class Extreme {
public static void main(String[] args) {
double negInf = -1.0 / 0.0;
double inf = 1.0 / 0.0;
double nan = 0.0 / 0.0;
double negZero = -2.0 / inf;
System.out.println("Negative inf: " + negInf);
System.out.println("Positive inf: " + inf);
System.out.println("NaN: " + nan);
System.out.println("Negative 0: " + negZero);
System.out.println("inf + -inf: " + (inf + negInf));
System.out.println("0 * NaN: " + (0 * nan));
System.out.println("NaN == NaN: " + (nan == nan));
}
}
|
Keep all operations the same but rewrite the snippet in Java. | >>>
>>> inf = 1e234 * 1e234
>>> _inf = 1e234 * -1e234
>>> _zero = 1 / _inf
>>> nan = inf + _inf
>>> inf, _inf, _zero, nan
(inf, -inf, -0.0, nan)
>>>
>>> for value in (inf, _inf, _zero, nan): print (value)
inf
-inf
-0.0
nan
>>>
>>> float('nan')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> -0.
-0.0
>>>
>>> nan == nan
False
>>> nan is nan
True
>>> 0. == -0.
True
>>> 0. is -0.
False
>>> inf + _inf
nan
>>> 0.0 * nan
nan
>>> nan * 0.0
nan
>>> 0.0 * inf
nan
>>> inf * 0.0
nan
| public class Extreme {
public static void main(String[] args) {
double negInf = -1.0 / 0.0;
double inf = 1.0 / 0.0;
double nan = 0.0 / 0.0;
double negZero = -2.0 / inf;
System.out.println("Negative inf: " + negInf);
System.out.println("Positive inf: " + inf);
System.out.println("NaN: " + nan);
System.out.println("Negative 0: " + negZero);
System.out.println("inf + -inf: " + (inf + negInf));
System.out.println("0 * NaN: " + (0 * nan));
System.out.println("NaN == NaN: " + (nan == nan));
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | >>>
>>> inf = 1e234 * 1e234
>>> _inf = 1e234 * -1e234
>>> _zero = 1 / _inf
>>> nan = inf + _inf
>>> inf, _inf, _zero, nan
(inf, -inf, -0.0, nan)
>>>
>>> for value in (inf, _inf, _zero, nan): print (value)
inf
-inf
-0.0
nan
>>>
>>> float('nan')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> -0.
-0.0
>>>
>>> nan == nan
False
>>> nan is nan
True
>>> 0. == -0.
True
>>> 0. is -0.
False
>>> inf + _inf
nan
>>> 0.0 * nan
nan
>>> nan * 0.0
nan
>>> 0.0 * inf
nan
>>> inf * 0.0
nan
| public class Extreme {
public static void main(String[] args) {
double negInf = -1.0 / 0.0;
double inf = 1.0 / 0.0;
double nan = 0.0 / 0.0;
double negZero = -2.0 / inf;
System.out.println("Negative inf: " + negInf);
System.out.println("Positive inf: " + inf);
System.out.println("NaN: " + nan);
System.out.println("Negative 0: " + negZero);
System.out.println("inf + -inf: " + (inf + negInf));
System.out.println("0 * NaN: " + (0 * nan));
System.out.println("NaN == NaN: " + (nan == nan));
}
}
|
Convert this Python snippet to Java and keep its semantics consistent. | mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
const = 0x2545F4914F6CDD1D
class Xorshift_star():
def __init__(self, seed=0):
self.state = seed & mask64
def seed(self, num):
self.state = num & mask64
def next_int(self):
"return random int between 0 and 2**32"
x = self.state
x = (x ^ (x >> 12)) & mask64
x = (x ^ (x << 25)) & mask64
x = (x ^ (x >> 27)) & mask64
self.state = x
answer = (((x * const) & mask64) >> 32) & mask32
return answer
def next_float(self):
"return random float between 0 and 1"
return self.next_int() / (1 << 32)
if __name__ == '__main__':
random_gen = Xorshift_star()
random_gen.seed(1234567)
for i in range(5):
print(random_gen.next_int())
random_gen.seed(987654321)
hist = {i:0 for i in range(5)}
for i in range(100_000):
hist[int(random_gen.next_float() *5)] += 1
print(hist)
| public class XorShiftStar {
private static final long MAGIC = Long.parseUnsignedLong("2545F4914F6CDD1D", 16);
private long state;
public void seed(long num) {
state = num;
}
public int nextInt() {
long x;
int answer;
x = state;
x = x ^ (x >>> 12);
x = x ^ (x << 25);
x = x ^ (x >>> 27);
state = x;
answer = (int) ((x * MAGIC) >> 32);
return answer;
}
public float nextFloat() {
return (float) Integer.toUnsignedLong(nextInt()) / (1L << 32);
}
public static void main(String[] args) {
var rng = new XorShiftStar();
rng.seed(1234567);
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println();
int[] counts = {0, 0, 0, 0, 0};
rng.seed(987654321);
for (int i = 0; i < 100_000; i++) {
int j = (int) Math.floor(rng.nextFloat() * 5.0);
counts[j]++;
}
for (int i = 0; i < counts.length; i++) {
System.out.printf("%d: %d\n", i, counts[i]);
}
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. |
import inflect
def count_letters(word):
count = 0
for letter in word:
if letter != ',' and letter !='-' and letter !=' ':
count += 1
return count
def split_with_spaces(sentence):
sentence_list = []
curr_word = ""
for c in sentence:
if c == " " and curr_word != "":
sentence_list.append(curr_word+" ")
curr_word = ""
else:
curr_word += c
if len(curr_word) > 0:
sentence_list.append(curr_word)
return sentence_list
def my_num_to_words(p, my_number):
number_string_list = p.number_to_words(my_number, wantlist=True, andword='')
number_string = number_string_list[0]
for i in range(1,len(number_string_list)):
number_string += " " + number_string_list[i]
return number_string
def build_sentence(p, max_words):
sentence_list = split_with_spaces("Four is the number of letters in the first word of this sentence,")
num_words = 13
word_number = 2
while num_words < max_words:
ordinal_string = my_num_to_words(p, p.ordinal(word_number))
word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1]))
new_string = " "+word_number_string+" in the "+ordinal_string+","
new_list = split_with_spaces(new_string)
sentence_list += new_list
num_words += len(new_list)
word_number += 1
return sentence_list, num_words
def word_and_counts(word_num):
sentence_list, num_words = build_sentence(p, word_num)
word_str = sentence_list[word_num - 1].strip(' ,')
num_letters = len(word_str)
num_characters = 0
for word in sentence_list:
num_characters += len(word)
print('Word {0:8d} is "{1}", with {2} letters. Length of the sentence so far: {3} '.format(word_num,word_str,num_letters,num_characters))
p = inflect.engine()
sentence_list, num_words = build_sentence(p, 201)
print(" ")
print("The lengths of the first 201 words are:")
print(" ")
print('{0:3d}: '.format(1),end='')
total_characters = 0
for word_index in range(201):
word_length = count_letters(sentence_list[word_index])
total_characters += len(sentence_list[word_index])
print('{0:2d}'.format(word_length),end='')
if (word_index+1) % 20 == 0:
print(" ")
print('{0:3d}: '.format(word_index + 2),end='')
else:
print(" ",end='')
print(" ")
print(" ")
print("Length of the sentence so far: "+str(total_characters))
print(" ")
word_and_counts(1000)
word_and_counts(10000)
word_and_counts(100000)
word_and_counts(1000000)
word_and_counts(10000000)
| import java.util.HashMap;
import java.util.Map;
public class FourIsTheNumberOfLetters {
public static void main(String[] args) {
String [] words = neverEndingSentence(201);
System.out.printf("Display the first 201 numbers in the sequence:%n%3d: ", 1);
for ( int i = 0 ; i < words.length ; i++ ) {
System.out.printf("%2d ", numberOfLetters(words[i]));
if ( (i+1) % 25 == 0 ) {
System.out.printf("%n%3d: ", i+2);
}
}
System.out.printf("%nTotal number of characters in the sentence is %d%n", characterCount(words));
for ( int i = 3 ; i <= 7 ; i++ ) {
int index = (int) Math.pow(10, i);
words = neverEndingSentence(index);
String last = words[words.length-1].replace(",", "");
System.out.printf("Number of letters of the %s word is %d. The word is \"%s\". The sentence length is %,d characters.%n", toOrdinal(index), numberOfLetters(last), last, characterCount(words));
}
}
@SuppressWarnings("unused")
private static void displaySentence(String[] words, int lineLength) {
int currentLength = 0;
for ( String word : words ) {
if ( word.length() + currentLength > lineLength ) {
String first = word.substring(0, lineLength-currentLength);
String second = word.substring(lineLength-currentLength);
System.out.println(first);
System.out.print(second);
currentLength = second.length();
}
else {
System.out.print(word);
currentLength += word.length();
}
if ( currentLength == lineLength ) {
System.out.println();
currentLength = 0;
}
System.out.print(" ");
currentLength++;
if ( currentLength == lineLength ) {
System.out.println();
currentLength = 0;
}
}
System.out.println();
}
private static int numberOfLetters(String word) {
return word.replace(",","").replace("-","").length();
}
private static long characterCount(String[] words) {
int characterCount = 0;
for ( int i = 0 ; i < words.length ; i++ ) {
characterCount += words[i].length() + 1;
}
characterCount--;
return characterCount;
}
private static String[] startSentence = new String[] {"Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence,"};
private static String[] neverEndingSentence(int wordCount) {
String[] words = new String[wordCount];
int index;
for ( index = 0 ; index < startSentence.length && index < wordCount ; index++ ) {
words[index] = startSentence[index];
}
int sentencePosition = 1;
while ( index < wordCount ) {
sentencePosition++;
String word = words[sentencePosition-1];
for ( String wordLoop : numToString(numberOfLetters(word)).split(" ") ) {
words[index] = wordLoop;
index++;
if ( index == wordCount ) {
break;
}
}
words[index] = "in";
index++;
if ( index == wordCount ) {
break;
}
words[index] = "the";
index++;
if ( index == wordCount ) {
break;
}
for ( String wordLoop : (toOrdinal(sentencePosition) + ",").split(" ") ) {
words[index] = wordLoop;
index++;
if ( index == wordCount ) {
break;
}
}
}
return words;
}
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 ) : "");
}
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);
}
}
|
Translate the given Python code snippet into Java without altering its behavior. |
def validate(diagram):
rawlines = diagram.splitlines()
lines = []
for line in rawlines:
if line != '':
lines.append(line)
if len(lines) == 0:
print('diagram has no non-empty lines!')
return None
width = len(lines[0])
cols = (width - 1) // 3
if cols not in [8, 16, 32, 64]:
print('number of columns should be 8, 16, 32 or 64')
return None
if len(lines)%2 == 0:
print('number of non-empty lines should be odd')
return None
if lines[0] != (('+--' * cols)+'+'):
print('incorrect header line')
return None
for i in range(len(lines)):
line=lines[i]
if i == 0:
continue
elif i%2 == 0:
if line != lines[0]:
print('incorrect separator line')
return None
elif len(line) != width:
print('inconsistent line widths')
return None
elif line[0] != '|' or line[width-1] != '|':
print("non-separator lines must begin and end with '|'")
return None
return lines
def decode(lines):
print("Name Bits Start End")
print("======= ==== ===== ===")
startbit = 0
results = []
for line in lines:
infield=False
for c in line:
if not infield and c == '|':
infield = True
spaces = 0
name = ''
elif infield:
if c == ' ':
spaces += 1
elif c != '|':
name += c
else:
bits = (spaces + len(name) + 1) // 3
endbit = startbit + bits - 1
print('{0:7} {1:2d} {2:2d} {3:2d}'.format(name, bits, startbit, endbit))
reslist = [name, bits, startbit, endbit]
results.append(reslist)
spaces = 0
name = ''
startbit += bits
return results
def unpack(results, hex):
print("\nTest string in hex:")
print(hex)
print("\nTest string in binary:")
bin = f'{int(hex, 16):0>{4*len(hex)}b}'
print(bin)
print("\nUnpacked:\n")
print("Name Size Bit pattern")
print("======= ==== ================")
for r in results:
name = r[0]
size = r[1]
startbit = r[2]
endbit = r[3]
bitpattern = bin[startbit:endbit+1]
print('{0:7} {1:2d} {2:16}'.format(name, size, bitpattern))
diagram =
lines = validate(diagram)
if lines == None:
print("No lines returned")
else:
print(" ")
print("Diagram after trimming whitespace and removal of blank lines:")
print(" ")
for line in lines:
print(line)
print(" ")
print("Decoded:")
print(" ")
results = decode(lines)
hex = "78477bbf5496e12e1bf169a4"
unpack(results, hex)
| import java.math.BigInteger;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class AsciiArtDiagramConverter {
private static final String TEST = "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| ID |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"|QR| Opcode |AA|TC|RD|RA| Z | RCODE |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| QDCOUNT |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| ANCOUNT |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| NSCOUNT |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| ARCOUNT |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+";
public static void main(String[] args) {
validate(TEST);
display(TEST);
Map<String,List<Integer>> asciiMap = decode(TEST);
displayMap(asciiMap);
displayCode(asciiMap, "78477bbf5496e12e1bf169a4");
}
private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) {
System.out.printf("%nTest string in hex:%n%s%n%n", hex);
String bin = new BigInteger(hex,16).toString(2);
int length = 0;
for ( String code : asciiMap.keySet() ) {
List<Integer> pos = asciiMap.get(code);
length += pos.get(1) - pos.get(0) + 1;
}
while ( length > bin.length() ) {
bin = "0" + bin;
}
System.out.printf("Test string in binary:%n%s%n%n", bin);
System.out.printf("Name Size Bit Pattern%n");
System.out.printf("-------- ----- -----------%n");
for ( String code : asciiMap.keySet() ) {
List<Integer> pos = asciiMap.get(code);
int start = pos.get(0);
int end = pos.get(1);
System.out.printf("%-8s %2d %s%n", code, end-start+1, bin.substring(start, end+1));
}
}
private static void display(String ascii) {
System.out.printf("%nDiagram:%n%n");
for ( String s : TEST.split("\\r\\n") ) {
System.out.println(s);
}
}
private static void displayMap(Map<String,List<Integer>> asciiMap) {
System.out.printf("%nDecode:%n%n");
System.out.printf("Name Size Start End%n");
System.out.printf("-------- ----- ----- -----%n");
for ( String code : asciiMap.keySet() ) {
List<Integer> pos = asciiMap.get(code);
System.out.printf("%-8s %2d %2d %2d%n", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1));
}
}
private static Map<String,List<Integer>> decode(String ascii) {
Map<String,List<Integer>> map = new LinkedHashMap<>();
String[] split = TEST.split("\\r\\n");
int size = split[0].indexOf("+", 1) - split[0].indexOf("+");
int length = split[0].length() - 1;
for ( int i = 1 ; i < split.length ; i += 2 ) {
int barIndex = 1;
String test = split[i];
int next;
while ( barIndex < length && (next = test.indexOf("|", barIndex)) > 0 ) {
List<Integer> startEnd = new ArrayList<>();
startEnd.add((barIndex/size) + (i/2)*(length/size));
startEnd.add(((next-1)/size) + (i/2)*(length/size));
String code = test.substring(barIndex, next).replace(" ", "");
map.put(code, startEnd);
barIndex = next + 1;
}
}
return map;
}
private static void validate(String ascii) {
String[] split = TEST.split("\\r\\n");
if ( split.length % 2 != 1 ) {
throw new RuntimeException("ERROR 1: Invalid number of input lines. Line count = " + split.length);
}
int size = 0;
for ( int i = 0 ; i < split.length ; i++ ) {
String test = split[i];
if ( i % 2 == 0 ) {
if ( ! test.matches("^\\+([-]+\\+)+$") ) {
throw new RuntimeException("ERROR 2: Improper line format. Line = " + test);
}
if ( size == 0 ) {
int firstPlus = test.indexOf("+");
int secondPlus = test.indexOf("+", 1);
size = secondPlus - firstPlus;
}
if ( ((test.length()-1) % size) != 0 ) {
throw new RuntimeException("ERROR 3: Improper line format. Line = " + test);
}
for ( int j = 0 ; j < test.length()-1 ; j += size ) {
if ( test.charAt(j) != '+' ) {
throw new RuntimeException("ERROR 4: Improper line format. Line = " + test);
}
for ( int k = j+1 ; k < j + size ; k++ ) {
if ( test.charAt(k) != '-' ) {
throw new RuntimeException("ERROR 5: Improper line format. Line = " + test);
}
}
}
}
else {
if ( ! test.matches("^\\|(\\s*[A-Za-z]+\\s*\\|)+$") ) {
throw new RuntimeException("ERROR 6: Improper line format. Line = " + test);
}
for ( int j = 0 ; j < test.length()-1 ; j += size ) {
for ( int k = j+1 ; k < j + size ; k++ ) {
if ( test.charAt(k) == '|' ) {
throw new RuntimeException("ERROR 7: Improper line format. Line = " + test);
}
}
}
}
}
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | from difflib import ndiff
def levenshtein(str1, str2):
result = ""
pos, removed = 0, 0
for x in ndiff(str1, str2):
if pos<len(str1) and str1[pos] == x[2]:
pos += 1
result += x[2]
if x[0] == "-":
removed += 1
continue
else:
if removed > 0:
removed -=1
else:
result += "-"
print(result)
levenshtein("place","palace")
levenshtein("rosettacode","raisethysword")
| public class LevenshteinAlignment {
public static String[] alignment(String a, String b) {
a = a.toLowerCase();
b = b.toLowerCase();
int[][] costs = new int[a.length()+1][b.length()+1];
for (int j = 0; j <= b.length(); j++)
costs[0][j] = j;
for (int i = 1; i <= a.length(); i++) {
costs[i][0] = i;
for (int j = 1; j <= b.length(); j++) {
costs[i][j] = Math.min(1 + Math.min(costs[i-1][j], costs[i][j-1]), a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1);
}
}
StringBuilder aPathRev = new StringBuilder();
StringBuilder bPathRev = new StringBuilder();
for (int i = a.length(), j = b.length(); i != 0 && j != 0; ) {
if (costs[i][j] == (a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1)) {
aPathRev.append(a.charAt(--i));
bPathRev.append(b.charAt(--j));
} else if (costs[i][j] == 1 + costs[i-1][j]) {
aPathRev.append(a.charAt(--i));
bPathRev.append('-');
} else if (costs[i][j] == 1 + costs[i][j-1]) {
aPathRev.append('-');
bPathRev.append(b.charAt(--j));
}
}
return new String[]{aPathRev.reverse().toString(), bPathRev.reverse().toString()};
}
public static void main(String[] args) {
String[] result = alignment("rosettacode", "raisethysword");
System.out.println(result[0]);
System.out.println(result[1]);
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | try:
from itertools import zip_longest as izip_longest
except:
from itertools import izip_longest
def fringe(tree):
for node1 in tree:
if isinstance(node1, tuple):
for node2 in fringe(node1):
yield node2
else:
yield node1
def same_fringe(tree1, tree2):
return all(node1 == node2 for node1, node2 in
izip_longest(fringe(tree1), fringe(tree2)))
if __name__ == '__main__':
a = 1, 2, 3, 4, 5, 6, 7, 8
b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))
c = (((1, 2), 3), 4), 5, 6, 7, 8
x = 1, 2, 3, 4, 5, 6, 7, 8, 9
y = 0, 2, 3, 4, 5, 6, 7, 8
z = 1, 2, (4, 3), 5, 6, 7, 8
assert same_fringe(a, a)
assert same_fringe(a, b)
assert same_fringe(a, c)
assert not same_fringe(a, x)
assert not same_fringe(a, y)
assert not same_fringe(a, z)
| import java.util.*;
class SameFringe
{
public interface Node<T extends Comparable<? super T>>
{
Node<T> getLeft();
Node<T> getRight();
boolean isLeaf();
T getData();
}
public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>
{
private final T data;
public SimpleNode<T> left;
public SimpleNode<T> right;
public SimpleNode(T data)
{ this(data, null, null); }
public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)
{
this.data = data;
this.left = left;
this.right = right;
}
public Node<T> getLeft()
{ return left; }
public Node<T> getRight()
{ return right; }
public boolean isLeaf()
{ return ((left == null) && (right == null)); }
public T getData()
{ return data; }
public SimpleNode<T> addToTree(T data)
{
int cmp = data.compareTo(this.data);
if (cmp == 0)
throw new IllegalArgumentException("Same data!");
if (cmp < 0)
{
if (left == null)
return (left = new SimpleNode<T>(data));
return left.addToTree(data);
}
if (right == null)
return (right = new SimpleNode<T>(data));
return right.addToTree(data);
}
}
public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)
{
Stack<Node<T>> stack1 = new Stack<Node<T>>();
Stack<Node<T>> stack2 = new Stack<Node<T>>();
stack1.push(node1);
stack2.push(node2);
while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))
if (!node1.getData().equals(node2.getData()))
return false;
return (node1 == null) && (node2 == null);
}
private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)
{
while (!stack.isEmpty())
{
Node<T> node = stack.pop();
if (node.isLeaf())
return node;
Node<T> rightNode = node.getRight();
if (rightNode != null)
stack.push(rightNode);
Node<T> leftNode = node.getLeft();
if (leftNode != null)
stack.push(leftNode);
}
return null;
}
public static void main(String[] args)
{
SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));
SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));
SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));
System.out.print("Leaves for set 1: ");
simpleWalk(headNode1);
System.out.println();
System.out.print("Leaves for set 2: ");
simpleWalk(headNode2);
System.out.println();
System.out.print("Leaves for set 3: ");
simpleWalk(headNode3);
System.out.println();
System.out.println("areLeavesSame(1, 2)? " + areLeavesSame(headNode1, headNode2));
System.out.println("areLeavesSame(2, 3)? " + areLeavesSame(headNode2, headNode3));
}
public static void simpleWalk(Node<Integer> node)
{
if (node.isLeaf())
System.out.print(node.getData() + " ");
else
{
Node<Integer> left = node.getLeft();
if (left != null)
simpleWalk(left);
Node<Integer> right = node.getRight();
if (right != null)
simpleWalk(right);
}
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | try:
from itertools import zip_longest as izip_longest
except:
from itertools import izip_longest
def fringe(tree):
for node1 in tree:
if isinstance(node1, tuple):
for node2 in fringe(node1):
yield node2
else:
yield node1
def same_fringe(tree1, tree2):
return all(node1 == node2 for node1, node2 in
izip_longest(fringe(tree1), fringe(tree2)))
if __name__ == '__main__':
a = 1, 2, 3, 4, 5, 6, 7, 8
b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))
c = (((1, 2), 3), 4), 5, 6, 7, 8
x = 1, 2, 3, 4, 5, 6, 7, 8, 9
y = 0, 2, 3, 4, 5, 6, 7, 8
z = 1, 2, (4, 3), 5, 6, 7, 8
assert same_fringe(a, a)
assert same_fringe(a, b)
assert same_fringe(a, c)
assert not same_fringe(a, x)
assert not same_fringe(a, y)
assert not same_fringe(a, z)
| import java.util.*;
class SameFringe
{
public interface Node<T extends Comparable<? super T>>
{
Node<T> getLeft();
Node<T> getRight();
boolean isLeaf();
T getData();
}
public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>
{
private final T data;
public SimpleNode<T> left;
public SimpleNode<T> right;
public SimpleNode(T data)
{ this(data, null, null); }
public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)
{
this.data = data;
this.left = left;
this.right = right;
}
public Node<T> getLeft()
{ return left; }
public Node<T> getRight()
{ return right; }
public boolean isLeaf()
{ return ((left == null) && (right == null)); }
public T getData()
{ return data; }
public SimpleNode<T> addToTree(T data)
{
int cmp = data.compareTo(this.data);
if (cmp == 0)
throw new IllegalArgumentException("Same data!");
if (cmp < 0)
{
if (left == null)
return (left = new SimpleNode<T>(data));
return left.addToTree(data);
}
if (right == null)
return (right = new SimpleNode<T>(data));
return right.addToTree(data);
}
}
public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)
{
Stack<Node<T>> stack1 = new Stack<Node<T>>();
Stack<Node<T>> stack2 = new Stack<Node<T>>();
stack1.push(node1);
stack2.push(node2);
while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))
if (!node1.getData().equals(node2.getData()))
return false;
return (node1 == null) && (node2 == null);
}
private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)
{
while (!stack.isEmpty())
{
Node<T> node = stack.pop();
if (node.isLeaf())
return node;
Node<T> rightNode = node.getRight();
if (rightNode != null)
stack.push(rightNode);
Node<T> leftNode = node.getLeft();
if (leftNode != null)
stack.push(leftNode);
}
return null;
}
public static void main(String[] args)
{
SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));
SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));
SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));
System.out.print("Leaves for set 1: ");
simpleWalk(headNode1);
System.out.println();
System.out.print("Leaves for set 2: ");
simpleWalk(headNode2);
System.out.println();
System.out.print("Leaves for set 3: ");
simpleWalk(headNode3);
System.out.println();
System.out.println("areLeavesSame(1, 2)? " + areLeavesSame(headNode1, headNode2));
System.out.println("areLeavesSame(2, 3)? " + areLeavesSame(headNode2, headNode3));
}
public static void simpleWalk(Node<Integer> node)
{
if (node.isLeaf())
System.out.print(node.getData() + " ");
else
{
Node<Integer> left = node.getLeft();
if (left != null)
simpleWalk(left);
Node<Integer> right = node.getRight();
if (right != null)
simpleWalk(right);
}
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | import autopy
autopy.key.type_string("Hello, world!")
autopy.key.type_string("Hello, world!", wpm=60)
autopy.key.tap(autopy.key.Code.RETURN)
autopy.key.tap(autopy.key.Code.F1)
autopy.key.tap(autopy.key.Code.LEFT_ARROW)
| import java.awt.Robot
public static void type(String str){
Robot robot = new Robot();
for(char ch:str.toCharArray()){
if(Character.isUpperCase(ch)){
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress((int)ch);
robot.keyRelease((int)ch);
robot.keyRelease(KeyEvent.VK_SHIFT);
}else{
char upCh = Character.toUpperCase(ch);
robot.keyPress((int)upCh);
robot.keyRelease((int)upCh);
}
}
}
|
Please provide an equivalent version of this Python code in Java. | from itertools import combinations, product, count
from functools import lru_cache, reduce
_bbullet, _wbullet = '\u2022\u25E6'
_or = set.__or__
def place(m, n):
"Place m black and white queens, peacefully, on an n-by-n board"
board = set(product(range(n), repeat=2))
placements = {frozenset(c) for c in combinations(board, m)}
for blacks in placements:
black_attacks = reduce(_or,
(queen_attacks_from(pos, n) for pos in blacks),
set())
for whites in {frozenset(c)
for c in combinations(board - black_attacks, m)}:
if not black_attacks & whites:
return blacks, whites
return set(), set()
@lru_cache(maxsize=None)
def queen_attacks_from(pos, n):
x0, y0 = pos
a = set([pos])
a.update((x, y0) for x in range(n))
a.update((x0, y) for y in range(n))
for x1 in range(n):
y1 = y0 -x0 +x1
if 0 <= y1 < n:
a.add((x1, y1))
y1 = y0 +x0 -x1
if 0 <= y1 < n:
a.add((x1, y1))
return a
def pboard(black_white, n):
"Print board"
if black_white is None:
blk, wht = set(), set()
else:
blk, wht = black_white
print(f"
f"on a {n}-by-{n} board:", end='')
for x, y in product(range(n), repeat=2):
if y == 0:
print()
xy = (x, y)
ch = ('?' if xy in blk and xy in wht
else 'B' if xy in blk
else 'W' if xy in wht
else _bbullet if (x + y)%2 else _wbullet)
print('%s' % ch, end='')
print()
if __name__ == '__main__':
n=2
for n in range(2, 7):
print()
for m in count(1):
ans = place(m, n)
if ans[0]:
pboard(ans, n)
else:
print (f"
break
print('\n')
m, n = 5, 7
ans = place(m, n)
pboard(ans, n)
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Peaceful {
enum Piece {
Empty,
Black,
White,
}
public static class Position {
public int x, y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Position) {
Position pos = (Position) obj;
return pos.x == x && pos.y == y;
}
return false;
}
}
private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {
if (m == 0) {
return true;
}
boolean placingBlack = true;
for (int i = 0; i < n; ++i) {
inner:
for (int j = 0; j < n; ++j) {
Position pos = new Position(i, j);
for (Position queen : pBlackQueens) {
if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {
continue inner;
}
}
for (Position queen : pWhiteQueens) {
if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {
continue inner;
}
}
if (placingBlack) {
pBlackQueens.add(pos);
placingBlack = false;
} else {
pWhiteQueens.add(pos);
if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {
return true;
}
pBlackQueens.remove(pBlackQueens.size() - 1);
pWhiteQueens.remove(pWhiteQueens.size() - 1);
placingBlack = true;
}
}
}
if (!placingBlack) {
pBlackQueens.remove(pBlackQueens.size() - 1);
}
return false;
}
private static boolean isAttacking(Position queen, Position pos) {
return queen.x == pos.x
|| queen.y == pos.y
|| Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);
}
private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {
Piece[] board = new Piece[n * n];
Arrays.fill(board, Piece.Empty);
for (Position queen : blackQueens) {
board[queen.x + n * queen.y] = Piece.Black;
}
for (Position queen : whiteQueens) {
board[queen.x + n * queen.y] = Piece.White;
}
for (int i = 0; i < board.length; ++i) {
if ((i != 0) && i % n == 0) {
System.out.println();
}
Piece b = board[i];
if (b == Piece.Black) {
System.out.print("B ");
} else if (b == Piece.White) {
System.out.print("W ");
} else {
int j = i / n;
int k = i - j * n;
if (j % 2 == k % 2) {
System.out.print("• ");
} else {
System.out.print("◦ ");
}
}
}
System.out.println('\n');
}
public static void main(String[] args) {
List<Position> nms = List.of(
new Position(2, 1),
new Position(3, 1),
new Position(3, 2),
new Position(4, 1),
new Position(4, 2),
new Position(4, 3),
new Position(5, 1),
new Position(5, 2),
new Position(5, 3),
new Position(5, 4),
new Position(5, 5),
new Position(6, 1),
new Position(6, 2),
new Position(6, 3),
new Position(6, 4),
new Position(6, 5),
new Position(6, 6),
new Position(7, 1),
new Position(7, 2),
new Position(7, 3),
new Position(7, 4),
new Position(7, 5),
new Position(7, 6),
new Position(7, 7)
);
for (Position nm : nms) {
int m = nm.y;
int n = nm.x;
System.out.printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n);
List<Position> blackQueens = new ArrayList<>();
List<Position> whiteQueens = new ArrayList<>();
if (place(m, n, blackQueens, whiteQueens)) {
printBoard(n, blackQueens, whiteQueens);
} else {
System.out.println("No solution exists.\n");
}
}
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | from itertools import combinations, product, count
from functools import lru_cache, reduce
_bbullet, _wbullet = '\u2022\u25E6'
_or = set.__or__
def place(m, n):
"Place m black and white queens, peacefully, on an n-by-n board"
board = set(product(range(n), repeat=2))
placements = {frozenset(c) for c in combinations(board, m)}
for blacks in placements:
black_attacks = reduce(_or,
(queen_attacks_from(pos, n) for pos in blacks),
set())
for whites in {frozenset(c)
for c in combinations(board - black_attacks, m)}:
if not black_attacks & whites:
return blacks, whites
return set(), set()
@lru_cache(maxsize=None)
def queen_attacks_from(pos, n):
x0, y0 = pos
a = set([pos])
a.update((x, y0) for x in range(n))
a.update((x0, y) for y in range(n))
for x1 in range(n):
y1 = y0 -x0 +x1
if 0 <= y1 < n:
a.add((x1, y1))
y1 = y0 +x0 -x1
if 0 <= y1 < n:
a.add((x1, y1))
return a
def pboard(black_white, n):
"Print board"
if black_white is None:
blk, wht = set(), set()
else:
blk, wht = black_white
print(f"
f"on a {n}-by-{n} board:", end='')
for x, y in product(range(n), repeat=2):
if y == 0:
print()
xy = (x, y)
ch = ('?' if xy in blk and xy in wht
else 'B' if xy in blk
else 'W' if xy in wht
else _bbullet if (x + y)%2 else _wbullet)
print('%s' % ch, end='')
print()
if __name__ == '__main__':
n=2
for n in range(2, 7):
print()
for m in count(1):
ans = place(m, n)
if ans[0]:
pboard(ans, n)
else:
print (f"
break
print('\n')
m, n = 5, 7
ans = place(m, n)
pboard(ans, n)
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Peaceful {
enum Piece {
Empty,
Black,
White,
}
public static class Position {
public int x, y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Position) {
Position pos = (Position) obj;
return pos.x == x && pos.y == y;
}
return false;
}
}
private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {
if (m == 0) {
return true;
}
boolean placingBlack = true;
for (int i = 0; i < n; ++i) {
inner:
for (int j = 0; j < n; ++j) {
Position pos = new Position(i, j);
for (Position queen : pBlackQueens) {
if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) {
continue inner;
}
}
for (Position queen : pWhiteQueens) {
if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) {
continue inner;
}
}
if (placingBlack) {
pBlackQueens.add(pos);
placingBlack = false;
} else {
pWhiteQueens.add(pos);
if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {
return true;
}
pBlackQueens.remove(pBlackQueens.size() - 1);
pWhiteQueens.remove(pWhiteQueens.size() - 1);
placingBlack = true;
}
}
}
if (!placingBlack) {
pBlackQueens.remove(pBlackQueens.size() - 1);
}
return false;
}
private static boolean isAttacking(Position queen, Position pos) {
return queen.x == pos.x
|| queen.y == pos.y
|| Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y);
}
private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {
Piece[] board = new Piece[n * n];
Arrays.fill(board, Piece.Empty);
for (Position queen : blackQueens) {
board[queen.x + n * queen.y] = Piece.Black;
}
for (Position queen : whiteQueens) {
board[queen.x + n * queen.y] = Piece.White;
}
for (int i = 0; i < board.length; ++i) {
if ((i != 0) && i % n == 0) {
System.out.println();
}
Piece b = board[i];
if (b == Piece.Black) {
System.out.print("B ");
} else if (b == Piece.White) {
System.out.print("W ");
} else {
int j = i / n;
int k = i - j * n;
if (j % 2 == k % 2) {
System.out.print("• ");
} else {
System.out.print("◦ ");
}
}
}
System.out.println('\n');
}
public static void main(String[] args) {
List<Position> nms = List.of(
new Position(2, 1),
new Position(3, 1),
new Position(3, 2),
new Position(4, 1),
new Position(4, 2),
new Position(4, 3),
new Position(5, 1),
new Position(5, 2),
new Position(5, 3),
new Position(5, 4),
new Position(5, 5),
new Position(6, 1),
new Position(6, 2),
new Position(6, 3),
new Position(6, 4),
new Position(6, 5),
new Position(6, 6),
new Position(7, 1),
new Position(7, 2),
new Position(7, 3),
new Position(7, 4),
new Position(7, 5),
new Position(7, 6),
new Position(7, 7)
);
for (Position nm : nms) {
int m = nm.y;
int n = nm.x;
System.out.printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n);
List<Position> blackQueens = new ArrayList<>();
List<Position> whiteQueens = new ArrayList<>();
if (place(m, n, blackQueens, whiteQueens)) {
printBoard(n, blackQueens, whiteQueens);
} else {
System.out.println("No solution exists.\n");
}
}
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | from __future__ import print_function
from string import ascii_lowercase
SYMBOLTABLE = list(ascii_lowercase)
def move2front_encode(strng, symboltable):
sequence, pad = [], symboltable[::]
for char in strng:
indx = pad.index(char)
sequence.append(indx)
pad = [pad.pop(indx)] + pad
return sequence
def move2front_decode(sequence, symboltable):
chars, pad = [], symboltable[::]
for indx in sequence:
char = pad[indx]
chars.append(char)
pad = [pad.pop(indx)] + pad
return ''.join(chars)
if __name__ == '__main__':
for s in ['broood', 'bananaaa', 'hiphophiphop']:
encode = move2front_encode(s, SYMBOLTABLE)
print('%14r encodes to %r' % (s, encode), end=', ')
decode = move2front_decode(encode, SYMBOLTABLE)
print('which decodes back to %r' % decode)
assert s == decode, 'Whoops!'
| import java.util.LinkedList;
import java.util.List;
public class MTF{
public static List<Integer> encode(String msg, String symTable){
List<Integer> output = new LinkedList<Integer>();
StringBuilder s = new StringBuilder(symTable);
for(char c : msg.toCharArray()){
int idx = s.indexOf("" + c);
output.add(idx);
s = s.deleteCharAt(idx).insert(0, c);
}
return output;
}
public static String decode(List<Integer> idxs, String symTable){
StringBuilder output = new StringBuilder();
StringBuilder s = new StringBuilder(symTable);
for(int idx : idxs){
char c = s.charAt(idx);
output = output.append(c);
s = s.deleteCharAt(idx).insert(0, c);
}
return output.toString();
}
private static void test(String toEncode, String symTable){
List<Integer> encoded = encode(toEncode, symTable);
System.out.println(toEncode + ": " + encoded);
String decoded = decode(encoded, symTable);
System.out.println((toEncode.equals(decoded) ? "" : "in") + "correctly decoded to " + decoded);
}
public static void main(String[] args){
String symTable = "abcdefghijklmnopqrstuvwxyz";
test("broood", symTable);
test("bananaaa", symTable);
test("hiphophiphop", symTable);
}
}
|
Write the same code in Java as shown below in Python. | from __future__ import print_function
from string import ascii_lowercase
SYMBOLTABLE = list(ascii_lowercase)
def move2front_encode(strng, symboltable):
sequence, pad = [], symboltable[::]
for char in strng:
indx = pad.index(char)
sequence.append(indx)
pad = [pad.pop(indx)] + pad
return sequence
def move2front_decode(sequence, symboltable):
chars, pad = [], symboltable[::]
for indx in sequence:
char = pad[indx]
chars.append(char)
pad = [pad.pop(indx)] + pad
return ''.join(chars)
if __name__ == '__main__':
for s in ['broood', 'bananaaa', 'hiphophiphop']:
encode = move2front_encode(s, SYMBOLTABLE)
print('%14r encodes to %r' % (s, encode), end=', ')
decode = move2front_decode(encode, SYMBOLTABLE)
print('which decodes back to %r' % decode)
assert s == decode, 'Whoops!'
| import java.util.LinkedList;
import java.util.List;
public class MTF{
public static List<Integer> encode(String msg, String symTable){
List<Integer> output = new LinkedList<Integer>();
StringBuilder s = new StringBuilder(symTable);
for(char c : msg.toCharArray()){
int idx = s.indexOf("" + c);
output.add(idx);
s = s.deleteCharAt(idx).insert(0, c);
}
return output;
}
public static String decode(List<Integer> idxs, String symTable){
StringBuilder output = new StringBuilder();
StringBuilder s = new StringBuilder(symTable);
for(int idx : idxs){
char c = s.charAt(idx);
output = output.append(c);
s = s.deleteCharAt(idx).insert(0, c);
}
return output.toString();
}
private static void test(String toEncode, String symTable){
List<Integer> encoded = encode(toEncode, symTable);
System.out.println(toEncode + ": " + encoded);
String decoded = decode(encoded, symTable);
System.out.println((toEncode.equals(decoded) ? "" : "in") + "correctly decoded to " + decoded);
}
public static void main(String[] args){
String symTable = "abcdefghijklmnopqrstuvwxyz";
test("broood", symTable);
test("bananaaa", symTable);
test("hiphophiphop", symTable);
}
}
|
Write a version of this Python function in Java with identical behavior. | Import-Module ActiveDirectory
$searchData = "user name"
$searchBase = "DC=example,DC=com"
get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase
| import java.io.IOException;
import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
public class LdapSearchDemo {
public static void main(String[] args) throws IOException, LdapException, CursorException {
new LdapSearchDemo().demonstrateSearch();
}
private void demonstrateSearch() throws IOException, LdapException, CursorException {
try (LdapConnection conn = new LdapNetworkConnection("localhost", 11389)) {
conn.bind("uid=admin,ou=system", "********");
search(conn, "*mil*");
conn.unBind();
}
}
private void search(LdapConnection connection, String uid) throws LdapException, CursorException {
String baseDn = "ou=users,o=mojo";
String filter = "(&(objectClass=person)(&(uid=" + uid + ")))";
SearchScope scope = SearchScope.SUBTREE;
String[] attributes = {"dn", "cn", "sn", "uid"};
int ksearch = 0;
EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);
while (cursor.next()) {
ksearch++;
Entry entry = cursor.get();
System.out.printf("Search entry %d = %s%n", ksearch, entry);
}
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | from numpy import *
A = matrix([[3, 0], [4, 5]])
U, Sigma, VT = linalg.svd(A)
print(U)
print(Sigma)
print(VT)
| import Jama.Matrix;
public class SingularValueDecomposition {
public static void main(String[] args) {
double[][] matrixArray = {{3, 0}, {4, 5}};
var matrix = new Matrix(matrixArray);
var svd = matrix.svd();
svd.getU().print(0, 10);
svd.getS().print(0, 10);
svd.getV().print(0, 10);
}
}
|
Translate the given Python code snippet into Java without altering its behavior. | >>> def isint(f):
return complex(f).imag == 0 and complex(f).real.is_integer()
>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]
[True, True, True, False, False, False]
>>>
...
>>> isint(25.000000)
True
>>> isint(24.999999)
False
>>> isint(25.000100)
False
>>> isint(-2.1e120)
True
>>> isint(-5e-2)
False
>>> isint(float('nan'))
False
>>> isint(float('inf'))
False
>>> isint(5.0+0.0j)
True
>>> isint(5-5j)
False
| import java.math.BigDecimal;
import java.util.List;
public class TestIntegerness {
private static boolean isLong(double d) {
return isLong(d, 0.0);
}
private static boolean isLong(double d, double tolerance) {
return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static boolean isBigInteger(BigDecimal bd) {
try {
bd.toBigIntegerExact();
return true;
} catch (ArithmeticException ex) {
return false;
}
}
private static class Rational {
long num;
long denom;
Rational(int num, int denom) {
this.num = num;
this.denom = denom;
}
boolean isLong() {
return num % denom == 0;
}
@Override
public String toString() {
return String.format("%s/%s", num, denom);
}
}
private static class Complex {
double real;
double imag;
Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
boolean isLong() {
return TestIntegerness.isLong(real) && imag == 0.0;
}
@Override
public String toString() {
if (imag >= 0.0) {
return String.format("%s + %si", real, imag);
}
return String.format("%s - %si", real, imag);
}
}
public static void main(String[] args) {
List<Double> da = List.of(25.000000, 24.999999, 25.000100);
for (Double d : da) {
boolean exact = isLong(d);
System.out.printf("%.6f is %s integer%n", d, exact ? "an" : "not an");
}
System.out.println();
double tolerance = 0.00001;
System.out.printf("With a tolerance of %.5f:%n", tolerance);
for (Double d : da) {
boolean fuzzy = isLong(d, tolerance);
System.out.printf("%.6f is %s integer%n", d, fuzzy ? "an" : "not an");
}
System.out.println();
List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY);
for (Double f : fa) {
boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString()));
System.out.printf("%s is %s integer%n", f, exact ? "an" : "not an");
}
System.out.println();
List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0));
for (Complex c : ca) {
boolean exact = c.isLong();
System.out.printf("%s is %s integer%n", c, exact ? "an" : "not an");
}
System.out.println();
List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2));
for (Rational r : ra) {
boolean exact = r.isLong();
System.out.printf("%s is %s integer%n", r, exact ? "an" : "not an");
}
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. | import os
exit_code = os.system('ls')
output = os.popen('ls').read()
| import java.util.Scanner;
import java.io.*;
public class Program {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("cmd /C dir");
Scanner sc = new Scanner(p.getInputStream());
while (sc.hasNext()) System.out.println(sc.nextLine());
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
|
Please provide an equivalent version of this Python code in Java. |
from __future__ import print_function
import lxml
from lxml import etree
if __name__=="__main__":
parser = etree.XMLParser(dtd_validation=True)
schema_root = etree.XML()
schema = etree.XMLSchema(schema_root)
parser = etree.XMLParser(schema = schema)
try:
root = etree.fromstring("<a>5</a>", parser)
print ("Finished validating good xml")
except lxml.etree.XMLSyntaxError as err:
print (err)
parser = etree.XMLParser(schema = schema)
try:
root = etree.fromstring("<a>5<b>foobar</b></a>", parser)
except lxml.etree.XMLSyntaxError as err:
print (err)
| import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.ws.Holder;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class XmlValidation {
public static void main(String... args) throws MalformedURLException {
URL schemaLocation = new URL("http:
URL documentLocation = new URL("http:
if (validate(schemaLocation, documentLocation)) {
System.out.println("document is valid");
} else {
System.out.println("document is invalid");
}
}
public static boolean minimalValidate(URL schemaLocation, URL documentLocation) {
SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
try {
Validator validator = factory.newSchema(schemaLocation).newValidator();
validator.validate(new StreamSource(documentLocation.toString()));
return true;
} catch (Exception e) {
return false;
}
}
public static boolean validate(URL schemaLocation, URL documentLocation) {
SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
final Holder<Boolean> valid = new Holder<>(true);
try {
Validator validator = factory.newSchema(schemaLocation).newValidator();
validator.setErrorHandler(new ErrorHandler(){
@Override
public void warning(SAXParseException exception) {
System.out.println("warning: " + exception.getMessage());
}
@Override
public void error(SAXParseException exception) {
System.out.println("error: " + exception.getMessage());
valid.value = false;
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
System.out.println("fatal error: " + exception.getMessage());
throw exception;
}});
validator.validate(new StreamSource(documentLocation.toString()));
return valid.value;
} catch (SAXException e) {
return false;
} catch (Exception e) {
System.err.println(e);
return false;
}
}
}
|
Write the same code in Java as shown below in Python. | def longest_increasing_subsequence(X):
N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
lo = 1
hi = L
while lo <= hi:
mid = (lo+hi)//2
if (X[M[mid]] < X[i]):
lo = mid+1
else:
hi = mid-1
newL = lo
P[i] = M[newL-1]
M[newL] = i
if (newL > L):
L = newL
S = []
k = M[L]
for i in range(L-1, -1, -1):
S.append(X[k])
k = P[k]
return S[::-1]
if __name__ == '__main__':
for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:
print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))
| import java.util.*;
public class LIS {
public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {
List<Node<E>> pileTops = new ArrayList<Node<E>>();
for (E x : n) {
Node<E> node = new Node<E>();
node.value = x;
int i = Collections.binarySearch(pileTops, node);
if (i < 0) i = ~i;
if (i != 0)
node.pointer = pileTops.get(i-1);
if (i != pileTops.size())
pileTops.set(i, node);
else
pileTops.add(node);
}
List<E> result = new ArrayList<E>();
for (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);
node != null; node = node.pointer)
result.add(node.value);
Collections.reverse(result);
return result;
}
private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {
public E value;
public Node<E> pointer;
public int compareTo(Node<E> y) { return value.compareTo(y.value); }
}
public static void main(String[] args) {
List<Integer> d = Arrays.asList(3,2,6,4,5,1);
System.out.printf("an L.I.S. of %s is %s\n", d, lis(d));
d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);
System.out.printf("an L.I.S. of %s is %s\n", d, lis(d));
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | import sys, math, collections
Sphere = collections.namedtuple("Sphere", "cx cy cz r")
V3 = collections.namedtuple("V3", "x y z")
def normalize((x, y, z)):
len = math.sqrt(x**2 + y**2 + z**2)
return V3(x / len, y / len, z / len)
def dot(v1, v2):
d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z
return -d if d < 0 else 0.0
def hit_sphere(sph, x0, y0):
x = x0 - sph.cx
y = y0 - sph.cy
zsq = sph.r ** 2 - (x ** 2 + y ** 2)
if zsq < 0:
return (False, 0, 0)
szsq = math.sqrt(zsq)
return (True, sph.cz - szsq, sph.cz + szsq)
def draw_sphere(k, ambient, light):
shades = ".:!*oe&
pos = Sphere(20.0, 20.0, 0.0, 20.0)
neg = Sphere(1.0, 1.0, -6.0, 20.0)
for i in xrange(int(math.floor(pos.cy - pos.r)),
int(math.ceil(pos.cy + pos.r) + 1)):
y = i + 0.5
for j in xrange(int(math.floor(pos.cx - 2 * pos.r)),
int(math.ceil(pos.cx + 2 * pos.r) + 1)):
x = (j - pos.cx) / 2.0 + 0.5 + pos.cx
(h, zb1, zb2) = hit_sphere(pos, x, y)
if not h:
hit_result = 0
else:
(h, zs1, zs2) = hit_sphere(neg, x, y)
if not h:
hit_result = 1
elif zs1 > zb1:
hit_result = 1
elif zs2 > zb2:
hit_result = 0
elif zs2 > zb1:
hit_result = 2
else:
hit_result = 1
if hit_result == 0:
sys.stdout.write(' ')
continue
elif hit_result == 1:
vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz)
elif hit_result == 2:
vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2)
vec = normalize(vec)
b = dot(light, vec) ** k + ambient
intensity = int((1 - b) * len(shades))
intensity = min(len(shades), max(0, intensity))
sys.stdout.write(shades[intensity])
print
light = normalize(V3(-50, 30, 50))
draw_sphere(2, 0.5, light)
| import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Point3D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.shape.MeshView;
import javafx.scene.shape.TriangleMesh;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
public class DeathStar extends Application {
private static final int DIVISION = 200;
float radius = 300;
@Override
public void start(Stage primaryStage) throws Exception {
Point3D otherSphere = new Point3D(-radius, 0, -radius * 1.5);
final TriangleMesh triangleMesh = createMesh(DIVISION, radius, otherSphere);
MeshView a = new MeshView(triangleMesh);
a.setTranslateY(radius);
a.setTranslateX(radius);
a.setRotationAxis(Rotate.Y_AXIS);
Scene scene = new Scene(new Group(a));
primaryStage.setScene(scene);
primaryStage.show();
}
static TriangleMesh createMesh(final int division, final float radius, final Point3D centerOtherSphere) {
Rotate rotate = new Rotate(180, centerOtherSphere);
final int div2 = division / 2;
final int nPoints = division * (div2 - 1) + 2;
final int nTPoints = (division + 1) * (div2 - 1) + division * 2;
final int nFaces = division * (div2 - 2) * 2 + division * 2;
final float rDiv = 1.f / division;
float points[] = new float[nPoints * 3];
float tPoints[] = new float[nTPoints * 2];
int faces[] = new int[nFaces * 6];
int pPos = 0, tPos = 0;
for (int y = 0; y < div2 - 1; ++y) {
float va = rDiv * (y + 1 - div2 / 2) * 2 * (float) Math.PI;
float sin_va = (float) Math.sin(va);
float cos_va = (float) Math.cos(va);
float ty = 0.5f + sin_va * 0.5f;
for (int i = 0; i < division; ++i) {
double a = rDiv * i * 2 * (float) Math.PI;
float hSin = (float) Math.sin(a);
float hCos = (float) Math.cos(a);
points[pPos + 0] = hSin * cos_va * radius;
points[pPos + 2] = hCos * cos_va * radius;
points[pPos + 1] = sin_va * radius;
final Point3D point3D = new Point3D(points[pPos + 0], points[pPos + 1], points[pPos + 2]);
double distance = centerOtherSphere.distance(point3D);
if (distance <= radius) {
Point3D subtract = centerOtherSphere.subtract(point3D);
Point3D transform = rotate.transform(subtract);
points[pPos + 0] = (float) transform.getX();
points[pPos + 1] = (float) transform.getY();
points[pPos + 2] = (float) transform.getZ();
}
tPoints[tPos + 0] = 1 - rDiv * i;
tPoints[tPos + 1] = ty;
pPos += 3;
tPos += 2;
}
tPoints[tPos + 0] = 0;
tPoints[tPos + 1] = ty;
tPos += 2;
}
points[pPos + 0] = 0;
points[pPos + 1] = -radius;
points[pPos + 2] = 0;
points[pPos + 3] = 0;
points[pPos + 4] = radius;
points[pPos + 5] = 0;
pPos += 6;
int pS = (div2 - 1) * division;
float textureDelta = 1.f / 256;
for (int i = 0; i < division; ++i) {
tPoints[tPos + 0] = rDiv * (0.5f + i);
tPoints[tPos + 1] = textureDelta;
tPos += 2;
}
for (int i = 0; i < division; ++i) {
tPoints[tPos + 0] = rDiv * (0.5f + i);
tPoints[tPos + 1] = 1 - textureDelta;
tPos += 2;
}
int fIndex = 0;
for (int y = 0; y < div2 - 2; ++y) {
for (int x = 0; x < division; ++x) {
int p0 = y * division + x;
int p1 = p0 + 1;
int p2 = p0 + division;
int p3 = p1 + division;
int t0 = p0 + y;
int t1 = t0 + 1;
int t2 = t0 + division + 1;
int t3 = t1 + division + 1;
faces[fIndex + 0] = p0;
faces[fIndex + 1] = t0;
faces[fIndex + 2] = p1 % division == 0 ? p1 - division : p1;
faces[fIndex + 3] = t1;
faces[fIndex + 4] = p2;
faces[fIndex + 5] = t2;
fIndex += 6;
faces[fIndex + 0] = p3 % division == 0 ? p3 - division : p3;
faces[fIndex + 1] = t3;
faces[fIndex + 2] = p2;
faces[fIndex + 3] = t2;
faces[fIndex + 4] = p1 % division == 0 ? p1 - division : p1;
faces[fIndex + 5] = t1;
fIndex += 6;
}
}
int p0 = pS;
int tB = (div2 - 1) * (division + 1);
for (int x = 0; x < division; ++x) {
int p2 = x, p1 = x + 1, t0 = tB + x;
faces[fIndex + 0] = p0;
faces[fIndex + 1] = t0;
faces[fIndex + 2] = p1 == division ? 0 : p1;
faces[fIndex + 3] = p1;
faces[fIndex + 4] = p2;
faces[fIndex + 5] = p2;
fIndex += 6;
}
p0 = p0 + 1;
tB = tB + division;
int pB = (div2 - 2) * division;
for (int x = 0; x < division; ++x) {
int p1 = pB + x, p2 = pB + x + 1, t0 = tB + x;
int t1 = (div2 - 2) * (division + 1) + x, t2 = t1 + 1;
faces[fIndex + 0] = p0;
faces[fIndex + 1] = t0;
faces[fIndex + 2] = p1;
faces[fIndex + 3] = t1;
faces[fIndex + 4] = p2 % division == 0 ? p2 - division : p2;
faces[fIndex + 5] = t2;
fIndex += 6;
}
TriangleMesh m = new TriangleMesh();
m.getPoints().setAll(points);
m.getTexCoords().setAll(tPoints);
m.getFaces().setAll(faces);
return m;
}
public static void main(String[] args) {
launch(args);
}
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. | from __future__ import print_function
def lgen(even=False, nmax=1000000):
start = 2 if even else 1
n, lst = 1, list(range(start, nmax + 1, 2))
lenlst = len(lst)
yield lst[0]
while n < lenlst and lst[n] < lenlst:
yield lst[n]
n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst[n]]
lenlst = len(lst)
for i in lst[n:]:
yield i
| import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class LuckyNumbers {
private static int MAX = 200000;
private static List<Integer> luckyEven = luckyNumbers(MAX, true);
private static List<Integer> luckyOdd = luckyNumbers(MAX, false);
public static void main(String[] args) {
if ( args.length == 1 || ( args.length == 2 && args[1].compareTo("lucky") == 0 ) ) {
int n = Integer.parseInt(args[0]);
System.out.printf("LuckyNumber(%d) = %d%n", n, luckyOdd.get(n-1));
}
else if ( args.length == 2 && args[1].compareTo("evenLucky") == 0 ) {
int n = Integer.parseInt(args[0]);
System.out.printf("EvenLuckyNumber(%d) = %d%n", n, luckyEven.get(n-1));
}
else if ( args.length == 2 || args.length == 3 ) {
int j = Integer.parseInt(args[0]);
int k = Integer.parseInt(args[1]);
if ( ( args.length == 2 && k > 0 ) || (args.length == 3 && k > 0 && args[2].compareTo("lucky") == 0 ) ) {
System.out.printf("LuckyNumber(%d) through LuckyNumber(%d) = %s%n", j, k, luckyOdd.subList(j-1, k));
}
else if ( args.length == 3 && k > 0 && args[2].compareTo("evenLucky") == 0 ) {
System.out.printf("EvenLuckyNumber(%d) through EvenLuckyNumber(%d) = %s%n", j, k, luckyEven.subList(j-1, k));
}
else if ( ( args.length == 2 && k < 0 ) || (args.length == 3 && k < 0 && args[2].compareTo("lucky") == 0 ) ) {
int n = Collections.binarySearch(luckyOdd, j);
int m = Collections.binarySearch(luckyOdd, -k);
System.out.printf("Lucky Numbers in the range %d to %d inclusive = %s%n", j, -k, luckyOdd.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));
}
else if ( args.length == 3 && k < 0 && args[2].compareTo("evenLucky") == 0 ) {
int n = Collections.binarySearch(luckyEven, j);
int m = Collections.binarySearch(luckyEven, -k);
System.out.printf("Even Lucky Numbers in the range %d to %d inclusive = %s%n", j, -k, luckyEven.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1));
}
}
}
private static List<Integer> luckyNumbers(int max, boolean even) {
List<Integer> luckyList = new ArrayList<>();
for ( int i = even ? 2 : 1 ; i <= max ; i += 2 ) {
luckyList.add(i);
}
int start = 1;
boolean removed = true;
while ( removed ) {
removed = false;
int increment = luckyList.get(start);
List<Integer> remove = new ArrayList<>();
for ( int i = increment-1 ; i < luckyList.size() ; i += increment ) {
remove.add(0, i);
removed = true;
}
for ( int i : remove ) {
luckyList.remove(i);
}
start++;
}
return luckyList;
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | >>> x="From global scope"
>>> def outerfunc():
x = "From scope at outerfunc"
def scoped_local():
x = "scope local"
return "scoped_local scope gives x = " + x
print(scoped_local())
def scoped_nonlocal():
nonlocal x
return "scoped_nonlocal scope gives x = " + x
print(scoped_nonlocal())
def scoped_global():
global x
return "scoped_global scope gives x = " + x
print(scoped_global())
def scoped_notdefinedlocally():
return "scoped_notdefinedlocally scope gives x = " + x
print(scoped_notdefinedlocally())
>>> outerfunc()
scoped_local scope gives x = scope local
scoped_nonlocal scope gives x = From scope at outerfunc
scoped_global scope gives x = From global scope
scoped_notdefinedlocally scope gives x = From global scope
>>>
| public
protected
private
static
public void function(int x){
int y;
{
int z;
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | >>> x="From global scope"
>>> def outerfunc():
x = "From scope at outerfunc"
def scoped_local():
x = "scope local"
return "scoped_local scope gives x = " + x
print(scoped_local())
def scoped_nonlocal():
nonlocal x
return "scoped_nonlocal scope gives x = " + x
print(scoped_nonlocal())
def scoped_global():
global x
return "scoped_global scope gives x = " + x
print(scoped_global())
def scoped_notdefinedlocally():
return "scoped_notdefinedlocally scope gives x = " + x
print(scoped_notdefinedlocally())
>>> outerfunc()
scoped_local scope gives x = scope local
scoped_nonlocal scope gives x = From scope at outerfunc
scoped_global scope gives x = From global scope
scoped_notdefinedlocally scope gives x = From global scope
>>>
| public
protected
private
static
public void function(int x){
int y;
{
int z;
}
}
|
Convert this Python block to Java, preserving its control flow and logic. |
import argparse
from argparse import Namespace
import datetime
import shlex
def parse_args():
'Set up, parse, and return arguments'
parser = argparse.ArgumentParser(epilog=globals()['__doc__'])
parser.add_argument('command', choices='add pl plc pa'.split(),
help=)
parser.add_argument('-d', '--description',
help='A description of the item. (e.g., title, name)')
parser.add_argument('-t', '--tag',
help=(
))
parser.add_argument('-f', '--field', nargs=2, action='append',
help='Other optional fields with value (can be repeated)')
return parser
def do_add(args, dbname):
'Add a new entry'
if args.description is None:
args.description = ''
if args.tag is None:
args.tag = ''
del args.command
print('Writing record to %s' % dbname)
with open(dbname, 'a') as db:
db.write('%r\n' % args)
def do_pl(args, dbname):
'Print the latest entry'
print('Getting last record from %s' % dbname)
with open(dbname, 'r') as db:
for line in db: pass
record = eval(line)
del record._date
print(str(record))
def do_plc(args, dbname):
'Print the latest entry for each category/tag'
print('Getting latest record for each tag from %s' % dbname)
with open(dbname, 'r') as db:
records = [eval(line) for line in db]
tags = set(record.tag for record in records)
records.reverse()
for record in records:
if record.tag in tags:
del record._date
print(str(record))
tags.discard(record.tag)
if not tags: break
def do_pa(args, dbname):
'Print all entries sorted by a date'
print('Getting all records by date from %s' % dbname)
with open(dbname, 'r') as db:
records = [eval(line) for line in db]
for record in records:
del record._date
print(str(record))
def test():
import time
parser = parse_args()
for cmdline in [
,
,
,
,
,
]:
args = parser.parse_args(shlex.split(cmdline))
now = datetime.datetime.utcnow()
args._date = now.isoformat()
do_command[args.command](args, dbname)
time.sleep(0.5)
do_command = dict(add=do_add, pl=do_pl, plc=do_plc, pa=do_pa)
dbname = '_simple_db_db.py'
if __name__ == '__main__':
if 0:
test()
else:
parser = parse_args()
args = parser.parse_args()
now = datetime.datetime.utcnow()
args._date = now.isoformat()
do_command[args.command](args, dbname)
| import java.io.*;
import java.text.*;
import java.util.*;
public class SimpleDatabase {
final static String filename = "simdb.csv";
public static void main(String[] args) {
if (args.length < 1 || args.length > 3) {
printUsage();
return;
}
switch (args[0].toLowerCase()) {
case "add":
addItem(args);
break;
case "latest":
printLatest(args);
break;
case "all":
printAll();
break;
default:
printUsage();
break;
}
}
private static class Item implements Comparable<Item>{
final String name;
final String date;
final String category;
Item(String n, String d, String c) {
name = n;
date = d;
category = c;
}
@Override
public int compareTo(Item item){
return date.compareTo(item.date);
}
@Override
public String toString() {
return String.format("%s,%s,%s%n", name, date, category);
}
}
private static void addItem(String[] input) {
if (input.length < 2) {
printUsage();
return;
}
List<Item> db = load();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = sdf.format(new Date());
String cat = (input.length == 3) ? input[2] : "none";
db.add(new Item(input[1], date, cat));
store(db);
}
private static void printLatest(String[] a) {
List<Item> db = load();
if (db.isEmpty()) {
System.out.println("No entries in database.");
return;
}
Collections.sort(db);
if (a.length == 2) {
for (Item item : db)
if (item.category.equals(a[1]))
System.out.println(item);
} else {
System.out.println(db.get(0));
}
}
private static void printAll() {
List<Item> db = load();
if (db.isEmpty()) {
System.out.println("No entries in database.");
return;
}
Collections.sort(db);
for (Item item : db)
System.out.println(item);
}
private static List<Item> load() {
List<Item> db = new ArrayList<>();
try (Scanner sc = new Scanner(new File(filename))) {
while (sc.hasNext()) {
String[] item = sc.nextLine().split(",");
db.add(new Item(item[0], item[1], item[2]));
}
} catch (IOException e) {
System.out.println(e);
}
return db;
}
private static void store(List<Item> db) {
try (FileWriter fw = new FileWriter(filename)) {
for (Item item : db)
fw.write(item.toString());
} catch (IOException e) {
System.out.println(e);
}
}
private static void printUsage() {
System.out.println("Usage:");
System.out.println(" simdb cmd [categoryName]");
System.out.println(" add add item, followed by optional category");
System.out.println(" latest print last added item(s), followed by "
+ "optional category");
System.out.println(" all print all");
System.out.println(" For instance: add \"some item name\" "
+ "\"some category name\"");
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. |
import argparse
from argparse import Namespace
import datetime
import shlex
def parse_args():
'Set up, parse, and return arguments'
parser = argparse.ArgumentParser(epilog=globals()['__doc__'])
parser.add_argument('command', choices='add pl plc pa'.split(),
help=)
parser.add_argument('-d', '--description',
help='A description of the item. (e.g., title, name)')
parser.add_argument('-t', '--tag',
help=(
))
parser.add_argument('-f', '--field', nargs=2, action='append',
help='Other optional fields with value (can be repeated)')
return parser
def do_add(args, dbname):
'Add a new entry'
if args.description is None:
args.description = ''
if args.tag is None:
args.tag = ''
del args.command
print('Writing record to %s' % dbname)
with open(dbname, 'a') as db:
db.write('%r\n' % args)
def do_pl(args, dbname):
'Print the latest entry'
print('Getting last record from %s' % dbname)
with open(dbname, 'r') as db:
for line in db: pass
record = eval(line)
del record._date
print(str(record))
def do_plc(args, dbname):
'Print the latest entry for each category/tag'
print('Getting latest record for each tag from %s' % dbname)
with open(dbname, 'r') as db:
records = [eval(line) for line in db]
tags = set(record.tag for record in records)
records.reverse()
for record in records:
if record.tag in tags:
del record._date
print(str(record))
tags.discard(record.tag)
if not tags: break
def do_pa(args, dbname):
'Print all entries sorted by a date'
print('Getting all records by date from %s' % dbname)
with open(dbname, 'r') as db:
records = [eval(line) for line in db]
for record in records:
del record._date
print(str(record))
def test():
import time
parser = parse_args()
for cmdline in [
,
,
,
,
,
]:
args = parser.parse_args(shlex.split(cmdline))
now = datetime.datetime.utcnow()
args._date = now.isoformat()
do_command[args.command](args, dbname)
time.sleep(0.5)
do_command = dict(add=do_add, pl=do_pl, plc=do_plc, pa=do_pa)
dbname = '_simple_db_db.py'
if __name__ == '__main__':
if 0:
test()
else:
parser = parse_args()
args = parser.parse_args()
now = datetime.datetime.utcnow()
args._date = now.isoformat()
do_command[args.command](args, dbname)
| import java.io.*;
import java.text.*;
import java.util.*;
public class SimpleDatabase {
final static String filename = "simdb.csv";
public static void main(String[] args) {
if (args.length < 1 || args.length > 3) {
printUsage();
return;
}
switch (args[0].toLowerCase()) {
case "add":
addItem(args);
break;
case "latest":
printLatest(args);
break;
case "all":
printAll();
break;
default:
printUsage();
break;
}
}
private static class Item implements Comparable<Item>{
final String name;
final String date;
final String category;
Item(String n, String d, String c) {
name = n;
date = d;
category = c;
}
@Override
public int compareTo(Item item){
return date.compareTo(item.date);
}
@Override
public String toString() {
return String.format("%s,%s,%s%n", name, date, category);
}
}
private static void addItem(String[] input) {
if (input.length < 2) {
printUsage();
return;
}
List<Item> db = load();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = sdf.format(new Date());
String cat = (input.length == 3) ? input[2] : "none";
db.add(new Item(input[1], date, cat));
store(db);
}
private static void printLatest(String[] a) {
List<Item> db = load();
if (db.isEmpty()) {
System.out.println("No entries in database.");
return;
}
Collections.sort(db);
if (a.length == 2) {
for (Item item : db)
if (item.category.equals(a[1]))
System.out.println(item);
} else {
System.out.println(db.get(0));
}
}
private static void printAll() {
List<Item> db = load();
if (db.isEmpty()) {
System.out.println("No entries in database.");
return;
}
Collections.sort(db);
for (Item item : db)
System.out.println(item);
}
private static List<Item> load() {
List<Item> db = new ArrayList<>();
try (Scanner sc = new Scanner(new File(filename))) {
while (sc.hasNext()) {
String[] item = sc.nextLine().split(",");
db.add(new Item(item[0], item[1], item[2]));
}
} catch (IOException e) {
System.out.println(e);
}
return db;
}
private static void store(List<Item> db) {
try (FileWriter fw = new FileWriter(filename)) {
for (Item item : db)
fw.write(item.toString());
} catch (IOException e) {
System.out.println(e);
}
}
private static void printUsage() {
System.out.println("Usage:");
System.out.println(" simdb cmd [categoryName]");
System.out.println(" add add item, followed by optional category");
System.out.println(" latest print last added item(s), followed by "
+ "optional category");
System.out.println(" all print all");
System.out.println(" For instance: add \"some item name\" "
+ "\"some category name\"");
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | from collections import namedtuple
Circle = namedtuple("Circle", "x y r")
circles = [
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circle(-0.2495892950, -0.3832854473, 1.0845181219),
Circle( 1.7813504266, 1.6178237031, 0.8162655711),
Circle(-0.1985249206, -0.8343333301, 0.0538864941),
Circle(-1.7011985145, -0.1263820964, 0.4776976918),
Circle(-0.4319462812, 1.4104420482, 0.7886291537),
Circle( 0.2178372997, -0.9499557344, 0.0357871187),
Circle(-0.6294854565, -1.3078893852, 0.7653357688),
Circle( 1.7952608455, 0.6281269104, 0.2727652452),
Circle( 1.4168575317, 1.0683357171, 1.1016025378),
Circle( 1.4637371396, 0.9463877418, 1.1846214562),
Circle(-0.5263668798, 1.7315156631, 1.4428514068),
Circle(-1.2197352481, 0.9144146579, 1.0727263474),
Circle(-0.1389358881, 0.1092805780, 0.7350208828),
Circle( 1.5293954595, 0.0030278255, 1.2472867347),
Circle(-0.5258728625, 1.3782633069, 1.3495508831),
Circle(-0.1403562064, 0.2437382535, 1.3804956588),
Circle( 0.8055826339, -0.0482092025, 0.3327165165),
Circle(-0.6311979224, 0.7184578971, 0.2491045282),
Circle( 1.4685857879, -0.8347049536, 1.3670667538),
Circle(-0.6855727502, 1.6465021616, 1.0593087096),
Circle( 0.0152957411, 0.0638919221, 0.9771215985)]
def main():
x_min = min(c.x - c.r for c in circles)
x_max = max(c.x + c.r for c in circles)
y_min = min(c.y - c.r for c in circles)
y_max = max(c.y + c.r for c in circles)
box_side = 500
dx = (x_max - x_min) / box_side
dy = (y_max - y_min) / box_side
count = 0
for r in xrange(box_side):
y = y_min + r * dy
for c in xrange(box_side):
x = x_min + c * dx
if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)
for circle in circles):
count += 1
print "Approximated area:", count * dx * dy
main()
| public class CirclesTotalArea {
private static double distSq(double x1, double y1, double x2, double y2) {
return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
}
private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) {
double r2 = circ[2] * circ[2];
return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 &&
distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 &&
distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 &&
distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2;
}
private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) {
if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] &&
rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; }
double r2 = circ[2] + Math.max(rect[2], rect[3]);
r2 = r2 * r2;
return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 &&
distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 &&
distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 &&
distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2;
}
private static boolean[] surelyOutside;
private static double totalArea(double[] rect, double[][] circs, int d) {
int surelyOutsideCount = 0;
for(int i = 0; i < circs.length; i++) {
if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; }
if(rectangleSurelyOutsideCircle(rect, circs[i])) {
surelyOutside[i] = true;
surelyOutsideCount++;
}
else { surelyOutside[i] = false; }
}
if(surelyOutsideCount == circs.length) { return 0; }
if(d < 1) {
return rect[2] * rect[3] / 3;
}
if(surelyOutsideCount > 0) {
double[][] newCircs = new double[circs.length - surelyOutsideCount][3];
int loc = 0;
for(int i = 0; i < circs.length; i++) {
if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; }
}
circs = newCircs;
}
double w = rect[2] / 2;
double h = rect[3] / 2;
double[][] pieces = {
{ rect[0], rect[1], w, h },
{ rect[0] + w, rect[1], w, h },
{ rect[0], rect[1] - h, w, h },
{ rect[0] + w, rect[1] - h, w, h }
};
double total = 0;
for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); }
return total;
}
public static double totalArea(double[][] circs, int d) {
double maxx = Double.NEGATIVE_INFINITY;
double minx = Double.POSITIVE_INFINITY;
double maxy = Double.NEGATIVE_INFINITY;
double miny = Double.POSITIVE_INFINITY;
for(double[] circ: circs) {
if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; }
if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; }
if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; }
if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; }
}
double[] rect = { minx, maxy, maxx - minx, maxy - miny };
surelyOutside = new boolean[circs.length];
return totalArea(rect, circs, d);
}
public static void main(String[] args) {
double[][] circs = {
{ 1.6417233788, 1.6121789534, 0.0848270516 },
{-1.4944608174, 1.2077959613, 1.1039549836 },
{ 0.6110294452, -0.6907087527, 0.9089162485 },
{ 0.3844862411, 0.2923344616, 0.2375743054 },
{-0.2495892950, -0.3832854473, 1.0845181219 },
{1.7813504266, 1.6178237031, 0.8162655711 },
{-0.1985249206, -0.8343333301, 0.0538864941 },
{-1.7011985145, -0.1263820964, 0.4776976918 },
{-0.4319462812, 1.4104420482, 0.7886291537 },
{0.2178372997, -0.9499557344, 0.0357871187 },
{-0.6294854565, -1.3078893852, 0.7653357688 },
{1.7952608455, 0.6281269104, 0.2727652452 },
{1.4168575317, 1.0683357171, 1.1016025378 },
{1.4637371396, 0.9463877418, 1.1846214562 },
{-0.5263668798, 1.7315156631, 1.4428514068 },
{-1.2197352481, 0.9144146579, 1.0727263474 },
{-0.1389358881, 0.1092805780, 0.7350208828 },
{1.5293954595, 0.0030278255, 1.2472867347 },
{-0.5258728625, 1.3782633069, 1.3495508831 },
{-0.1403562064, 0.2437382535, 1.3804956588 },
{0.8055826339, -0.0482092025, 0.3327165165 },
{-0.6311979224, 0.7184578971, 0.2491045282 },
{1.4685857879, -0.8347049536, 1.3670667538 },
{-0.6855727502, 1.6465021616, 1.0593087096 },
{0.0152957411, 0.0638919221, 0.9771215985 }
};
double ans = totalArea(circs, 24);
System.out.println("Approx. area is " + ans);
System.out.println("Error is " + Math.abs(21.56503660 - ans));
}
}
|
Write a version of this Python function in Java with identical behavior. | from collections import namedtuple
Circle = namedtuple("Circle", "x y r")
circles = [
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circle(-0.2495892950, -0.3832854473, 1.0845181219),
Circle( 1.7813504266, 1.6178237031, 0.8162655711),
Circle(-0.1985249206, -0.8343333301, 0.0538864941),
Circle(-1.7011985145, -0.1263820964, 0.4776976918),
Circle(-0.4319462812, 1.4104420482, 0.7886291537),
Circle( 0.2178372997, -0.9499557344, 0.0357871187),
Circle(-0.6294854565, -1.3078893852, 0.7653357688),
Circle( 1.7952608455, 0.6281269104, 0.2727652452),
Circle( 1.4168575317, 1.0683357171, 1.1016025378),
Circle( 1.4637371396, 0.9463877418, 1.1846214562),
Circle(-0.5263668798, 1.7315156631, 1.4428514068),
Circle(-1.2197352481, 0.9144146579, 1.0727263474),
Circle(-0.1389358881, 0.1092805780, 0.7350208828),
Circle( 1.5293954595, 0.0030278255, 1.2472867347),
Circle(-0.5258728625, 1.3782633069, 1.3495508831),
Circle(-0.1403562064, 0.2437382535, 1.3804956588),
Circle( 0.8055826339, -0.0482092025, 0.3327165165),
Circle(-0.6311979224, 0.7184578971, 0.2491045282),
Circle( 1.4685857879, -0.8347049536, 1.3670667538),
Circle(-0.6855727502, 1.6465021616, 1.0593087096),
Circle( 0.0152957411, 0.0638919221, 0.9771215985)]
def main():
x_min = min(c.x - c.r for c in circles)
x_max = max(c.x + c.r for c in circles)
y_min = min(c.y - c.r for c in circles)
y_max = max(c.y + c.r for c in circles)
box_side = 500
dx = (x_max - x_min) / box_side
dy = (y_max - y_min) / box_side
count = 0
for r in xrange(box_side):
y = y_min + r * dy
for c in xrange(box_side):
x = x_min + c * dx
if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)
for circle in circles):
count += 1
print "Approximated area:", count * dx * dy
main()
| public class CirclesTotalArea {
private static double distSq(double x1, double y1, double x2, double y2) {
return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
}
private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) {
double r2 = circ[2] * circ[2];
return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 &&
distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 &&
distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 &&
distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2;
}
private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) {
if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] &&
rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; }
double r2 = circ[2] + Math.max(rect[2], rect[3]);
r2 = r2 * r2;
return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 &&
distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 &&
distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 &&
distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2;
}
private static boolean[] surelyOutside;
private static double totalArea(double[] rect, double[][] circs, int d) {
int surelyOutsideCount = 0;
for(int i = 0; i < circs.length; i++) {
if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; }
if(rectangleSurelyOutsideCircle(rect, circs[i])) {
surelyOutside[i] = true;
surelyOutsideCount++;
}
else { surelyOutside[i] = false; }
}
if(surelyOutsideCount == circs.length) { return 0; }
if(d < 1) {
return rect[2] * rect[3] / 3;
}
if(surelyOutsideCount > 0) {
double[][] newCircs = new double[circs.length - surelyOutsideCount][3];
int loc = 0;
for(int i = 0; i < circs.length; i++) {
if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; }
}
circs = newCircs;
}
double w = rect[2] / 2;
double h = rect[3] / 2;
double[][] pieces = {
{ rect[0], rect[1], w, h },
{ rect[0] + w, rect[1], w, h },
{ rect[0], rect[1] - h, w, h },
{ rect[0] + w, rect[1] - h, w, h }
};
double total = 0;
for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); }
return total;
}
public static double totalArea(double[][] circs, int d) {
double maxx = Double.NEGATIVE_INFINITY;
double minx = Double.POSITIVE_INFINITY;
double maxy = Double.NEGATIVE_INFINITY;
double miny = Double.POSITIVE_INFINITY;
for(double[] circ: circs) {
if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; }
if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; }
if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; }
if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; }
}
double[] rect = { minx, maxy, maxx - minx, maxy - miny };
surelyOutside = new boolean[circs.length];
return totalArea(rect, circs, d);
}
public static void main(String[] args) {
double[][] circs = {
{ 1.6417233788, 1.6121789534, 0.0848270516 },
{-1.4944608174, 1.2077959613, 1.1039549836 },
{ 0.6110294452, -0.6907087527, 0.9089162485 },
{ 0.3844862411, 0.2923344616, 0.2375743054 },
{-0.2495892950, -0.3832854473, 1.0845181219 },
{1.7813504266, 1.6178237031, 0.8162655711 },
{-0.1985249206, -0.8343333301, 0.0538864941 },
{-1.7011985145, -0.1263820964, 0.4776976918 },
{-0.4319462812, 1.4104420482, 0.7886291537 },
{0.2178372997, -0.9499557344, 0.0357871187 },
{-0.6294854565, -1.3078893852, 0.7653357688 },
{1.7952608455, 0.6281269104, 0.2727652452 },
{1.4168575317, 1.0683357171, 1.1016025378 },
{1.4637371396, 0.9463877418, 1.1846214562 },
{-0.5263668798, 1.7315156631, 1.4428514068 },
{-1.2197352481, 0.9144146579, 1.0727263474 },
{-0.1389358881, 0.1092805780, 0.7350208828 },
{1.5293954595, 0.0030278255, 1.2472867347 },
{-0.5258728625, 1.3782633069, 1.3495508831 },
{-0.1403562064, 0.2437382535, 1.3804956588 },
{0.8055826339, -0.0482092025, 0.3327165165 },
{-0.6311979224, 0.7184578971, 0.2491045282 },
{1.4685857879, -0.8347049536, 1.3670667538 },
{-0.6855727502, 1.6465021616, 1.0593087096 },
{0.0152957411, 0.0638919221, 0.9771215985 }
};
double ans = totalArea(circs, 24);
System.out.println("Approx. area is " + ans);
System.out.println("Error is " + Math.abs(21.56503660 - ans));
}
}
|
Write the same code in Java as shown below in Python. | from collections import namedtuple
Circle = namedtuple("Circle", "x y r")
circles = [
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circle(-0.2495892950, -0.3832854473, 1.0845181219),
Circle( 1.7813504266, 1.6178237031, 0.8162655711),
Circle(-0.1985249206, -0.8343333301, 0.0538864941),
Circle(-1.7011985145, -0.1263820964, 0.4776976918),
Circle(-0.4319462812, 1.4104420482, 0.7886291537),
Circle( 0.2178372997, -0.9499557344, 0.0357871187),
Circle(-0.6294854565, -1.3078893852, 0.7653357688),
Circle( 1.7952608455, 0.6281269104, 0.2727652452),
Circle( 1.4168575317, 1.0683357171, 1.1016025378),
Circle( 1.4637371396, 0.9463877418, 1.1846214562),
Circle(-0.5263668798, 1.7315156631, 1.4428514068),
Circle(-1.2197352481, 0.9144146579, 1.0727263474),
Circle(-0.1389358881, 0.1092805780, 0.7350208828),
Circle( 1.5293954595, 0.0030278255, 1.2472867347),
Circle(-0.5258728625, 1.3782633069, 1.3495508831),
Circle(-0.1403562064, 0.2437382535, 1.3804956588),
Circle( 0.8055826339, -0.0482092025, 0.3327165165),
Circle(-0.6311979224, 0.7184578971, 0.2491045282),
Circle( 1.4685857879, -0.8347049536, 1.3670667538),
Circle(-0.6855727502, 1.6465021616, 1.0593087096),
Circle( 0.0152957411, 0.0638919221, 0.9771215985)]
def main():
x_min = min(c.x - c.r for c in circles)
x_max = max(c.x + c.r for c in circles)
y_min = min(c.y - c.r for c in circles)
y_max = max(c.y + c.r for c in circles)
box_side = 500
dx = (x_max - x_min) / box_side
dy = (y_max - y_min) / box_side
count = 0
for r in xrange(box_side):
y = y_min + r * dy
for c in xrange(box_side):
x = x_min + c * dx
if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)
for circle in circles):
count += 1
print "Approximated area:", count * dx * dy
main()
| public class CirclesTotalArea {
private static double distSq(double x1, double y1, double x2, double y2) {
return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
}
private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) {
double r2 = circ[2] * circ[2];
return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 &&
distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 &&
distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 &&
distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2;
}
private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) {
if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] &&
rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; }
double r2 = circ[2] + Math.max(rect[2], rect[3]);
r2 = r2 * r2;
return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 &&
distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 &&
distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 &&
distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2;
}
private static boolean[] surelyOutside;
private static double totalArea(double[] rect, double[][] circs, int d) {
int surelyOutsideCount = 0;
for(int i = 0; i < circs.length; i++) {
if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; }
if(rectangleSurelyOutsideCircle(rect, circs[i])) {
surelyOutside[i] = true;
surelyOutsideCount++;
}
else { surelyOutside[i] = false; }
}
if(surelyOutsideCount == circs.length) { return 0; }
if(d < 1) {
return rect[2] * rect[3] / 3;
}
if(surelyOutsideCount > 0) {
double[][] newCircs = new double[circs.length - surelyOutsideCount][3];
int loc = 0;
for(int i = 0; i < circs.length; i++) {
if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; }
}
circs = newCircs;
}
double w = rect[2] / 2;
double h = rect[3] / 2;
double[][] pieces = {
{ rect[0], rect[1], w, h },
{ rect[0] + w, rect[1], w, h },
{ rect[0], rect[1] - h, w, h },
{ rect[0] + w, rect[1] - h, w, h }
};
double total = 0;
for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); }
return total;
}
public static double totalArea(double[][] circs, int d) {
double maxx = Double.NEGATIVE_INFINITY;
double minx = Double.POSITIVE_INFINITY;
double maxy = Double.NEGATIVE_INFINITY;
double miny = Double.POSITIVE_INFINITY;
for(double[] circ: circs) {
if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; }
if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; }
if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; }
if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; }
}
double[] rect = { minx, maxy, maxx - minx, maxy - miny };
surelyOutside = new boolean[circs.length];
return totalArea(rect, circs, d);
}
public static void main(String[] args) {
double[][] circs = {
{ 1.6417233788, 1.6121789534, 0.0848270516 },
{-1.4944608174, 1.2077959613, 1.1039549836 },
{ 0.6110294452, -0.6907087527, 0.9089162485 },
{ 0.3844862411, 0.2923344616, 0.2375743054 },
{-0.2495892950, -0.3832854473, 1.0845181219 },
{1.7813504266, 1.6178237031, 0.8162655711 },
{-0.1985249206, -0.8343333301, 0.0538864941 },
{-1.7011985145, -0.1263820964, 0.4776976918 },
{-0.4319462812, 1.4104420482, 0.7886291537 },
{0.2178372997, -0.9499557344, 0.0357871187 },
{-0.6294854565, -1.3078893852, 0.7653357688 },
{1.7952608455, 0.6281269104, 0.2727652452 },
{1.4168575317, 1.0683357171, 1.1016025378 },
{1.4637371396, 0.9463877418, 1.1846214562 },
{-0.5263668798, 1.7315156631, 1.4428514068 },
{-1.2197352481, 0.9144146579, 1.0727263474 },
{-0.1389358881, 0.1092805780, 0.7350208828 },
{1.5293954595, 0.0030278255, 1.2472867347 },
{-0.5258728625, 1.3782633069, 1.3495508831 },
{-0.1403562064, 0.2437382535, 1.3804956588 },
{0.8055826339, -0.0482092025, 0.3327165165 },
{-0.6311979224, 0.7184578971, 0.2491045282 },
{1.4685857879, -0.8347049536, 1.3670667538 },
{-0.6855727502, 1.6465021616, 1.0593087096 },
{0.0152957411, 0.0638919221, 0.9771215985 }
};
double ans = totalArea(circs, 24);
System.out.println("Approx. area is " + ans);
System.out.println("Error is " + Math.abs(21.56503660 - ans));
}
}
|
Translate the given Python code snippet into Java without altering its behavior. | from math import hypot, pi, cos, sin
from PIL import Image
def hough(im, ntx=460, mry=360):
"Calculate Hough transform."
pim = im.load()
nimx, mimy = im.size
mry = int(mry/2)*2
him = Image.new("L", (ntx, mry), 255)
phim = him.load()
rmax = hypot(nimx, mimy)
dr = rmax / (mry/2)
dth = pi / ntx
for jx in xrange(nimx):
for iy in xrange(mimy):
col = pim[jx, iy]
if col == 255: continue
for jtx in xrange(ntx):
th = dth * jtx
r = jx*cos(th) + iy*sin(th)
iry = mry/2 + int(r/dr+0.5)
phim[jtx, iry] -= 1
return him
def test():
"Test Hough transform with pentagon."
im = Image.open("pentagon.png").convert("L")
him = hough(im)
him.save("ho5.bmp")
if __name__ == "__main__": test()
| import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.*;
public class HoughTransform
{
public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast)
{
int width = inputData.width;
int height = inputData.height;
int maxRadius = (int)Math.ceil(Math.hypot(width, height));
int halfRAxisSize = rAxisSize >>> 1;
ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize);
double[] sinTable = new double[thetaAxisSize];
double[] cosTable = new double[thetaAxisSize];
for (int theta = thetaAxisSize - 1; theta >= 0; theta--)
{
double thetaRadians = theta * Math.PI / thetaAxisSize;
sinTable[theta] = Math.sin(thetaRadians);
cosTable[theta] = Math.cos(thetaRadians);
}
for (int y = height - 1; y >= 0; y--)
{
for (int x = width - 1; x >= 0; x--)
{
if (inputData.contrast(x, y, minContrast))
{
for (int theta = thetaAxisSize - 1; theta >= 0; theta--)
{
double r = cosTable[theta] * x + sinTable[theta] * y;
int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize;
outputData.accumulate(theta, rScaled, 1);
}
}
}
}
return outputData;
}
public static class ArrayData
{
public final int[] dataArray;
public final int width;
public final int height;
public ArrayData(int width, int height)
{
this(new int[width * height], width, height);
}
public ArrayData(int[] dataArray, int width, int height)
{
this.dataArray = dataArray;
this.width = width;
this.height = height;
}
public int get(int x, int y)
{ return dataArray[y * width + x]; }
public void set(int x, int y, int value)
{ dataArray[y * width + x] = value; }
public void accumulate(int x, int y, int delta)
{ set(x, y, get(x, y) + delta); }
public boolean contrast(int x, int y, int minContrast)
{
int centerValue = get(x, y);
for (int i = 8; i >= 0; i--)
{
if (i == 4)
continue;
int newx = x + (i % 3) - 1;
int newy = y + (i / 3) - 1;
if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height))
continue;
if (Math.abs(get(newx, newy) - centerValue) >= minContrast)
return true;
}
return false;
}
public int getMax()
{
int max = dataArray[0];
for (int i = width * height - 1; i > 0; i--)
if (dataArray[i] > max)
max = dataArray[i];
return max;
}
}
public static ArrayData getArrayDataFromImage(String filename) throws IOException
{
BufferedImage inputImage = ImageIO.read(new File(filename));
int width = inputImage.getWidth();
int height = inputImage.getHeight();
int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);
ArrayData arrayData = new ArrayData(width, height);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int rgbValue = rgbData[y * width + x];
rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);
arrayData.set(x, height - 1 - y, rgbValue);
}
}
return arrayData;
}
public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException
{
int max = arrayData.getMax();
BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < arrayData.height; y++)
{
for (int x = 0; x < arrayData.width; x++)
{
int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255);
outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000);
}
}
ImageIO.write(outputImage, "PNG", new File(filename));
return;
}
public static void main(String[] args) throws IOException
{
ArrayData inputData = getArrayDataFromImage(args[0]);
int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]);
ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast);
writeOutputImage(args[1], outputData);
return;
}
}
|
Generate an equivalent Java version of this Python code. | import math
import random
def GammaInc_Q( a, x):
a1 = a-1
a2 = a-2
def f0( t ):
return t**a1*math.exp(-t)
def df0(t):
return (a1-t)*t**a2*math.exp(-t)
y = a1
while f0(y)*(x-y) >2.0e-8 and y < x: y += .3
if y > x: y = x
h = 3.0e-4
n = int(y/h)
h = y/n
hh = 0.5*h
gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1)))
return gamax/gamma_spounge(a)
c = None
def gamma_spounge( z):
global c
a = 12
if c is None:
k1_factrl = 1.0
c = []
c.append(math.sqrt(2.0*math.pi))
for k in range(1,a):
c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl )
k1_factrl *= -k
accm = c[0]
for k in range(1,a):
accm += c[k] / (z+k)
accm *= math.exp( -(z+a)) * (z+a)**(z+0.5)
return accm/z;
def chi2UniformDistance( dataSet ):
expected = sum(dataSet)*1.0/len(dataSet)
cntrd = (d-expected for d in dataSet)
return sum(x*x for x in cntrd)/expected
def chi2Probability(dof, distance):
return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance)
def chi2IsUniform(dataSet, significance):
dof = len(dataSet)-1
dist = chi2UniformDistance(dataSet)
return chi2Probability( dof, dist ) > significance
dset1 = [ 199809, 200665, 199607, 200270, 199649 ]
dset2 = [ 522573, 244456, 139979, 71531, 21461 ]
for ds in (dset1, dset2):
print "Data set:", ds
dof = len(ds)-1
distance =chi2UniformDistance(ds)
print "dof: %d distance: %.4f" % (dof, distance),
prob = chi2Probability( dof, distance)
print "probability: %.4f"%prob,
print "uniform? ", "Yes"if chi2IsUniform(ds,0.05) else "No"
| import static java.lang.Math.pow;
import java.util.Arrays;
import static java.util.Arrays.stream;
import org.apache.commons.math3.special.Gamma;
public class Test {
static double x2Dist(double[] data) {
double avg = stream(data).sum() / data.length;
double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2));
return sqs / avg;
}
static double x2Prob(double dof, double distance) {
return Gamma.regularizedGammaQ(dof / 2, distance / 2);
}
static boolean x2IsUniform(double[] data, double significance) {
return x2Prob(data.length - 1.0, x2Dist(data)) > significance;
}
public static void main(String[] a) {
double[][] dataSets = {{199809, 200665, 199607, 200270, 199649},
{522573, 244456, 139979, 71531, 21461}};
System.out.printf(" %4s %12s %12s %8s %s%n",
"dof", "distance", "probability", "Uniform?", "dataset");
for (double[] ds : dataSets) {
int dof = ds.length - 1;
double dist = x2Dist(ds);
double prob = x2Prob(dof, dist);
System.out.printf("%4d %12.3f %12.8f %5s %6s%n",
dof, dist, prob, x2IsUniform(ds, 0.05) ? "YES" : "NO",
Arrays.toString(ds));
}
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | import numpy as np
import scipy as sp
import scipy.stats
def welch_ttest(x1, x2):
n1 = x1.size
n2 = x2.size
m1 = np.mean(x1)
m2 = np.mean(x2)
v1 = np.var(x1, ddof=1)
v2 = np.var(x2, ddof=1)
t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)
df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))
p = 2 * sp.stats.t.cdf(-abs(t), df)
return t, df, p
welch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))
(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)
| import org.apache.commons.math3.distribution.TDistribution;
public class WelchTTest {
public static double[] meanvar(double[] a) {
double m = 0.0, v = 0.0;
int n = a.length;
for (double x: a) {
m += x;
}
m /= n;
for (double x: a) {
v += (x - m) * (x - m);
}
v /= (n - 1);
return new double[] {m, v};
}
public static double[] welch_ttest(double[] x, double[] y) {
double mx, my, vx, vy, t, df, p;
double[] res;
int nx = x.length, ny = y.length;
res = meanvar(x);
mx = res[0];
vx = res[1];
res = meanvar(y);
my = res[0];
vy = res[1];
t = (mx-my)/Math.sqrt(vx/nx+vy/ny);
df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));
TDistribution dist = new TDistribution(df);
p = 2.0*dist.cumulativeProbability(-Math.abs(t));
return new double[] {t, df, p};
}
public static void main(String[] args) {
double x[] = {3.0, 4.0, 1.0, 2.1};
double y[] = {490.2, 340.0, 433.9};
double res[] = welch_ttest(x, y);
System.out.println("t = " + res[0]);
System.out.println("df = " + res[1]);
System.out.println("p = " + res[2]);
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | import numpy as np
import scipy as sp
import scipy.stats
def welch_ttest(x1, x2):
n1 = x1.size
n2 = x2.size
m1 = np.mean(x1)
m2 = np.mean(x2)
v1 = np.var(x1, ddof=1)
v2 = np.var(x2, ddof=1)
t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)
df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))
p = 2 * sp.stats.t.cdf(-abs(t), df)
return t, df, p
welch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))
(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)
| import org.apache.commons.math3.distribution.TDistribution;
public class WelchTTest {
public static double[] meanvar(double[] a) {
double m = 0.0, v = 0.0;
int n = a.length;
for (double x: a) {
m += x;
}
m /= n;
for (double x: a) {
v += (x - m) * (x - m);
}
v /= (n - 1);
return new double[] {m, v};
}
public static double[] welch_ttest(double[] x, double[] y) {
double mx, my, vx, vy, t, df, p;
double[] res;
int nx = x.length, ny = y.length;
res = meanvar(x);
mx = res[0];
vx = res[1];
res = meanvar(y);
my = res[0];
vy = res[1];
t = (mx-my)/Math.sqrt(vx/nx+vy/ny);
df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));
TDistribution dist = new TDistribution(df);
p = 2.0*dist.cumulativeProbability(-Math.abs(t));
return new double[] {t, df, p};
}
public static void main(String[] args) {
double x[] = {3.0, 4.0, 1.0, 2.1};
double y[] = {490.2, 340.0, 433.9};
double res[] = welch_ttest(x, y);
System.out.println("t = " + res[0]);
System.out.println("df = " + res[1]);
System.out.println("p = " + res[2]);
}
}
|
Preserve the algorithm and functionality while converting the code from Python to Java. | import numpy as np
import scipy as sp
import scipy.stats
def welch_ttest(x1, x2):
n1 = x1.size
n2 = x2.size
m1 = np.mean(x1)
m2 = np.mean(x2)
v1 = np.var(x1, ddof=1)
v2 = np.var(x2, ddof=1)
t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)
df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))
p = 2 * sp.stats.t.cdf(-abs(t), df)
return t, df, p
welch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))
(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)
| import org.apache.commons.math3.distribution.TDistribution;
public class WelchTTest {
public static double[] meanvar(double[] a) {
double m = 0.0, v = 0.0;
int n = a.length;
for (double x: a) {
m += x;
}
m /= n;
for (double x: a) {
v += (x - m) * (x - m);
}
v /= (n - 1);
return new double[] {m, v};
}
public static double[] welch_ttest(double[] x, double[] y) {
double mx, my, vx, vy, t, df, p;
double[] res;
int nx = x.length, ny = y.length;
res = meanvar(x);
mx = res[0];
vx = res[1];
res = meanvar(y);
my = res[0];
vy = res[1];
t = (mx-my)/Math.sqrt(vx/nx+vy/ny);
df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1)));
TDistribution dist = new TDistribution(df);
p = 2.0*dist.cumulativeProbability(-Math.abs(t));
return new double[] {t, df, p};
}
public static void main(String[] args) {
double x[] = {3.0, 4.0, 1.0, 2.1};
double y[] = {490.2, 340.0, 433.9};
double res[] = welch_ttest(x, y);
System.out.println("t = " + res[0]);
System.out.println("df = " + res[1]);
System.out.println("p = " + res[2]);
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | try:
from functools import reduce
except: pass
def topx(data, tops=None):
'Extract the set of top-level(s) in topological order'
for k, v in data.items():
v.discard(k)
if tops is None:
tops = toplevels(data)
return _topx(data, tops, [], set())
def _topx(data, tops, _sofar, _sofar_set):
'Recursive topological extractor'
_sofar += [tops]
_sofar_set.union(tops)
depends = reduce(set.union, (data.get(top, set()) for top in tops))
if depends:
_topx(data, depends, _sofar, _sofar_set)
ordered, accum = [], set()
for s in _sofar[::-1]:
ordered += [sorted(s - accum)]
accum |= s
return ordered
def printorder(order):
'Prettyprint topological ordering'
if order:
print("First: " + ', '.join(str(s) for s in order[0]))
for o in order[1:]:
print(" Then: " + ', '.join(str(s) for s in o))
def toplevels(data):
for k, v in data.items():
v.discard(k)
dependents = reduce(set.union, data.values())
return set(data.keys()) - dependents
if __name__ == '__main__':
data = dict(
top1 = set('ip1 des1 ip2'.split()),
top2 = set('ip2 des1 ip3'.split()),
des1 = set('des1a des1b des1c'.split()),
des1a = set('des1a1 des1a2'.split()),
des1c = set('des1c1 extra1'.split()),
ip2 = set('ip2a ip2b ip2c ipcommon'.split()),
ip1 = set('ip1a ipcommon extra1'.split()),
)
tops = toplevels(data)
print("The top levels of the dependency graph are: " + ' '.join(tops))
for t in sorted(tops):
print("\nThe compile order for top level: %s is..." % t)
printorder(topx(data, set([t])))
if len(tops) > 1:
print("\nThe compile order for top levels: %s is..."
% ' and '.join(str(s) for s in sorted(tops)) )
printorder(topx(data, tops))
| import java.util.*;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
public class TopologicalSort2 {
public static void main(String[] args) {
String s = "top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,"
+ "des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1";
Graph g = new Graph(s, new int[][]{
{0, 10}, {0, 2}, {0, 3},
{1, 10}, {1, 3}, {1, 4},
{2, 17}, {2, 5}, {2, 9},
{3, 6}, {3, 7}, {3, 8}, {3, 9},
{10, 11}, {10, 12}, {10, 13},
{11, 14}, {11, 15},
{13, 16}, {13, 17},});
System.out.println("Top levels: " + g.toplevels());
String[] files = {"top1", "top2", "ip1"};
for (String f : files)
System.out.printf("Compile order for %s %s%n", f, g.compileOrder(f));
}
}
class Graph {
List<String> vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = asList(s.split(","));
numVertices = vertices.size();
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> toplevels() {
List<String> result = new ArrayList<>();
outer:
for (int c = 0; c < numVertices; c++) {
for (int r = 0; r < numVertices; r++) {
if (adjacency[r][c])
continue outer;
}
result.add(vertices.get(c));
}
return result;
}
List<String> compileOrder(String item) {
LinkedList<String> result = new LinkedList<>();
LinkedList<Integer> queue = new LinkedList<>();
queue.add(vertices.indexOf(item));
while (!queue.isEmpty()) {
int r = queue.poll();
for (int c = 0; c < numVertices; c++) {
if (adjacency[r][c] && !queue.contains(c)) {
queue.add(c);
}
}
result.addFirst(vertices.get(r));
}
return result.stream().distinct().collect(toList());
}
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. | try:
from functools import reduce
except: pass
def topx(data, tops=None):
'Extract the set of top-level(s) in topological order'
for k, v in data.items():
v.discard(k)
if tops is None:
tops = toplevels(data)
return _topx(data, tops, [], set())
def _topx(data, tops, _sofar, _sofar_set):
'Recursive topological extractor'
_sofar += [tops]
_sofar_set.union(tops)
depends = reduce(set.union, (data.get(top, set()) for top in tops))
if depends:
_topx(data, depends, _sofar, _sofar_set)
ordered, accum = [], set()
for s in _sofar[::-1]:
ordered += [sorted(s - accum)]
accum |= s
return ordered
def printorder(order):
'Prettyprint topological ordering'
if order:
print("First: " + ', '.join(str(s) for s in order[0]))
for o in order[1:]:
print(" Then: " + ', '.join(str(s) for s in o))
def toplevels(data):
for k, v in data.items():
v.discard(k)
dependents = reduce(set.union, data.values())
return set(data.keys()) - dependents
if __name__ == '__main__':
data = dict(
top1 = set('ip1 des1 ip2'.split()),
top2 = set('ip2 des1 ip3'.split()),
des1 = set('des1a des1b des1c'.split()),
des1a = set('des1a1 des1a2'.split()),
des1c = set('des1c1 extra1'.split()),
ip2 = set('ip2a ip2b ip2c ipcommon'.split()),
ip1 = set('ip1a ipcommon extra1'.split()),
)
tops = toplevels(data)
print("The top levels of the dependency graph are: " + ' '.join(tops))
for t in sorted(tops):
print("\nThe compile order for top level: %s is..." % t)
printorder(topx(data, set([t])))
if len(tops) > 1:
print("\nThe compile order for top levels: %s is..."
% ' and '.join(str(s) for s in sorted(tops)) )
printorder(topx(data, tops))
| import java.util.*;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
public class TopologicalSort2 {
public static void main(String[] args) {
String s = "top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,"
+ "des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1";
Graph g = new Graph(s, new int[][]{
{0, 10}, {0, 2}, {0, 3},
{1, 10}, {1, 3}, {1, 4},
{2, 17}, {2, 5}, {2, 9},
{3, 6}, {3, 7}, {3, 8}, {3, 9},
{10, 11}, {10, 12}, {10, 13},
{11, 14}, {11, 15},
{13, 16}, {13, 17},});
System.out.println("Top levels: " + g.toplevels());
String[] files = {"top1", "top2", "ip1"};
for (String f : files)
System.out.printf("Compile order for %s %s%n", f, g.compileOrder(f));
}
}
class Graph {
List<String> vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = asList(s.split(","));
numVertices = vertices.size();
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> toplevels() {
List<String> result = new ArrayList<>();
outer:
for (int c = 0; c < numVertices; c++) {
for (int r = 0; r < numVertices; r++) {
if (adjacency[r][c])
continue outer;
}
result.add(vertices.get(c));
}
return result;
}
List<String> compileOrder(String item) {
LinkedList<String> result = new LinkedList<>();
LinkedList<Integer> queue = new LinkedList<>();
queue.add(vertices.indexOf(item));
while (!queue.isEmpty()) {
int r = queue.poll();
for (int c = 0; c < numVertices; c++) {
if (adjacency[r][c] && !queue.contains(c)) {
queue.add(c);
}
}
result.addFirst(vertices.get(r));
}
return result.stream().distinct().collect(toList());
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | def getitem(s, depth=0):
out = [""]
while s:
c = s[0]
if depth and (c == ',' or c == '}'):
return out,s
if c == '{':
x = getgroup(s[1:], depth+1)
if x:
out,s = [a+b for a in out for b in x[0]], x[1]
continue
if c == '\\' and len(s) > 1:
s, c = s[1:], c + s[1]
out, s = [a+c for a in out], s[1:]
return out,s
def getgroup(s, depth):
out, comma = [], False
while s:
g,s = getitem(s, depth)
if not s: break
out += g
if s[0] == '}':
if comma: return out, s[1:]
return ['{' + a + '}' for a in out], s[1:]
if s[0] == ',':
comma,s = True, s[1:]
return None
for s in .split('\n'):
print "\n\t".join([s] + getitem(s)[0]) + "\n"
| 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);
}
}
}
|
Change the following Python code into Java without altering its purpose. | def no_args():
pass
no_args()
def fixed_args(x, y):
print('x=%r, y=%r' % (x, y))
fixed_args(1, 2)
fixed_args(y=2, x=1)
myargs=(1,2)
fixed_args(*myargs)
def opt_args(x=1):
print(x)
opt_args()
opt_args(3.141)
def var_args(*v):
print(v)
var_args(1, 2, 3)
var_args(1, (2,3))
var_args()
fixed_args(y=2, x=1)
if 1:
no_args()
assert no_args() is None
def return_something():
return 1
x = return_something()
def is_builtin(x):
print(x.__name__ in dir(__builtins__))
is_builtin(pow)
is_builtin(is_builtin)
def takes_anything(*args, **kwargs):
for each in args:
print(each)
for key, value in sorted(kwargs.items()):
print("%s:%s" % (key, value))
wrapped_fn(*args, **kwargs)
| foo();
Int x = bar();
|
Translate the given Python code snippet into Java without altering its behavior. | def no_args():
pass
no_args()
def fixed_args(x, y):
print('x=%r, y=%r' % (x, y))
fixed_args(1, 2)
fixed_args(y=2, x=1)
myargs=(1,2)
fixed_args(*myargs)
def opt_args(x=1):
print(x)
opt_args()
opt_args(3.141)
def var_args(*v):
print(v)
var_args(1, 2, 3)
var_args(1, (2,3))
var_args()
fixed_args(y=2, x=1)
if 1:
no_args()
assert no_args() is None
def return_something():
return 1
x = return_something()
def is_builtin(x):
print(x.__name__ in dir(__builtins__))
is_builtin(pow)
is_builtin(is_builtin)
def takes_anything(*args, **kwargs):
for each in args:
print(each)
for key, value in sorted(kwargs.items()):
print("%s:%s" % (key, value))
wrapped_fn(*args, **kwargs)
| foo();
Int x = bar();
|
Convert the following code from Python to Java, ensuring the logic remains intact. | "Generate a short Superpermutation of n characters A... as a string using various algorithms."
from __future__ import print_function, division
from itertools import permutations
from math import factorial
import string
import datetime
import gc
MAXN = 7
def s_perm0(n):
allchars = string.ascii_uppercase[:n]
allperms = [''.join(p) for p in permutations(allchars)]
sp, tofind = allperms[0], set(allperms[1:])
while tofind:
for skip in range(1, n):
for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])):
trial_perm = (sp + trial_add)[-n:]
if trial_perm in tofind:
sp += trial_add
tofind.discard(trial_perm)
trial_add = None
break
if trial_add is None:
break
assert all(perm in sp for perm in allperms)
return sp
def s_perm1(n):
allchars = string.ascii_uppercase[:n]
allperms = [''.join(p) for p in sorted(permutations(allchars))]
perms, sp = allperms[::], ''
while perms:
nxt = perms.pop()
if nxt not in sp:
sp += nxt
assert all(perm in sp for perm in allperms)
return sp
def s_perm2(n):
allchars = string.ascii_uppercase[:n]
allperms = [''.join(p) for p in sorted(permutations(allchars))]
perms, sp = allperms[::], ''
while perms:
nxt = perms.pop(0)
if nxt not in sp:
sp += nxt
if perms:
nxt = perms.pop(-1)
if nxt not in sp:
sp += nxt
assert all(perm in sp for perm in allperms)
return sp
def _s_perm3(n, cmp):
allchars = string.ascii_uppercase[:n]
allperms = [''.join(p) for p in sorted(permutations(allchars))]
perms, sp = allperms[::], ''
while perms:
lastn = sp[-n:]
nxt = cmp(perms,
key=lambda pm:
sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn)))
perms.remove(nxt)
if nxt not in sp:
sp += nxt
assert all(perm in sp for perm in allperms)
return sp
def s_perm3_max(n):
return _s_perm3(n, max)
def s_perm3_min(n):
return _s_perm3(n, min)
longest = [factorial(n) * n for n in range(MAXN + 1)]
weight, runtime = {}, {}
print(__doc__)
for algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]:
print('\n
print(algo.__doc__)
weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0)
for n in range(1, MAXN + 1):
gc.collect()
gc.disable()
t = datetime.datetime.now()
sp = algo(n)
t = datetime.datetime.now() - t
gc.enable()
runtime[algo.__name__] += t
lensp = len(sp)
wt = (lensp / longest[n]) ** 2
print(' For N=%i: SP length %5i Max: %5i Weight: %5.2f'
% (n, lensp, longest[n], wt))
weight[algo.__name__] *= wt
weight[algo.__name__] **= 1 / n
weight[algo.__name__] = 1 / weight[algo.__name__]
print('%*s Overall Weight: %5.2f in %.1f seconds.'
% (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds()))
print('\n
print('\n'.join('%12s (%.3f)' % kv for kv in
sorted(weight.items(), key=lambda keyvalue: -keyvalue[1])))
print('\n
print('\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in
sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))
| import static java.util.stream.IntStream.rangeClosed;
public class Test {
final static int nMax = 12;
static char[] superperm;
static int pos;
static int[] count = new int[nMax];
static int factSum(int n) {
return rangeClosed(1, n)
.map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum();
}
static boolean r(int n) {
if (n == 0)
return false;
char c = superperm[pos - n];
if (--count[n] == 0) {
count[n] = n;
if (!r(n - 1))
return false;
}
superperm[pos++] = c;
return true;
}
static void superPerm(int n) {
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
pos = n;
superperm = new char[factSum(n)];
for (int i = 0; i < n + 1; i++)
count[i] = i;
for (int i = 1; i < n + 1; i++)
superperm[i - 1] = chars.charAt(i);
while (r(n)) {
}
}
public static void main(String[] args) {
for (int n = 0; n < nMax; n++) {
superPerm(n);
System.out.printf("superPerm(%2d) len = %d", n, superperm.length);
System.out.println();
}
}
}
|
Change the following Python code into Java without altering its purpose. | import random, tkMessageBox
from Tkinter import *
window = Tk()
window.geometry("300x50+100+100")
options = { "padx":5, "pady":5}
s=StringVar()
s.set(1)
def increase():
s.set(int(s.get())+1)
def rand():
if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"):
s.set(random.randrange(0,5000))
def update(e):
if not e.char.isdigit():
tkMessageBox.showerror('Error', 'Invalid input !')
return "break"
e = Entry(text=s)
e.grid(column=0, row=0, **options)
e.bind('<Key>', update)
b1 = Button(text="Increase", command=increase, **options )
b1.grid(column=1, row=0, **options)
b2 = Button(text="Random", command=rand, **options)
b2.grid(column=2, row=0, **options)
mainloop()
| import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Interact extends JFrame{
final JTextField numberField;
final JButton incButton, randButton;
public Interact(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
numberField = new JTextField();
incButton = new JButton("Increment");
randButton = new JButton("Random");
numberField.setText("0");
numberField.addKeyListener(new KeyListener(){
@Override
public void keyTyped(KeyEvent e) {
if(!Character.isDigit(e.getKeyChar())){
e.consume();
}
}
@Override
public void keyReleased(KeyEvent e){}
@Override
public void keyPressed(KeyEvent e){}
});
incButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String text = numberField.getText();
if(text.isEmpty()){
numberField.setText("1");
}else{
numberField.setText((Long.valueOf(text) + 1) + "");
}
}
});
randButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(JOptionPane.showConfirmDialog(null, "Are you sure?") ==
JOptionPane.YES_OPTION){
numberField.setText(Long.toString((long)(Math.random()
* Long.MAX_VALUE)));
}
}
});
setLayout(new GridLayout(2, 1));
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 2));
buttonPanel.add(incButton);
buttonPanel.add(randButton);
add(numberField);
add(buttonPanel);
pack();
}
public static void main(String[] args){
new Interact().setVisible(true);
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. | from random import randrange
try:
range = xrange
except: pass
def one_of_n(lines):
choice = None
for i, line in enumerate(lines):
if randrange(i+1) == 0:
choice = line
return choice
def one_of_n_test(n=10, trials=1000000):
bins = [0] * n
if n:
for i in range(trials):
bins[one_of_n(range(n))] += 1
return bins
print(one_of_n_test())
| import java.util.Arrays;
import java.util.Random;
public class OneOfNLines {
static Random rand;
public static int oneOfN(int n) {
int choice = 0;
for(int i = 1; i < n; i++) {
if(rand.nextInt(i+1) == 0)
choice = i;
}
return choice;
}
public static void main(String[] args) {
int n = 10;
int trials = 1000000;
int[] bins = new int[n];
rand = new Random();
for(int i = 0; i < trials; i++)
bins[oneOfN(n)]++;
System.out.println(Arrays.toString(bins));
}
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. | from itertools import groupby, permutations
def A036058(number):
return ''.join( str(len(list(g))) + k
for k,g in groupby(sorted(str(number), reverse=True)) )
def A036058_length(numberstring='0', printit=False):
iterations, last_three, queue_index = 1, ([None] * 3), 0
def A036058(number):
return ''.join( str(len(list(g))) + k
for k,g in groupby(number) )
while True:
if printit:
print(" %2i %s" % (iterations, numberstring))
numberstring = ''.join(sorted(numberstring, reverse=True))
if numberstring in last_three:
break
assert iterations < 1000000
last_three[queue_index], numberstring = numberstring, A036058(numberstring)
iterations += 1
queue_index +=1
queue_index %=3
return iterations
def max_A036058_length( start_range=range(11) ):
already_done = set()
max_len = (-1, [])
for n in start_range:
sn = str(n)
sns = tuple(sorted(sn, reverse=True))
if sns not in already_done:
already_done.add(sns)
size = A036058_length(sns)
if size > max_len[0]:
max_len = (size, [n])
elif size == max_len[0]:
max_len[1].append(n)
return max_len
lenmax, starts = max_A036058_length( range(1000000) )
allstarts = []
for n in starts:
allstarts += [int(''.join(x))
for x in set(k
for k in permutations(str(n), 4)
if k[0] != '0')]
allstarts = [x for x in sorted(allstarts) if x < 1000000]
print ( % (lenmax, allstarts) )
print ( )
for n in starts:
print()
A036058_length(str(n), printit=True)
| import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.IntStream;
public class SelfReferentialSequence {
static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);
public static void main(String[] args) {
Seeds res = IntStream.range(0, 1000_000)
.parallel()
.mapToObj(n -> summarize(n, false))
.collect(Seeds::new, Seeds::accept, Seeds::combine);
System.out.println("Seeds:");
res.seeds.forEach(e -> System.out.println(Arrays.toString(e)));
System.out.println("\nSequence:");
summarize(res.seeds.get(0)[0], true);
}
static int[] summarize(int seed, boolean display) {
String n = String.valueOf(seed);
String k = Arrays.toString(n.chars().sorted().toArray());
if (!display && cache.get(k) != null)
return new int[]{seed, cache.get(k)};
Set<String> seen = new HashSet<>();
StringBuilder sb = new StringBuilder();
int[] freq = new int[10];
while (!seen.contains(n)) {
seen.add(n);
int len = n.length();
for (int i = 0; i < len; i++)
freq[n.charAt(i) - '0']++;
sb.setLength(0);
for (int i = 9; i >= 0; i--) {
if (freq[i] != 0) {
sb.append(freq[i]).append(i);
freq[i] = 0;
}
}
if (display)
System.out.println(n);
n = sb.toString();
}
cache.put(k, seen.size());
return new int[]{seed, seen.size()};
}
static class Seeds {
int largest = Integer.MIN_VALUE;
List<int[]> seeds = new ArrayList<>();
void accept(int[] s) {
int size = s[1];
if (size >= largest) {
if (size > largest) {
largest = size;
seeds.clear();
}
seeds.add(s);
}
}
void combine(Seeds acc) {
acc.seeds.forEach(this::accept);
}
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | irregularOrdinals = {
"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth",
"nine": "ninth",
"twelve": "twelfth",
}
def num2ordinal(n):
conversion = int(float(n))
num = spell_integer(conversion)
hyphen = num.rsplit("-", 1)
num = num.rsplit(" ", 1)
delim = " "
if len(num[-1]) > len(hyphen[-1]):
num = hyphen
delim = "-"
if num[-1] in irregularOrdinals:
num[-1] = delim + irregularOrdinals[num[-1]]
elif num[-1].endswith("y"):
num[-1] = delim + num[-1][:-1] + "ieth"
else:
num[-1] = delim + num[-1] + "th"
return "".join(num)
if __name__ == "__main__":
tests = "1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123 00123.0 1.23e2".split()
for num in tests:
print("{} => {}".format(num, num2ordinal(num)))
TENS = [None, None, "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"]
SMALL = ["zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"]
HUGE = [None, None] + [h + "illion"
for h in ("m", "b", "tr", "quadr", "quint", "sext",
"sept", "oct", "non", "dec")]
def nonzero(c, n, connect=''):
return "" if n == 0 else connect + c + spell_integer(n)
def last_and(num):
if ',' in num:
pre, last = num.rsplit(',', 1)
if ' and ' not in last:
last = ' and' + last
num = ''.join([pre, ',', last])
return num
def big(e, n):
if e == 0:
return spell_integer(n)
elif e == 1:
return spell_integer(n) + " thousand"
else:
return spell_integer(n) + " " + HUGE[e]
def base1000_rev(n):
while n != 0:
n, r = divmod(n, 1000)
yield r
def spell_integer(n):
if n < 0:
return "minus " + spell_integer(-n)
elif n < 20:
return SMALL[n]
elif n < 100:
a, b = divmod(n, 10)
return TENS[a] + nonzero("-", b)
elif n < 1000:
a, b = divmod(n, 100)
return SMALL[a] + " hundred" + nonzero(" ", b, ' and')
else:
num = ", ".join([big(e, x) for e, x in
enumerate(base1000_rev(n)) if x][::-1])
return last_and(num)
| 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 ) : "");
}
}
|
Write a version of this Python function in Java with identical behavior. | irregularOrdinals = {
"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth",
"nine": "ninth",
"twelve": "twelfth",
}
def num2ordinal(n):
conversion = int(float(n))
num = spell_integer(conversion)
hyphen = num.rsplit("-", 1)
num = num.rsplit(" ", 1)
delim = " "
if len(num[-1]) > len(hyphen[-1]):
num = hyphen
delim = "-"
if num[-1] in irregularOrdinals:
num[-1] = delim + irregularOrdinals[num[-1]]
elif num[-1].endswith("y"):
num[-1] = delim + num[-1][:-1] + "ieth"
else:
num[-1] = delim + num[-1] + "th"
return "".join(num)
if __name__ == "__main__":
tests = "1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123 00123.0 1.23e2".split()
for num in tests:
print("{} => {}".format(num, num2ordinal(num)))
TENS = [None, None, "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"]
SMALL = ["zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"]
HUGE = [None, None] + [h + "illion"
for h in ("m", "b", "tr", "quadr", "quint", "sext",
"sept", "oct", "non", "dec")]
def nonzero(c, n, connect=''):
return "" if n == 0 else connect + c + spell_integer(n)
def last_and(num):
if ',' in num:
pre, last = num.rsplit(',', 1)
if ' and ' not in last:
last = ' and' + last
num = ''.join([pre, ',', last])
return num
def big(e, n):
if e == 0:
return spell_integer(n)
elif e == 1:
return spell_integer(n) + " thousand"
else:
return spell_integer(n) + " " + HUGE[e]
def base1000_rev(n):
while n != 0:
n, r = divmod(n, 1000)
yield r
def spell_integer(n):
if n < 0:
return "minus " + spell_integer(-n)
elif n < 20:
return SMALL[n]
elif n < 100:
a, b = divmod(n, 10)
return TENS[a] + nonzero("-", b)
elif n < 1000:
a, b = divmod(n, 100)
return SMALL[a] + " hundred" + nonzero(" ", b, ' and')
else:
num = ", ".join([big(e, x) for e, x in
enumerate(base1000_rev(n)) if x][::-1])
return last_and(num)
| 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 ) : "");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.