Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same algorithm in C# as shown in this Python implementation. | import random
class Card(object):
suits = ("Clubs","Hearts","Spades","Diamonds")
pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace")
def __init__(self, pip,suit):
self.pip=pip
self.suit=suit
def __str__(self):
return "%s %s"%(self.pip,self.suit)
class Deck(object):
def __init__(self):
self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]
def __str__(self):
return "[%s]"%", ".join( (str(card) for card in self.deck))
def shuffle(self):
random.shuffle(self.deck)
def deal(self):
self.shuffle()
return self.deck.pop(0)
| using System;
using System.Linq;
using System.Collections.Generic;
public struct Card
{
public Card(string rank, string suit) : this()
{
Rank = rank;
Suit = suit;
}
public string Rank { get; }
public string Suit { get; }
public override string ToString() => $"{Rank} of {Suit}";
}
public class Deck : IEnumerable<Card>
{
static readonly string[] ranks = { "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" };
static readonly string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
readonly List<Card> cards;
public Deck() {
cards = (from suit in suits
from rank in ranks
select new Card(rank, suit)).ToList();
}
public int Count => cards.Count;
public void Shuffle() {
var random = new Random();
for (int i = 0; i < cards.Count; i++) {
int r = random.Next(i, cards.Count);
var temp = cards[i];
cards[i] = cards[r];
cards[r] = temp;
}
}
public Card Deal() {
int last = cards.Count - 1;
Card card = cards[last];
cards.RemoveAt(last);
return card;
}
public IEnumerator<Card> GetEnumerator() {
for (int i = cards.Count - 1; i >= 0; i--)
yield return cards[i];
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
|
Port the provided Python code into C# while preserving the original functionality. | array = []
array.append(1)
array.append(3)
array[0] = 2
print array[0]
| int[] numbers = new int[10];
|
Ensure the translated C# code behaves exactly like the original Python snippet. | array = []
array.append(1)
array.append(3)
array[0] = 2
print array[0]
| int[] numbers = new int[10];
|
Translate this program into C# but keep the logic exactly as in Python. | def setup():
size(729, 729)
fill(0)
background(255)
noStroke()
rect(width / 3, height / 3, width / 3, width / 3)
rectangles(width / 3, height / 3, width / 3)
def rectangles(x, y, s):
if s < 1: return
xc, yc = x - s, y - s
for row in range(3):
for col in range(3):
if not (row == 1 and col == 1):
xx, yy = xc + row * s, yc + col * s
delta = s / 3
rect(xx + delta, yy + delta, delta, delta)
rectangles(xx + s / 3, yy + s / 3, s / 3)
| using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List<string> NextCarpet(List<string> carpet)
{
return carpet.Select(x => x + x + x)
.Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))
.Concat(carpet.Select(x => x + x + x)).ToList();
}
static List<string> SierpinskiCarpet(int n)
{
return Enumerable.Range(1, n).Aggregate(new List<string> { "#" }, (carpet, _) => NextCarpet(carpet));
}
static void Main(string[] args)
{
foreach (string s in SierpinskiCarpet(3))
Console.WriteLine(s);
}
}
|
Translate the given Python code snippet into C# without altering its behavior. | import random
def bogosort(l):
while not in_order(l):
random.shuffle(l)
return l
def in_order(l):
if not l:
return True
last = l[0]
for x in l[1:]:
if x < last:
return False
last = x
return True
| using System;
using System.Collections.Generic;
namespace RosettaCode.BogoSort
{
public static class BogoSorter
{
public static void Sort<T>(List<T> list) where T:IComparable
{
while (!list.isSorted())
{
list.Shuffle();
}
}
private static bool isSorted<T>(this IList<T> list) where T:IComparable
{
if(list.Count<=1)
return true;
for (int i = 1 ; i < list.Count; i++)
if(list[i].CompareTo(list[i-1])<0) return false;
return true;
}
private static void Shuffle<T>(this IList<T> list)
{
Random rand = new Random();
for (int i = 0; i < list.Count; i++)
{
int swapIndex = rand.Next(list.Count);
T temp = list[swapIndex];
list[swapIndex] = list[i];
list[i] = temp;
}
}
}
class TestProgram
{
static void Main()
{
List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };
BogoSorter.Sort(testList);
foreach (int i in testList) Console.Write(i + " ");
}
}
}
|
Change the following Python code into C# without altering its purpose. |
import pandas as pd
df_patients = pd.read_csv (r'patients.csv', sep = ",", decimal=".")
df_visits = pd.read_csv (r'visits.csv', sep = ",", decimal=".")
df_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])
df_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')
df_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False)
df_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']})
print(df_result)
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
public static class MergeAndAggregateDatasets
{
public static void Main()
{
string patientsCsv = @"
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz";
string visitsCsv = @"
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3";
string format = "yyyy-MM-dd";
var formatProvider = new DateTimeFormat(format).FormatProvider;
var patients = ParseCsv(
patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),
line => (PatientId: int.Parse(line[0]), LastName: line[1]));
var visits = ParseCsv(
visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),
line => (
PatientId: int.Parse(line[0]),
VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?),
Score: double.TryParse(line[2], out double score) ? score : default(double?)
)
);
var results =
patients.GroupJoin(visits,
p => p.PatientId,
v => v.PatientId,
(p, vs) => (
p.PatientId,
p.LastName,
LastVisit: vs.Max(v => v.VisitDate),
ScoreSum: vs.Sum(v => v.Score),
ScoreAvg: vs.Average(v => v.Score)
)
).OrderBy(r => r.PatientId);
Console.WriteLine("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |");
foreach (var r in results) {
Console.WriteLine($"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? "",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |");
}
}
private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor)
{
for (int i = 1; i < contents.Length; i++) {
var line = contents[i].Split(',');
yield return constructor(line);
}
}
}
|
Preserve the algorithm and functionality while converting the code from Python to C#. |
import pandas as pd
df_patients = pd.read_csv (r'patients.csv', sep = ",", decimal=".")
df_visits = pd.read_csv (r'visits.csv', sep = ",", decimal=".")
df_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])
df_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')
df_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False)
df_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']})
print(df_result)
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
public static class MergeAndAggregateDatasets
{
public static void Main()
{
string patientsCsv = @"
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz";
string visitsCsv = @"
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3";
string format = "yyyy-MM-dd";
var formatProvider = new DateTimeFormat(format).FormatProvider;
var patients = ParseCsv(
patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),
line => (PatientId: int.Parse(line[0]), LastName: line[1]));
var visits = ParseCsv(
visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),
line => (
PatientId: int.Parse(line[0]),
VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?),
Score: double.TryParse(line[2], out double score) ? score : default(double?)
)
);
var results =
patients.GroupJoin(visits,
p => p.PatientId,
v => v.PatientId,
(p, vs) => (
p.PatientId,
p.LastName,
LastVisit: vs.Max(v => v.VisitDate),
ScoreSum: vs.Sum(v => v.Score),
ScoreAvg: vs.Average(v => v.Score)
)
).OrderBy(r => r.PatientId);
Console.WriteLine("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |");
foreach (var r in results) {
Console.WriteLine($"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? "",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |");
}
}
private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor)
{
for (int i = 1; i < contents.Length; i++) {
var line = contents[i].Split(',');
yield return constructor(line);
}
}
}
|
Port the provided Python code into C# while preserving the original functionality. | def euler(f,y0,a,b,h):
t,y = a,y0
while t <= b:
print "%6.3f %6.3f" % (t,y)
t += h
y += h * f(t,y)
def newtoncooling(time, temp):
return -0.07 * (temp - 20)
euler(newtoncooling,100,0,100,10)
| using System;
namespace prog
{
class MainClass
{
const float T0 = 100f;
const float TR = 20f;
const float k = 0.07f;
readonly static float[] delta_t = {2.0f,5.0f,10.0f};
const int n = 100;
public delegate float func(float t);
static float NewtonCooling(float t)
{
return -k * (t-TR);
}
public static void Main (string[] args)
{
func f = new func(NewtonCooling);
for(int i=0; i<delta_t.Length; i++)
{
Console.WriteLine("delta_t = " + delta_t[i]);
Euler(f,T0,n,delta_t[i]);
}
}
public static void Euler(func f, float y, int n, float h)
{
for(float x=0; x<=n; x+=h)
{
Console.WriteLine("\t" + x + "\t" + y);
y += h * f(y);
}
}
}
}
|
Port the provided Python code into C# while preserving the original functionality. | >>> from math import floor, sqrt
>>> def non_square(n):
return n + floor(1/2 + sqrt(n))
>>>
>>> print(*map(non_square, range(1, 23)))
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
>>>
>>> def is_square(n):
return sqrt(n).is_integer()
>>> non_squares = map(non_square, range(1, 10 ** 6))
>>> next(filter(is_square, non_squares))
StopIteration Traceback (most recent call last)
<ipython-input-45-f32645fc1c0a> in <module>()
1 non_squares = map(non_square, range(1, 10 ** 6))
----> 2 next(filter(is_square, non_squares))
StopIteration:
| using System;
using System.Diagnostics;
namespace sons
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i < 23; i++)
Console.WriteLine(nonsqr(i));
for (int i = 1; i < 1000000; i++)
{
double j = Math.Sqrt(nonsqr(i));
Debug.Assert(j != Math.Floor(j),"Square");
}
}
static int nonsqr(int i)
{
return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));
}
}
}
|
Translate the given Python code snippet into C# without altering its behavior. | >>> s = 'abcdefgh'
>>> n, m, char, chars = 2, 3, 'd', 'cd'
>>>
>>> s[n-1:n+m-1]
'bcd'
>>>
>>> s[n-1:]
'bcdefgh'
>>>
>>> s[:-1]
'abcdefg'
>>>
>>> indx = s.index(char)
>>> s[indx:indx+m]
'def'
>>>
>>> indx = s.index(chars)
>>> s[indx:indx+m]
'cde'
>>>
| using System;
namespace SubString
{
class Program
{
static void Main(string[] args)
{
string s = "0123456789";
const int n = 3;
const int m = 2;
const char c = '3';
const string z = "345";
Console.WriteLine(s.Substring(n, m));
Console.WriteLine(s.Substring(n, s.Length - n));
Console.WriteLine(s.Substring(0, s.Length - 1));
Console.WriteLine(s.Substring(s.IndexOf(c), m));
Console.WriteLine(s.Substring(s.IndexOf(z), m));
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | >>> def jortsort(sequence):
return list(sequence) == sorted(sequence)
>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:
print(f'jortsort({repr(data)}) is {jortsort(data)}')
jortsort((1, 2, 4, 3)) is False
jortsort((14, 6, 8)) is False
jortsort(['a', 'c']) is True
jortsort(['s', 'u', 'x']) is True
jortsort('CVGH') is False
jortsort('PQRST') is True
>>>
| using System;
class Program
{
public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>
{
T[] originalArray = (T[]) array.Clone();
Array.Sort(array);
for (var i = 0; i < originalArray.Length; i++)
{
if (!Equals(originalArray[i], array[i]))
{
return false;
}
}
return true;
}
}
|
Translate this program into C# but keep the logic exactly as in Python. | import calendar
calendar.isleap(year)
| using System;
class Program
{
static void Main()
{
foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })
{
Console.WriteLine("{0} is {1}a leap year.",
year,
DateTime.IsLeapYear(year) ? string.Empty : "not ");
}
}
}
|
Produce a language-to-language conversion: from Python to C#, same semantics. | n=13
print(sorted(range(1,n+1), key=str))
| using static System.Console;
using static System.Linq.Enumerable;
public class Program
{
public static void Main() {
foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($"{n}: {string.Join(", ", LexOrder(n))}");
}
public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());
}
|
Translate the given Python code snippet into C# without altering its behavior. | 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)
if __name__ == '__main__':
for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):
print('%+4i -> %s' % (n, spell_integer(n)))
print('')
n = 201021002001
while n:
print('%-12i -> %s' % (n, spell_integer(n)))
n //= -10
print('%-12i -> %s' % (n, spell_integer(n)))
print('')
| using System;
class NumberNamer {
static readonly string[] incrementsOfOne =
{ "zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
static readonly string[] incrementsOfTen =
{ "", "", "twenty", "thirty", "fourty",
"fifty", "sixty", "seventy", "eighty", "ninety" };
const string millionName = "million",
thousandName = "thousand",
hundredName = "hundred",
andName = "and";
public static string GetName( int i ) {
string output = "";
if( i >= 1000000 ) {
output += ParseTriplet( i / 1000000 ) + " " + millionName;
i %= 1000000;
if( i == 0 ) return output;
}
if( i >= 1000 ) {
if( output.Length > 0 ) {
output += ", ";
}
output += ParseTriplet( i / 1000 ) + " " + thousandName;
i %= 1000;
if( i == 0 ) return output;
}
if( output.Length > 0 ) {
output += ", ";
}
output += ParseTriplet( i );
return output;
}
static string ParseTriplet( int i ) {
string output = "";
if( i >= 100 ) {
output += incrementsOfOne[i / 100] + " " + hundredName;
i %= 100;
if( i == 0 ) return output;
}
if( output.Length > 0 ) {
output += " " + andName + " ";
}
if( i >= 20 ) {
output += incrementsOfTen[i / 10];
i %= 10;
if( i == 0 ) return output;
}
if( output.Length > 0 ) {
output += " ";
}
output += incrementsOfOne[i];
return output;
}
}
class Program {
static void Main( string[] args ) {
Console.WriteLine( NumberNamer.GetName( 1 ) );
Console.WriteLine( NumberNamer.GetName( 234 ) );
Console.WriteLine( NumberNamer.GetName( 31337 ) );
Console.WriteLine( NumberNamer.GetName( 987654321 ) );
}
}
|
Preserve the algorithm and functionality while converting the code from Python to C#. | A = 'I am string'
B = 'I am string too'
if len(A) > len(B):
print('"' + A + '"', 'has length', len(A), 'and is the longest of the two strings')
print('"' + B + '"', 'has length', len(B), 'and is the shortest of the two strings')
elif len(A) < len(B):
print('"' + B + '"', 'has length', len(B), 'and is the longest of the two strings')
print('"' + A + '"', 'has length', len(A), 'and is the shortest of the two strings')
else:
print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string')
print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')
| using System;
using System.Collections.Generic;
namespace example
{
class Program
{
static void Main(string[] args)
{
var strings = new string[] { "abcd", "123456789", "abcdef", "1234567" };
compareAndReportStringsLength(strings);
}
private static void compareAndReportStringsLength(string[] strings)
{
if (strings.Length > 0)
{
char Q = '"';
string hasLength = " has length ";
string predicateMax = " and is the longest string";
string predicateMin = " and is the shortest string";
string predicateAve = " and is neither the longest nor the shortest string";
string predicate;
(int, int)[] li = new (int, int)[strings.Length];
for (int i = 0; i < strings.Length; i++)
li[i] = (strings[i].Length, i);
Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);
int maxLength = li[0].Item1;
int minLength = li[strings.Length - 1].Item1;
for (int i = 0; i < strings.Length; i++)
{
int length = li[i].Item1;
string str = strings[li[i].Item2];
if (length == maxLength)
predicate = predicateMax;
else if (length == minLength)
predicate = predicateMin;
else
predicate = predicateAve;
Console.WriteLine(Q + str + Q + hasLength + length + predicate);
}
}
}
}
}
|
Preserve the algorithm and functionality while converting the code from Python to C#. | import collections, sys
def filecharcount(openfile):
return sorted(collections.Counter(c for l in openfile for c in l).items())
f = open(sys.argv[1])
print(filecharcount(f))
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Program
{
static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)
{
var dictionary = new SortedDictionary<TItem, int>();
foreach (var item in items)
{
if (dictionary.ContainsKey(item))
{
dictionary[item]++;
}
else
{
dictionary[item] = 1;
}
}
return dictionary;
}
static void Main(string[] arguments)
{
var file = arguments.FirstOrDefault();
if (File.Exists(file))
{
var text = File.ReadAllText(file);
foreach (var entry in GetFrequencies(text))
{
Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
}
}
}
}
|
Please provide an equivalent version of this Python code in C#. | next = str(int('123') + 1)
| string s = "12345";
s = (int.Parse(s) + 1).ToString();
using System.Numerics;
string bis = "123456789012345678999999999";
bis = (BigInteger.Parse(bis) + 1).ToString();
|
Change the programming language of this snippet from Python to C# without modifying what it does. | >>> def stripchars(s, chars):
... return s.translate(None, chars)
...
>>> stripchars("She was a soul stripper. She took my heart!", "aei")
'Sh ws soul strppr. Sh took my hrt!'
| using System;
public static string RemoveCharactersFromString(string testString, string removeChars)
{
char[] charAry = removeChars.ToCharArray();
string returnString = testString;
foreach (char c in charAry)
{
while (returnString.IndexOf(c) > -1)
{
returnString = returnString.Remove(returnString.IndexOf(c), 1);
}
}
return returnString;
}
|
Produce a functionally identical C# code for the snippet given in Python. | from math import fsum
def average(x):
return fsum(x)/float(len(x)) if x else 0
print (average([0,0,3,1,4,1,5,9,0,0]))
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
| using System;
using System.Linq;
class Program
{
static void Main()
{
Console.WriteLine(new[] { 1, 2, 3 }.Average());
}
}
|
Can you help me rewrite this code in C# instead of Python, keeping it the same logically? | from __future__ import division
import math
def hist(source):
hist = {}; l = 0;
for e in source:
l += 1
if e not in hist:
hist[e] = 0
hist[e] += 1
return (l,hist)
def entropy(hist,l):
elist = []
for v in hist.values():
c = v / l
elist.append(-c * math.log(c ,2))
return sum(elist)
def printHist(h):
flip = lambda (k,v) : (v,k)
h = sorted(h.iteritems(), key = flip)
print 'Sym\thi\tfi\tInf'
for (k,v) in h:
print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2))
source = "1223334444"
(l,h) = hist(source);
print '.[Results].'
print 'Length',l
print 'Entropy:', entropy(h, l)
printHist(h)
| using System;
using System.Collections.Generic;
namespace Entropy
{
class Program
{
public static double logtwo(double num)
{
return Math.Log(num)/Math.Log(2);
}
public static void Main(string[] args)
{
label1:
string input = Console.ReadLine();
double infoC=0;
Dictionary<char,double> table = new Dictionary<char, double>();
foreach (char c in input)
{
if (table.ContainsKey(c))
table[c]++;
else
table.Add(c,1);
}
double freq;
foreach (KeyValuePair<char,double> letter in table)
{
freq=letter.Value/input.Length;
infoC+=freq*logtwo(freq);
}
infoC*=-1;
Console.WriteLine("The Entropy of {0} is {1}",input,infoC);
goto label1;
}
}
}
|
Convert the following code from Python to C#, ensuring the logic remains intact. | def token_with_escape(a, escape = '^', separator = '|'):
result = []
token = ''
state = 0
for c in a:
if state == 0:
if c == escape:
state = 1
elif c == separator:
result.append(token)
token = ''
else:
token += c
elif state == 1:
token += c
state = 0
result.append(token)
return result
| using System;
using System.Text;
using System.Collections.Generic;
public class TokenizeAStringWithEscaping
{
public static void Main() {
string testcase = "one^|uno||three^^^^|four^^^|^cuatro|";
foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {
Console.WriteLine(": " + token);
}
}
}
public static class Extensions
{
public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {
if (input == null) yield break;
var buffer = new StringBuilder();
bool escaping = false;
foreach (char c in input) {
if (escaping) {
buffer.Append(c);
escaping = false;
} else if (c == escape) {
escaping = true;
} else if (c == separator) {
yield return buffer.Flush();
} else {
buffer.Append(c);
}
}
if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();
}
public static string Flush(this StringBuilder stringBuilder) {
string result = stringBuilder.ToString();
stringBuilder.Clear();
return result;
}
}
|
Preserve the algorithm and functionality while converting the code from Python to C#. | print "Hello world!"
| Using System;
namespace HelloWorld {
class Program
{
static void Main()
{
Console.Writeln("Hello World!");
}
}
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Python version. | print "Hello world!"
| Using System;
namespace HelloWorld {
class Program
{
static void Main()
{
Console.Writeln("Hello World!");
}
}
}
|
Produce a functionally identical C# code for the snippet given in Python. | >>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]
>>>
>>> difn = lambda s, n: difn(dif(s), n-1) if n else s
>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
>>> difn(s, 0)
[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
>>> difn(s, 1)
[-43, 11, -29, -7, 10, 23, -50, 50, 18]
>>> difn(s, 2)
[54, -40, 22, 17, 13, -73, 100, -32]
>>> from pprint import pprint
>>> pprint( [difn(s, i) for i in xrange(10)] )
[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],
[-43, 11, -29, -7, 10, 23, -50, 50, 18],
[54, -40, 22, 17, 13, -73, 100, -32],
[-94, 62, -5, -4, -86, 173, -132],
[156, -67, 1, -82, 259, -305],
[-223, 68, -83, 341, -564],
[291, -151, 424, -905],
[-442, 575, -1329],
[1017, -1904],
[-2921]]
| using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)
{
switch (order)
{
case 0u:
return sequence;
case 1u:
return sequence.Skip(1).Zip(sequence, (next, current) => next - current);
default:
return ForwardDifference(ForwardDifference(sequence), order - 1u);
}
}
static void Main()
{
IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };
do
{
Console.WriteLine(string.Join(", ", sequence));
} while ((sequence = ForwardDifference(sequence)).Any());
}
}
|
Convert this Python block to C#, preserving its control flow and logic. | def prime(a):
return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
| static bool isPrime(int n)
{
if (n <= 1) return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0) return false;
return true;
}
|
Convert the following code from Python to C#, ensuring the logic remains intact. | def prime(a):
return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
| static bool isPrime(int n)
{
if (n <= 1) return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0) return false;
return true;
}
|
Port the following code from Python to C# with equivalent syntax and logic. | def binomialCoeff(n, k):
result = 1
for i in range(1, k+1):
result = result * (n-i+1) / i
return result
if __name__ == "__main__":
print(binomialCoeff(5, 3))
| using System;
namespace BinomialCoefficients
{
class Program
{
static void Main(string[] args)
{
ulong n = 1000000, k = 3;
ulong result = biCoefficient(n, k);
Console.WriteLine("The Binomial Coefficient of {0}, and {1}, is equal to: {2}", n, k, result);
Console.ReadLine();
}
static int fact(int n)
{
if (n == 0) return 1;
else return n * fact(n - 1);
}
static ulong biCoefficient(ulong n, ulong k)
{
if (k > n - k)
{
k = n - k;
}
ulong c = 1;
for (uint i = 0; i < k; i++)
{
c = c * (n - i);
c = c / (i + 1);
}
return c;
}
}
}
|
Generate an equivalent C# version of this Python code. | collection = [0, '1']
x = collection[0]
collection.append(2)
collection.insert(0, '-1')
y = collection[0]
collection.extend([2,'3'])
collection += [2,'3']
collection[2:6]
len(collection)
collection = (0, 1)
collection[:]
collection[-4:-1]
collection[::2]
collection="some string"
x = collection[::-1]
collection[::2] == "some string"[::2]
collection.__getitem__(slice(0,len(collection),2))
collection = {0: "zero", 1: "one"}
collection['zero'] = 2
collection = set([0, '1'])
|
int[] intArray = new int[5] { 1, 2, 3, 4, 5 };
int[] intArray = new int[]{ 1, 2, 3, 4, 5 };
int[] intArray = { 1, 2, 3, 4, 5 };
string[] stringArr = new string[5];
stringArr[0] = "string";
|
Port the provided Python code into C# while preserving the original functionality. | for node in lst:
print node.value
| var current = [head of list to traverse]
while(current != null)
{
current = current.Next;
}
|
Convert this Python snippet to C# and keep its semantics consistent. |
import io
ppmfileout = io.StringIO('')
def writeppmp3(self, f):
self.writeppm(f, ppmformat='P3')
def writeppm(self, f, ppmformat='P6'):
assert ppmformat in ['P3', 'P6'], 'Format wrong'
magic = ppmformat + '\n'
comment = '
maxval = max(max(max(bit) for bit in row) for row in self.map)
assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'
if ppmformat == 'P6':
fwrite = lambda s: f.write(bytes(s, 'UTF-8'))
maxval = 255
else:
fwrite = f.write
numsize=len(str(maxval))
fwrite(magic)
fwrite(comment)
fwrite('%i %i\n%i\n' % (self.width, self.height, maxval))
for h in range(self.height-1, -1, -1):
for w in range(self.width):
r, g, b = self.get(w, h)
if ppmformat == 'P3':
fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))
else:
fwrite('%c%c%c' % (r, g, b))
if ppmformat == 'P3':
fwrite('\n')
Bitmap.writeppmp3 = writeppmp3
Bitmap.writeppm = writeppm
bitmap = Bitmap(4, 4, black)
bitmap.fillrect(1, 0, 1, 2, white)
bitmap.set(3, 3, Colour(127, 0, 63))
bitmap.writeppmp3(ppmfileout)
print(ppmfileout.getvalue())
ppmfileout = open('tmp.ppm', 'wb')
bitmap.writeppm(ppmfileout)
ppmfileout.close()
| using System;
using System.IO;
class PPMWriter
{
public static void WriteBitmapToPPM(string file, Bitmap bitmap)
{
var writer = new StreamWriter(file);
writer.WriteLine("P6");
writer.WriteLine($"{bitmap.Width} {bitmap.Height}");
writer.WriteLine("255");
writer.Close();
var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));
for (int x = 0; x < bitmap.Height; x++)
for (int y = 0; y < bitmap.Width; y++)
{
Color color = bitmap.GetPixel(y, x);
writerB.Write(color.R);
writerB.Write(color.G);
writerB.Write(color.B);
}
writerB.Close();
}
}
|
Convert this Python snippet to C# and keep its semantics consistent. | import os
os.remove("output.txt")
os.rmdir("docs")
os.remove("/output.txt")
os.rmdir("/docs")
| using System;
using System.IO;
namespace DeleteFile {
class Program {
static void Main() {
File.Delete("input.txt");
Directory.Delete("docs");
File.Delete("/input.txt");
Directory.Delete("/docs");
}
}
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Python version. | import datetime, calendar
DISCORDIAN_SEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"]
def ddate(year, month, day):
today = datetime.date(year, month, day)
is_leap_year = calendar.isleap(year)
if is_leap_year and month == 2 and day == 29:
return "St. Tib's Day, YOLD " + (year + 1166)
day_of_year = today.timetuple().tm_yday - 1
if is_leap_year and day_of_year >= 60:
day_of_year -= 1
season, dday = divmod(day_of_year, 73)
return "%s %d, YOLD %d" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)
| using System;
public static class DiscordianDate
{
static readonly string[] seasons = { "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath" };
static readonly string[] weekdays = { "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange" };
static readonly string[] apostles = { "Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay" };
static readonly string[] holidays = { "Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux" };
public static string Discordian(this DateTime date) {
string yold = $" in the YOLD {date.Year + 1166}.";
int dayOfYear = date.DayOfYear;
if (DateTime.IsLeapYear(date.Year)) {
if (dayOfYear == 60) return "St. Tib's day" + yold;
else if (dayOfYear > 60) dayOfYear--;
}
dayOfYear--;
int seasonDay = dayOfYear % 73 + 1;
int seasonNr = dayOfYear / 73;
int weekdayNr = dayOfYear % 5;
string holyday = "";
if (seasonDay == 5) holyday = $" Celebrate {apostles[seasonNr]}!";
else if (seasonDay == 50) holyday = $" Celebrate {holidays[seasonNr]}!";
return $"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}";
}
public static void Main() {
foreach (var (day, month, year) in new [] {
(1, 1, 2010),
(5, 1, 2010),
(19, 2, 2011),
(28, 2, 2012),
(29, 2, 2012),
(1, 3, 2012),
(19, 3, 2013),
(3, 5, 2014),
(31, 5, 2015),
(22, 6, 2016),
(15, 7, 2016),
(12, 8, 2017),
(19, 9, 2018),
(26, 9, 2018),
(24, 10, 2019),
(8, 12, 2020),
(31, 12, 2020)
})
{
Console.WriteLine($"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}");
}
}
}
|
Convert this Python snippet to C# and keep its semantics consistent. | from __future__ import division
from math import factorial
from random import randrange
MAX_N = 20
TIMES = 1000000
def analytical(n):
return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))
def test(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
if __name__ == '__main__':
print(" n\tavg\texp.\tdiff\n-------------------------------")
for n in range(1, MAX_N+1):
avg = test(n, TIMES)
theory = analytical(n)
diff = (avg / theory - 1) * 100
print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))
| public class AverageLoopLength {
private static int N = 100000;
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] powers = new double[n + 1];
powers[0] = 1.0;
factorial[0] = 1.0;
for (int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
powers[i] = powers[i - 1] * n;
}
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial[n] / factorial[n - i] / powers[i];
}
return sum;
}
private static double average(int n) {
Random rnd = new Random();
double sum = 0.0;
for (int a = 0; a < N; a++) {
int[] random = new int[n];
for (int i = 0; i < n; i++) {
random[i] = rnd.Next(n);
}
var seen = new HashSet<double>(n);
int current = 0;
int length = 0;
while (seen.Add(current)) {
length++;
current = random[current];
}
sum += length;
}
return sum / N;
}
public static void Main(string[] args) {
Console.WriteLine(" N average analytical (error)");
Console.WriteLine("=== ========= ============ =========");
for (int i = 1; i <= 20; i++) {
var average = AverageLoopLength.average(i);
var analytical = AverageLoopLength.analytical(i);
Console.WriteLine("{0,3} {1,10:N4} {2,13:N4} {3,8:N2}%", i, average, analytical, (analytical - average) / analytical * 100);
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. | from __future__ import division
from math import factorial
from random import randrange
MAX_N = 20
TIMES = 1000000
def analytical(n):
return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))
def test(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
if __name__ == '__main__':
print(" n\tavg\texp.\tdiff\n-------------------------------")
for n in range(1, MAX_N+1):
avg = test(n, TIMES)
theory = analytical(n)
diff = (avg / theory - 1) * 100
print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))
| public class AverageLoopLength {
private static int N = 100000;
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] powers = new double[n + 1];
powers[0] = 1.0;
factorial[0] = 1.0;
for (int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
powers[i] = powers[i - 1] * n;
}
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial[n] / factorial[n - i] / powers[i];
}
return sum;
}
private static double average(int n) {
Random rnd = new Random();
double sum = 0.0;
for (int a = 0; a < N; a++) {
int[] random = new int[n];
for (int i = 0; i < n; i++) {
random[i] = rnd.Next(n);
}
var seen = new HashSet<double>(n);
int current = 0;
int length = 0;
while (seen.Add(current)) {
length++;
current = random[current];
}
sum += length;
}
return sum / N;
}
public static void Main(string[] args) {
Console.WriteLine(" N average analytical (error)");
Console.WriteLine("=== ========= ============ =========");
for (int i = 1; i <= 20; i++) {
var average = AverageLoopLength.average(i);
var analytical = AverageLoopLength.analytical(i);
Console.WriteLine("{0,3} {1,10:N4} {2,13:N4} {3,8:N2}%", i, average, analytical, (analytical - average) / analytical * 100);
}
}
}
|
Preserve the algorithm and functionality while converting the code from Python to C#. | >>> original = 'Mary had a %s lamb.'
>>> extra = 'little'
>>> original % extra
'Mary had a little lamb.'
| class Program
{
static void Main()
{
string extra = "little";
string formatted = $"Mary had a {extra} lamb.";
System.Console.WriteLine(formatted);
}
}
|
Generate a C# translation of this Python snippet without changing its computational steps. | from itertools import islice
def posd():
"diff between position numbers. 1, 2, 3... interleaved with 3, 5, 7..."
count, odd = 1, 3
while True:
yield count
yield odd
count, odd = count + 1, odd + 2
def pos_gen():
"position numbers. 1 3 2 5 7 4 9 ..."
val = 1
diff = posd()
while True:
yield val
val += next(diff)
def plus_minus():
"yield (list_offset, sign) or zero for Partition calc"
n, sign = 0, [1, 1]
p_gen = pos_gen()
out_on = next(p_gen)
while True:
n += 1
if n == out_on:
next_sign = sign.pop(0)
if not sign:
sign = [-next_sign] * 2
yield -n, next_sign
out_on = next(p_gen)
else:
yield 0
def part(n):
"Partition numbers"
p = [1]
p_m = plus_minus()
mods = []
for _ in range(n):
next_plus_minus = next(p_m)
if next_plus_minus:
mods.append(next_plus_minus)
p.append(sum(p[offset] * sign for offset, sign in mods))
return p[-1]
print("(Intermediaries):")
print(" posd:", list(islice(posd(), 10)))
print(" pos_gen:", list(islice(pos_gen(), 10)))
print(" plus_minus:", list(islice(plus_minus(), 15)))
print("\nPartitions:", [part(x) for x in range(15)])
| using System;
class Program {
const long Lm = (long)1e18;
const string Fm = "D18";
struct LI { public long lo, ml, mh, hi, tp; }
static void inc(ref LI d, LI s) {
if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }
if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }
if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }
if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }
d.tp += s.tp;
}
static void dec(ref LI d, LI s) {
if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }
if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }
if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }
if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }
d.tp -= s.tp;
}
static LI set(long s) { LI d;
d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }
static string fmt(LI x) {
if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);
if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);
if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);
if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);
return x.lo.ToString();
}
static LI partcount(int n) {
var P = new LI[n + 1]; P[0] = set(1);
for (int i = 1; i <= n; i++) {
int k = 0, d = -2, j = i;
LI x = set(0);
while (true) {
if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;
if ((j -= ++k) >= 0) inc(ref x, P[j]); else break;
if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;
if ((j -= ++k) >= 0) dec(ref x, P[j]); else break;
}
P[i] = x;
}
return P[n];
}
static void Main(string[] args) {
var sw = System.Diagnostics.Stopwatch.StartNew ();
var res = partcount(6666); sw.Stop();
Console.Write("{0} {1} ms", fmt(res), sw.Elapsed.TotalMilliseconds);
}
}
|
Translate this program into C# but keep the logic exactly as in Python. | from collections import deque
def prime_digits_sum(r):
q = deque([(r, 0)])
while q:
r, n = q.popleft()
for d in 2, 3, 5, 7:
if d >= r:
if d == r: yield n + d
break
q.append((r - d, (n + d) * 10))
print(*prime_digits_sum(13))
| using System;
using static System.Console;
using LI = System.Collections.Generic.SortedSet<int>;
class Program {
static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {
if (lft == 0) res.Add(vlu);
else if (lft > 0) foreach (int itm in set)
res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);
return res; }
static void Main(string[] args) { WriteLine(string.Join(" ",
unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }
}
|
Write a version of this Python function in C# with identical behavior. | from collections import deque
def prime_digits_sum(r):
q = deque([(r, 0)])
while q:
r, n = q.popleft()
for d in 2, 3, 5, 7:
if d >= r:
if d == r: yield n + d
break
q.append((r - d, (n + d) * 10))
print(*prime_digits_sum(13))
| using System;
using static System.Console;
using LI = System.Collections.Generic.SortedSet<int>;
class Program {
static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {
if (lft == 0) res.Add(vlu);
else if (lft > 0) foreach (int itm in set)
res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);
return res; }
static void Main(string[] args) { WriteLine(string.Join(" ",
unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }
}
|
Convert the following code from Python to C#, ensuring the logic remains intact. | from collections import deque
def prime_digits_sum(r):
q = deque([(r, 0)])
while q:
r, n = q.popleft()
for d in 2, 3, 5, 7:
if d >= r:
if d == r: yield n + d
break
q.append((r - d, (n + d) * 10))
print(*prime_digits_sum(13))
| using System;
using static System.Console;
using LI = System.Collections.Generic.SortedSet<int>;
class Program {
static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {
if (lft == 0) res.Add(vlu);
else if (lft > 0) foreach (int itm in set)
res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);
return res; }
static void Main(string[] args) { WriteLine(string.Join(" ",
unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }
}
|
Transform the following Python implementation into C#, maintaining the same output and logic. | import sys, datetime, shutil
if len(sys.argv) == 1:
try:
with open('notes.txt', 'r') as f:
shutil.copyfileobj(f, sys.stdout)
except IOError:
pass
else:
with open('notes.txt', 'a') as f:
f.write(datetime.datetime.now().isoformat() + '\n')
f.write("\t%s\n" % ' '.join(sys.argv[1:]))
| using System;
using System.IO;
using System.Text;
namespace RosettaCode
{
internal class Program
{
private const string FileName = "NOTES.TXT";
private static void Main(string[] args)
{
if (args.Length==0)
{
string txt = File.ReadAllText(FileName);
Console.WriteLine(txt);
}
else
{
var sb = new StringBuilder();
sb.Append(DateTime.Now).Append("\n\t");
foreach (string s in args)
sb.Append(s).Append(" ");
sb.Append("\n");
if (File.Exists(FileName))
File.AppendAllText(FileName, sb.ToString());
else
File.WriteAllText(FileName, sb.ToString());
}
}
}
}
|
Produce a language-to-language conversion: from Python to C#, same semantics. | PI = 3.141592653589793
TWO_PI = 6.283185307179586
def normalize2deg(a):
while a < 0: a += 360
while a >= 360: a -= 360
return a
def normalize2grad(a):
while a < 0: a += 400
while a >= 400: a -= 400
return a
def normalize2mil(a):
while a < 0: a += 6400
while a >= 6400: a -= 6400
return a
def normalize2rad(a):
while a < 0: a += TWO_PI
while a >= TWO_PI: a -= TWO_PI
return a
def deg2grad(a): return a * 10.0 / 9.0
def deg2mil(a): return a * 160.0 / 9.0
def deg2rad(a): return a * PI / 180.0
def grad2deg(a): return a * 9.0 / 10.0
def grad2mil(a): return a * 16.0
def grad2rad(a): return a * PI / 200.0
def mil2deg(a): return a * 9.0 / 160.0
def mil2grad(a): return a / 16.0
def mil2rad(a): return a * PI / 3200.0
def rad2deg(a): return a * 180.0 / PI
def rad2grad(a): return a * 200.0 / PI
def rad2mil(a): return a * 3200.0 / PI
| using System;
public static class Angles
{
public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000);
public static void Print(params double[] angles) {
string[] names = { "Degrees", "Gradians", "Mils", "Radians" };
Func<double, double> rnd = a => Math.Round(a, 4);
Func<double, double>[] normal = { NormalizeDeg, NormalizeGrad, NormalizeMil, NormalizeRad };
Func<double, double>[,] convert = {
{ a => a, DegToGrad, DegToMil, DegToRad },
{ GradToDeg, a => a, GradToMil, GradToRad },
{ MilToDeg, MilToGrad, a => a, MilToRad },
{ RadToDeg, RadToGrad, RadToMil, a => a }
};
Console.WriteLine($@"{"Angle",-12}{"Normalized",-12}{"Unit",-12}{
"Degrees",-12}{"Gradians",-12}{"Mils",-12}{"Radians",-12}");
foreach (double angle in angles) {
for (int i = 0; i < 4; i++) {
double nAngle = normal[i](angle);
Console.WriteLine($@"{
rnd(angle),-12}{
rnd(nAngle),-12}{
names[i],-12}{
rnd(convert[i, 0](nAngle)),-12}{
rnd(convert[i, 1](nAngle)),-12}{
rnd(convert[i, 2](nAngle)),-12}{
rnd(convert[i, 3](nAngle)),-12}");
}
}
}
public static double NormalizeDeg(double angle) => Normalize(angle, 360);
public static double NormalizeGrad(double angle) => Normalize(angle, 400);
public static double NormalizeMil(double angle) => Normalize(angle, 6400);
public static double NormalizeRad(double angle) => Normalize(angle, 2 * Math.PI);
private static double Normalize(double angle, double N) {
while (angle <= -N) angle += N;
while (angle >= N) angle -= N;
return angle;
}
public static double DegToGrad(double angle) => angle * 10 / 9;
public static double DegToMil(double angle) => angle * 160 / 9;
public static double DegToRad(double angle) => angle * Math.PI / 180;
public static double GradToDeg(double angle) => angle * 9 / 10;
public static double GradToMil(double angle) => angle * 16;
public static double GradToRad(double angle) => angle * Math.PI / 200;
public static double MilToDeg(double angle) => angle * 9 / 160;
public static double MilToGrad(double angle) => angle / 16;
public static double MilToRad(double angle) => angle * Math.PI / 3200;
public static double RadToDeg(double angle) => angle * 180 / Math.PI;
public static double RadToGrad(double angle) => angle * 200 / Math.PI;
public static double RadToMil(double angle) => angle * 3200 / Math.PI;
}
|
Translate this program into C# but keep the logic exactly as in Python. | >>> import os
>>> os.path.commonpath(['/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp'
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RosettaCodeTasks
{
class Program
{
static void Main ( string[ ] args )
{
FindCommonDirectoryPath.Test ( );
}
}
class FindCommonDirectoryPath
{
public static void Test ( )
{
Console.WriteLine ( "Find Common Directory Path" );
Console.WriteLine ( );
List<string> PathSet1 = new List<string> ( );
PathSet1.Add ( "/home/user1/tmp/coverage/test" );
PathSet1.Add ( "/home/user1/tmp/covert/operator" );
PathSet1.Add ( "/home/user1/tmp/coven/members" );
Console.WriteLine("Path Set 1 (All Absolute Paths):");
foreach ( string path in PathSet1 )
{
Console.WriteLine ( path );
}
Console.WriteLine ( "Path Set 1 Common Path: {0}", FindCommonPath ( "/", PathSet1 ) );
}
public static string FindCommonPath ( string Separator, List<string> Paths )
{
string CommonPath = String.Empty;
List<string> SeparatedPath = Paths
.First ( str => str.Length == Paths.Max ( st2 => st2.Length ) )
.Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries )
.ToList ( );
foreach ( string PathSegment in SeparatedPath.AsEnumerable ( ) )
{
if ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) )
{
CommonPath = PathSegment;
}
else if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) )
{
CommonPath += Separator + PathSegment;
}
else
{
break;
}
}
return CommonPath;
}
}
}
|
Write the same algorithm in C# as shown in this Python implementation. | from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
yield nxt
while True:
an1, n = nxt, n + 1
nxt = an1 - n
if nxt < 0 or nxt in a:
nxt = an1 + n
a.add(nxt)
self.n = n
yield nxt
if __name__ == '__main__':
recamans = Recamans()
print("First fifteen members of Recamans sequence:",
list(islice(recamans(), 15)))
so_far = set()
for term in recamans():
if term in so_far:
print(f"First duplicate number in series is: a({recamans.n}) = {term}")
break
so_far.add(term)
n = 1_000
setn = set(range(n + 1))
for _ in recamans():
if setn.issubset(recamans.a):
print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
break
| using System;
using System.Collections.Generic;
namespace RecamanSequence {
class Program {
static void Main(string[] args) {
List<int> a = new List<int>() { 0 };
HashSet<int> used = new HashSet<int>() { 0 };
HashSet<int> used1000 = new HashSet<int>() { 0 };
bool foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.Count < 1001) {
int next = a[n - 1] - n;
if (next < 1 || used.Contains(next)) {
next += 2 * n;
}
bool alreadyUsed = used.Contains(next);
a.Add(next);
if (!alreadyUsed) {
used.Add(next);
if (0 <= next && next <= 1000) {
used1000.Add(next);
}
}
if (n == 14) {
Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a));
}
if (!foundDup && alreadyUsed) {
Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next);
foundDup = true;
}
if (used1000.Count == 1001) {
Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n);
}
n++;
}
}
}
}
|
Write the same algorithm in C# as shown in this Python implementation. | from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
yield nxt
while True:
an1, n = nxt, n + 1
nxt = an1 - n
if nxt < 0 or nxt in a:
nxt = an1 + n
a.add(nxt)
self.n = n
yield nxt
if __name__ == '__main__':
recamans = Recamans()
print("First fifteen members of Recamans sequence:",
list(islice(recamans(), 15)))
so_far = set()
for term in recamans():
if term in so_far:
print(f"First duplicate number in series is: a({recamans.n}) = {term}")
break
so_far.add(term)
n = 1_000
setn = set(range(n + 1))
for _ in recamans():
if setn.issubset(recamans.a):
print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
break
| using System;
using System.Collections.Generic;
namespace RecamanSequence {
class Program {
static void Main(string[] args) {
List<int> a = new List<int>() { 0 };
HashSet<int> used = new HashSet<int>() { 0 };
HashSet<int> used1000 = new HashSet<int>() { 0 };
bool foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.Count < 1001) {
int next = a[n - 1] - n;
if (next < 1 || used.Contains(next)) {
next += 2 * n;
}
bool alreadyUsed = used.Contains(next);
a.Add(next);
if (!alreadyUsed) {
used.Add(next);
if (0 <= next && next <= 1000) {
used1000.Add(next);
}
}
if (n == 14) {
Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a));
}
if (!foundDup && alreadyUsed) {
Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next);
foundDup = true;
}
if (used1000.Count == 1001) {
Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n);
}
n++;
}
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. | >>> from array import array
>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'),
('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]
>>> for typecode, initializer in argslist:
a = array(typecode, initializer)
print a
del a
array('l')
array('c', 'hello world')
array('u', u'hello \u2641')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.1400000000000001])
>>>
| using System;
using System.Runtime.InteropServices;
public unsafe class Program
{
public static unsafe void HeapMemory()
{
const int HEAP_ZERO_MEMORY = 0x00000008;
const int size = 1000;
int ph = GetProcessHeap();
void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);
if (pointer == null)
throw new OutOfMemoryException();
Console.WriteLine(HeapSize(ph, 0, pointer));
HeapFree(ph, 0, pointer);
}
public static unsafe void StackMemory()
{
byte* buffer = stackalloc byte[1000];
}
public static void Main(string[] args)
{
HeapMemory();
StackMemory();
}
[DllImport("kernel32")]
static extern void* HeapAlloc(int hHeap, int flags, int size);
[DllImport("kernel32")]
static extern bool HeapFree(int hHeap, int flags, void* block);
[DllImport("kernel32")]
static extern int GetProcessHeap();
[DllImport("kernel32")]
static extern int HeapSize(int hHeap, int flags, void* block);
}
|
Port the following code from Python to C# with equivalent syntax and logic. |
import random
board = list('123456789')
wins = ((0,1,2), (3,4,5), (6,7,8),
(0,3,6), (1,4,7), (2,5,8),
(0,4,8), (2,4,6))
def printboard():
print('\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))
def score():
for w in wins:
b = board[w[0]]
if b in 'XO' and all (board[i] == b for i in w):
return b, [i+1 for i in w]
return None, None
def finished():
return all (b in 'XO' for b in board)
def space():
return [ b for b in board if b not in 'XO']
def my_turn(xo):
options = space()
choice = random.choice(options)
board[int(choice)-1] = xo
return choice
def your_turn(xo):
options = space()
while True:
choice = input(" Put your %s in any of these positions: %s "
% (xo, ''.join(options))).strip()
if choice in options:
break
print( "Whoops I don't understand the input" )
board[int(choice)-1] = xo
return choice
def me(xo='X'):
printboard()
print('I go at', my_turn(xo))
return score()
assert not s[0], "\n%s wins across %s" % s
def you(xo='O'):
printboard()
print('You went at', your_turn(xo))
return score()
assert not s[0], "\n%s wins across %s" % s
print(__doc__)
while not finished():
s = me('X')
if s[0]:
printboard()
print("\n%s wins across %s" % s)
break
if not finished():
s = you('O')
if s[0]:
printboard()
print("\n%s wins across %s" % s)
break
else:
print('\nA draw')
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RosettaTicTacToe
{
class Program
{
static string[][] Players = new string[][] {
new string[] { "COMPUTER", "X" },
new string[] { "HUMAN", "O" }
};
const int Unplayed = -1;
const int Computer = 0;
const int Human = 1;
static int[] GameBoard = new int[9];
static int[] corners = new int[] { 0, 2, 6, 8 };
static int[][] wins = new int[][] {
new int[] { 0, 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8 },
new int[] { 0, 3, 6 }, new int[] { 1, 4, 7 }, new int[] { 2, 5, 8 },
new int[] { 0, 4, 8 }, new int[] { 2, 4, 6 } };
static void Main(string[] args)
{
while (true)
{
Console.Clear();
Console.WriteLine("Welcome to Rosetta Code Tic-Tac-Toe for C#.");
initializeGameBoard();
displayGameBoard();
int currentPlayer = rnd.Next(0, 2);
Console.WriteLine("The first move goes to {0} who is playing {1}s.\n", playerName(currentPlayer), playerToken(currentPlayer));
while (true)
{
int thisMove = getMoveFor(currentPlayer);
if (thisMove == Unplayed)
{
Console.WriteLine("{0}, you've quit the game ... am I that good?", playerName(currentPlayer));
break;
}
playMove(thisMove, currentPlayer);
displayGameBoard();
if (isGameWon())
{
Console.WriteLine("{0} has won the game!", playerName(currentPlayer));
break;
}
else if (isGameTied())
{
Console.WriteLine("Cat game ... we have a tie.");
break;
}
currentPlayer = getNextPlayer(currentPlayer);
}
if (!playAgain())
return;
}
}
static int getMoveFor(int player)
{
if (player == Human)
return getManualMove(player);
else
{
int selectedMove = getSemiRandomMove(player);
Console.WriteLine("{0} selects position {1}.", playerName(player), selectedMove + 1);
return selectedMove;
}
}
static int getManualMove(int player)
{
while (true)
{
Console.Write("{0}, enter you move (number): ", playerName(player));
ConsoleKeyInfo keyInfo = Console.ReadKey();
Console.WriteLine();
if (keyInfo.Key == ConsoleKey.Escape)
return Unplayed;
if (keyInfo.Key >= ConsoleKey.D1 && keyInfo.Key <= ConsoleKey.D9)
{
int move = keyInfo.KeyChar - '1';
if (GameBoard[move] == Unplayed)
return move;
else
Console.WriteLine("Spot {0} is already taken, please select again.", move + 1);
}
else
Console.WriteLine("Illegal move, please select again.\n");
}
}
static int getRandomMove(int player)
{
int movesLeft = GameBoard.Count(position => position == Unplayed);
int x = rnd.Next(0, movesLeft);
for (int i = 0; i < GameBoard.Length; i++)
{
if (GameBoard[i] == Unplayed && x < 0)
return i;
x--;
}
return Unplayed;
}
static int getSemiRandomMove(int player)
{
int posToPlay;
if (checkForWinningMove(player, out posToPlay))
return posToPlay;
if (checkForBlockingMove(player, out posToPlay))
return posToPlay;
return getRandomMove(player);
}
static int getBestMove(int player)
{
return -1;
}
static bool checkForWinningMove(int player, out int posToPlay)
{
posToPlay = Unplayed;
foreach (var line in wins)
if (twoOfThreeMatchPlayer(player, line, out posToPlay))
return true;
return false;
}
static bool checkForBlockingMove(int player, out int posToPlay)
{
posToPlay = Unplayed;
foreach (var line in wins)
if (twoOfThreeMatchPlayer(getNextPlayer(player), line, out posToPlay))
return true;
return false;
}
static bool twoOfThreeMatchPlayer(int player, int[] line, out int posToPlay)
{
int cnt = 0;
posToPlay = int.MinValue;
foreach (int pos in line)
{
if (GameBoard[pos] == player)
cnt++;
else if (GameBoard[pos] == Unplayed)
posToPlay = pos;
}
return cnt == 2 && posToPlay >= 0;
}
static void playMove(int boardPosition, int player)
{
GameBoard[boardPosition] = player;
}
static bool isGameWon()
{
return wins.Any(line => takenBySamePlayer(line[0], line[1], line[2]));
}
static bool takenBySamePlayer(int a, int b, int c)
{
return GameBoard[a] != Unplayed && GameBoard[a] == GameBoard[b] && GameBoard[a] == GameBoard[c];
}
static bool isGameTied()
{
return !GameBoard.Any(spot => spot == Unplayed);
}
static Random rnd = new Random();
static void initializeGameBoard()
{
for (int i = 0; i < GameBoard.Length; i++)
GameBoard[i] = Unplayed;
}
static string playerName(int player)
{
return Players[player][0];
}
static string playerToken(int player)
{
return Players[player][1];
}
static int getNextPlayer(int player)
{
return (player + 1) % 2;
}
static void displayGameBoard()
{
Console.WriteLine(" {0} | {1} | {2}", pieceAt(0), pieceAt(1), pieceAt(2));
Console.WriteLine("---|---|---");
Console.WriteLine(" {0} | {1} | {2}", pieceAt(3), pieceAt(4), pieceAt(5));
Console.WriteLine("---|---|---");
Console.WriteLine(" {0} | {1} | {2}", pieceAt(6), pieceAt(7), pieceAt(8));
Console.WriteLine();
}
static string pieceAt(int boardPosition)
{
if (GameBoard[boardPosition] == Unplayed)
return (boardPosition + 1).ToString();
return playerToken(GameBoard[boardPosition]);
}
private static bool playAgain()
{
Console.WriteLine("\nDo you want to play again?");
return Console.ReadKey(false).Key == ConsoleKey.Y;
}
}
}
|
Generate an equivalent C# version of this Python code. | i=1
while i:
print(i)
i += 1
| using System;
using System.Numerics;
class Program
{
static void Main()
{
BigInteger i = 1;
while (true)
{
Console.WriteLine(i++);
}
}
}
|
Preserve the algorithm and functionality while converting the code from Python to C#. | i=1
while i:
print(i)
i += 1
| using System;
using System.Numerics;
class Program
{
static void Main()
{
BigInteger i = 1;
while (true)
{
Console.WriteLine(i++);
}
}
}
|
Translate the given Python code snippet into C# without altering its behavior. | >>> import socket
>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))
>>> for ip in ips: print ip
...
2001:200:dff:fff1:216:3eff:feb1:44d7
203.178.141.194
| private string LookupDns(string s)
{
try
{
System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);
string result = ip.AddressList[0].ToString();
for (int i = 1; i < ip.AddressList.Length; ++i)
result += ", " + ip.AddressList[i].ToString();
return result;
}
catch (System.Net.Sockets.SocketException se)
{
return se.Message;
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | >>> import socket
>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))
>>> for ip in ips: print ip
...
2001:200:dff:fff1:216:3eff:feb1:44d7
203.178.141.194
| private string LookupDns(string s)
{
try
{
System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);
string result = ip.AddressList[0].ToString();
for (int i = 1; i < ip.AddressList.Length; ++i)
result += ", " + ip.AddressList[i].ToString();
return result;
}
catch (System.Net.Sockets.SocketException se)
{
return se.Message;
}
}
|
Change the programming language of this snippet from Python to C# without modifying what it does. | from random import randint
def dice5():
return randint(1, 5)
def dice7():
r = dice5() + dice5() * 5 - 6
return (r % 7) + 1 if r < 21 else dice7()
| using System;
public class SevenSidedDice
{
Random random = new Random();
static void Main(string[] args)
{
SevenSidedDice sevenDice = new SevenSidedDice();
Console.WriteLine("Random number from 1 to 7: "+ sevenDice.seven());
Console.Read();
}
int seven()
{
int v=21;
while(v>20)
v=five()+five()*5-6;
return 1+v%7;
}
int five()
{
return 1 + random.Next(5);
}
}
|
Preserve the algorithm and functionality while converting the code from Python to C#. | width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
myarray = [[0] * width for i in range(height)]
myarray[0][0] = 3.5
print (myarray[0][0])
| class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter two integers. Space delimited please: ");
string s = Console.ReadLine();
int[,] myArray=new int[(int)s[0],(int)s[2]];
myArray[0, 0] = 2;
Console.WriteLine(myArray[0, 0]);
Console.ReadLine();
}
}
|
Translate this program into C# but keep the logic exactly as in Python. |
def chinese_remainder(n, a):
sum = 0
prod = reduce(lambda a, b: a*b, n)
for n_i, a_i in zip(n, a):
p = prod / n_i
sum += a_i * mul_inv(p, n_i) * p
return sum % prod
def mul_inv(a, b):
b0 = b
x0, x1 = 0, 1
if b == 1: return 1
while a > 1:
q = a / b
a, b = b, a%b
x0, x1 = x1 - q * x0, x0
if x1 < 0: x1 += b0
return x1
if __name__ == '__main__':
n = [3, 5, 7]
a = [2, 3, 2]
print chinese_remainder(n, a)
| using System;
using System.Linq;
namespace ChineseRemainderTheorem
{
class Program
{
static void Main(string[] args)
{
int[] n = { 3, 5, 7 };
int[] a = { 2, 3, 2 };
int result = ChineseRemainderTheorem.Solve(n, a);
int counter = 0;
int maxCount = n.Length - 1;
while (counter <= maxCount)
{
Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})");
counter++;
}
}
}
public static class ChineseRemainderTheorem
{
public static int Solve(int[] n, int[] a)
{
int prod = n.Aggregate(1, (i, j) => i * j);
int p;
int sm = 0;
for (int i = 0; i < n.Length; i++)
{
p = prod / n[i];
sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;
}
return sm % prod;
}
private static int ModularMultiplicativeInverse(int a, int mod)
{
int b = a % mod;
for (int x = 1; x < mod; x++)
{
if ((b * x) % mod == 1)
{
return x;
}
}
return 1;
}
}
}
|
Port the following code from VB to Java with equivalent syntax and logic. | Debug.Print Hex(&HF0F0 And &HFF00)
Debug.Print Hex(&HF0F0 Or &HFF00)
Debug.Print Hex(&HF0F0 Xor &HFF00)
Debug.Print Hex(Not &HF0F0)
Debug.Print Hex(&HF0F0 Eqv &HFF00)
Debug.Print Hex(&HF0F0 Imp &HFF00)
| module BitwiseOps
{
@Inject Console console;
void run()
{
for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])
{
static String hex(Int64 n)
{
return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();
}
console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):
| {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}
| {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}
| {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}
| NOT {hex(n1)} = {hex(~n1)}
| left shift {hex(n1)} by {n2} = {hex(n1 << n2)}
| right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}
| right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}
| left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}
| right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}
| leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}
| rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}
| leading zero count of {hex(n1)} = {n1.leadingZeroCount}
| trailing zero count of {hex(n1)} = {n1.trailingZeroCount}
| bit count (aka "population") of {hex(n1)} = {n1.bitCount}
| reversed bits of {hex(n1)} = {hex(n1.reverseBits())}
| reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}
|
);
}
}
}
|
Rewrite the snippet below in Java so it works the same as the original VB code. | option explicit
const pi180= 0.01745329251994329576923690768489
const pi=3.1415926535897932384626433832795
class turtle
dim fso
dim fn
dim svg
dim iang
dim ori
dim incr
dim pdown
dim clr
dim x
dim y
public property let orient(n):ori = n*pi180 :end property
public property let iangle(n):iang= n*pi180 :end property
public sub pd() : pdown=true: end sub
public sub pu() :pdown=FALSE :end sub
public sub rt(i)
ori=ori - i*iang:
end sub
public sub lt(i):
ori=(ori + i*iang)
end sub
public sub bw(l)
x= x+ cos(ori+pi)*l*incr
y= y+ sin(ori+pi)*l*incr
end sub
public sub fw(l)
dim x1,y1
x1=x + cos(ori)*l*incr
y1=y + sin(ori)*l*incr
if pdown then line x,y,x1,y1
x=x1:y=y1
end sub
Private Sub Class_Initialize()
setlocale "us"
initsvg
x=400:y=400:incr=100
ori=90*pi180
iang=90*pi180
clr=0
pdown=true
end sub
Private Sub Class_Terminate()
disply
end sub
private sub line (x,y,x1,y1)
svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>"
end sub
private sub disply()
dim shell
svg.WriteLine "</svg></body></html>"
svg.close
Set shell = CreateObject("Shell.Application")
shell.ShellExecute fn,1,False
end sub
private sub initsvg()
dim scriptpath
Set fso = CreateObject ("Scripting.Filesystemobject")
ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\"))
fn=Scriptpath & "SIERP.HTML"
Set svg = fso.CreateTextFile(fn,True)
if SVG IS nothing then wscript.echo "Can
svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>"
svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>"
svg.writeline "</head>"&vbcrlf & "<body>"
svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">"
end sub
end class
sub dragon(st,le,dir)
if st=0 then x.fw le: exit sub
x.rt dir
dragon st-1, le/1.41421 ,1
x.rt dir*2
dragon st-1, le/1.41421 ,-1
x.rt dir
end sub
dim x
set x=new turtle
x.iangle=45
x.orient=45
x.incr=1
x.x=200:x.y=200
dragon 12,300,1
set x=nothing
| import java.awt.Color;
import java.awt.Graphics;
import java.util.*;
import javax.swing.JFrame;
public class DragonCurve extends JFrame {
private List<Integer> turns;
private double startingAngle, side;
public DragonCurve(int iter) {
super("Dragon Curve");
setBounds(100, 100, 800, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
turns = getSequence(iter);
startingAngle = -iter * (Math.PI / 4);
side = 400 / Math.pow(2, iter / 2.);
}
public List<Integer> getSequence(int iterations) {
List<Integer> turnSequence = new ArrayList<Integer>();
for (int i = 0; i < iterations; i++) {
List<Integer> copy = new ArrayList<Integer>(turnSequence);
Collections.reverse(copy);
turnSequence.add(1);
for (Integer turn : copy) {
turnSequence.add(-turn);
}
}
return turnSequence;
}
@Override
public void paint(Graphics g) {
g.setColor(Color.BLACK);
double angle = startingAngle;
int x1 = 230, y1 = 350;
int x2 = x1 + (int) (Math.cos(angle) * side);
int y2 = y1 + (int) (Math.sin(angle) * side);
g.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
for (Integer turn : turns) {
angle += turn * (Math.PI / 2);
x2 = x1 + (int) (Math.cos(angle) * side);
y2 = y1 + (int) (Math.sin(angle) * side);
g.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
}
}
public static void main(String[] args) {
new DragonCurve(14).setVisible(true);
}
}
|
Generate a Java translation of this VB snippet without changing its computational steps. | $Include "Rapidq.inc"
dim file as qfilestream
if file.open("c:\A Test.txt", fmOpenRead) then
while not File.eof
print File.readline
wend
else
print "Cannot read file"
end if
input "Press enter to exit: ";a$
| import java.io.BufferedReader;
import java.io.FileReader;
public class ReadFileByLines {
private static void processLine(int lineNo, String line) {
}
public static void main(String[] args) {
for (String filename : args) {
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
String line;
int lineNo = 0;
while ((line = br.readLine()) != null) {
processLine(++lineNo, line);
}
}
catch (Exception x) {
x.printStackTrace();
}
finally {
if (fr != null) {
try {br.close();} catch (Exception ignoreMe) {}
try {fr.close();} catch (Exception ignoreMe) {}
}
}
}
}
}
|
Write the same code in Java as shown below in VB. | Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T)
Dim node As New Node(Of T)(value)
a.Next = node
node.Previous = a
b.Previous = node
node.Next = b
End Sub
| import java.util.LinkedList;
@SuppressWarnings("serial")
public class DoublyLinkedListInsertion<T> extends LinkedList<T> {
public static void main(String[] args) {
DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();
list.addFirst("Add First 1");
list.addFirst("Add First 2");
list.addFirst("Add First 3");
list.addFirst("Add First 4");
list.addFirst("Add First 5");
traverseList(list);
list.addAfter("Add First 3", "Add New");
traverseList(list);
}
public void addAfter(T after, T element) {
int index = indexOf(after);
if ( index >= 0 ) {
add(index + 1, element);
}
else {
addLast(element);
}
}
private static void traverseList(LinkedList<String> list) {
System.out.println("Traverse List:");
for ( int i = 0 ; i < list.size() ; i++ ) {
System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i));
}
System.out.println();
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | Dim s As Variant
Private Function quick_select(ByRef s As Variant, k As Integer) As Integer
Dim left As Integer, right As Integer, pos As Integer
Dim pivotValue As Integer, tmp As Integer
left = 1: right = UBound(s)
Do While left < right
pivotValue = s(k)
tmp = s(k)
s(k) = s(right)
s(right) = tmp
pos = left
For i = left To right
If s(i) < pivotValue Then
tmp = s(i)
s(i) = s(pos)
s(pos) = tmp
pos = pos + 1
End If
Next i
tmp = s(right)
s(right) = s(pos)
s(pos) = tmp
If pos = k Then
Exit Do
End If
If pos < k Then
left = pos + 1
Else
right = pos - 1
End If
Loop
quick_select = s(k)
End Function
Public Sub main()
Dim r As Integer, i As Integer
s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]
For i = 1 To 10
r = quick_select(s, i)
Debug.Print IIf(i < 10, r & ", ", "" & r);
Next i
End Sub
| import java.util.Random;
public class QuickSelect {
private static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {
E pivotVal = arr[pivot];
swap(arr, pivot, right);
int storeIndex = left;
for (int i = left; i < right; i++) {
if (arr[i].compareTo(pivotVal) < 0) {
swap(arr, i, storeIndex);
storeIndex++;
}
}
swap(arr, right, storeIndex);
return storeIndex;
}
private static <E extends Comparable<? super E>> E select(E[] arr, int n) {
int left = 0;
int right = arr.length - 1;
Random rand = new Random();
while (right >= left) {
int pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);
if (pivotIndex == n) {
return arr[pivotIndex];
} else if (pivotIndex < n) {
left = pivotIndex + 1;
} else {
right = pivotIndex - 1;
}
}
return null;
}
private static void swap(Object[] arr, int i1, int i2) {
if (i1 != i2) {
Object temp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = temp;
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Integer[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
System.out.print(select(input, i));
if (i < 9) System.out.print(", ");
}
System.out.println();
}
}
|
Write a version of this VB function in Java with identical behavior. | Private Function to_base(ByVal number As Long, base As Integer) As String
Dim digits As String, result As String
Dim i As Integer, digit As Integer
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
Do While number > 0
digit = number Mod base
result = Mid(digits, digit + 1, 1) & result
number = number \ base
Loop
to_base = result
End Function
Private Function from_base(number As String, base As Integer) As Long
Dim digits As String, result As Long
Dim i As Integer
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)
For i = 2 To Len(number)
result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)
Next i
from_base = result
End Function
Public Sub Non_decimal_radices_Convert()
Debug.Print "26 decimal in base 16 is: "; to_base(26, 16); ". Conversely, hexadecimal 1a in decimal is: "; from_base("1a", 16)
End Sub
| public static long backToTen(String num, int oldBase){
return Long.parseLong(num, oldBase);
}
public static String tenToBase(long num, int newBase){
return Long.toString(num, newBase);
}
|
Write the same algorithm in Java as shown in this VB implementation. | Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
| import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | dim crctbl(255)
const crcc =&hEDB88320
sub gencrctable
for i= 0 to 255
k=i
for j=1 to 8
if k and 1 then
k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0))
k=k xor crcc
else
k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0))
end if
next
crctbl(i)=k
next
end sub
function crc32 (buf)
dim r,r1,i
r=&hffffffff
for i=1 to len(buf)
r1=(r and &h7fffffff)\&h100 or (&h800000 and (r and &h80000000)<>0)
r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255)
next
crc32=r xor &hffffffff
end function
gencrctable
wscript.stdout.writeline hex(crc32("The quick brown fox jumps over the lazy dog"))
| import java.util.zip.* ;
public class CRCMaker {
public static void main( String[ ] args ) {
String toBeEncoded = new String( "The quick brown fox jumps over the lazy dog" ) ;
CRC32 myCRC = new CRC32( ) ;
myCRC.update( toBeEncoded.getBytes( ) ) ;
System.out.println( "The CRC-32 value is : " + Long.toHexString( myCRC.getValue( ) ) + " !" ) ;
}
}
|
Convert this VB snippet to Java and keep its semantics consistent. | Public Sub CSV_TO_HTML()
input_ = "Character,Speech\n" & _
"The multitude,The messiah! Show us the messiah!\n" & _
"Brians mother,<angry>Now you listen here! He
"he
"The multitude,Who are you?\n" & _
"Brians mother,I
"The multitude,Behold his mother! Behold his mother!"
Debug.Print "<table>" & vbCrLf & "<tr><td>"
For i = 1 To Len(input_)
Select Case Mid(input_, i, 1)
Case "\"
If Mid(input_, i + 1, 1) = "n" Then
Debug.Print "</td></tr>" & vbCrLf & "<tr><td>";
i = i + 1
Else
Debug.Print Mid(input_, i, 1);
End If
Case ",": Debug.Print "</td><td>";
Case "<": Debug.Print "<";
Case ">": Debug.Print ">";
Case "&": Debug.Print "&";
Case Else: Debug.Print Mid(input_, i, 1);
End Select
Next i
Debug.Print "</td></tr>" & vbCrLf & "</table>"
End Sub
|
grammar csv2html;
dialog : {System.out.println("<HTML><Table>");}header body+{System.out.println("</Table></HTML>");} ;
header : {System.out.println("<THEAD align=\"center\"><TR bgcolor=\"blue\">");}row{System.out.println("</TR></THEAD");};
body : {System.out.println("<TBODY><TR>");}row{System.out.println("</TR></TBODY");};
row : field ',' field '\r'? '\n';
field : Field{System.out.println("<TD>" + $Field.text.replace("<","<").replace(">",">") + "</TD>");};
Field : ~[,\n\r]+;
|
Rewrite the snippet below in Java so it works the same as the original VB code. | Public Sub CSV_TO_HTML()
input_ = "Character,Speech\n" & _
"The multitude,The messiah! Show us the messiah!\n" & _
"Brians mother,<angry>Now you listen here! He
"he
"The multitude,Who are you?\n" & _
"Brians mother,I
"The multitude,Behold his mother! Behold his mother!"
Debug.Print "<table>" & vbCrLf & "<tr><td>"
For i = 1 To Len(input_)
Select Case Mid(input_, i, 1)
Case "\"
If Mid(input_, i + 1, 1) = "n" Then
Debug.Print "</td></tr>" & vbCrLf & "<tr><td>";
i = i + 1
Else
Debug.Print Mid(input_, i, 1);
End If
Case ",": Debug.Print "</td><td>";
Case "<": Debug.Print "<";
Case ">": Debug.Print ">";
Case "&": Debug.Print "&";
Case Else: Debug.Print Mid(input_, i, 1);
End Select
Next i
Debug.Print "</td></tr>" & vbCrLf & "</table>"
End Sub
|
grammar csv2html;
dialog : {System.out.println("<HTML><Table>");}header body+{System.out.println("</Table></HTML>");} ;
header : {System.out.println("<THEAD align=\"center\"><TR bgcolor=\"blue\">");}row{System.out.println("</TR></THEAD");};
body : {System.out.println("<TBODY><TR>");}row{System.out.println("</TR></TBODY");};
row : field ',' field '\r'? '\n';
field : Field{System.out.println("<TD>" + $Field.text.replace("<","<").replace(">",">") + "</TD>");};
Field : ~[,\n\r]+;
|
Generate an equivalent Java version of this VB code. | Class NumberContainer
Private TheNumber As Integer
Sub Constructor(InitialNumber As Integer)
TheNumber = InitialNumber
End Sub
Function Number() As Integer
Return TheNumber
End Function
Sub Number(Assigns NewNumber As Integer)
TheNumber = NewNumber
End Sub
End Class
| public class MyClass{
private int variable;
public MyClass(){
}
public void someMethod(){
this.variable = 1;
}
}
|
Change the following VB code into Java without altering its purpose. | Module Module1
ReadOnly max As ULong = 1000000
Function Kaprekar(n As ULong) As Boolean
If n = 1 Then Return True
Dim sq = n * n
Dim sq_str = Str(sq)
Dim l = Len(sq_str)
For x = l - 1 To 1 Step -1
If sq_str(x) = "0" Then
l = l - 1
Else
Exit For
End If
Next
For x = 1 To l - 1
Dim p2 = Val(Mid(sq_str, x + 1))
If p2 > n Then
Continue For
End If
Dim p1 = Val(Left(sq_str, x))
If p1 > n Then Return False
If (p1 + p2) = n Then Return True
Next
Return False
End Function
Sub Main()
Dim count = 0
Console.WriteLine("Kaprekar numbers below 10000")
For n = 1 To max - 1
If Kaprekar(n) Then
count = count + 1
If n < 10000 Then
Console.WriteLine("{0,2} {1,4}", count, n)
End If
End If
Next
Console.WriteLine()
Console.WriteLine("{0} numbers below {1} are kaprekar numbers", count, max)
End Sub
End Module
| public class Kaprekar {
private static String[] splitAt(String str, int idx){
String[] ans = new String[2];
ans[0] = str.substring(0, idx);
if(ans[0].equals("")) ans[0] = "0";
ans[1] = str.substring(idx);
return ans;
}
public static void main(String[] args){
int count = 0;
int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;
for(long i = 1; i <= 1000000; i++){
String sqrStr = Long.toString(i * i, base);
for(int j = 0; j < sqrStr.length() / 2 + 1; j++){
String[] parts = splitAt(sqrStr, j);
long firstNum = Long.parseLong(parts[0], base);
long secNum = Long.parseLong(parts[1], base);
if(secNum == 0) break;
if(firstNum + secNum == i){
System.out.println(i + "\t" + Long.toString(i, base) +
"\t" + sqrStr + "\t" + parts[0] + " + " + parts[1]);
count++;
break;
}
}
}
System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base);
}
}
|
Ensure the translated Java code behaves exactly like the original VB snippet. | Module Module1
ReadOnly max As ULong = 1000000
Function Kaprekar(n As ULong) As Boolean
If n = 1 Then Return True
Dim sq = n * n
Dim sq_str = Str(sq)
Dim l = Len(sq_str)
For x = l - 1 To 1 Step -1
If sq_str(x) = "0" Then
l = l - 1
Else
Exit For
End If
Next
For x = 1 To l - 1
Dim p2 = Val(Mid(sq_str, x + 1))
If p2 > n Then
Continue For
End If
Dim p1 = Val(Left(sq_str, x))
If p1 > n Then Return False
If (p1 + p2) = n Then Return True
Next
Return False
End Function
Sub Main()
Dim count = 0
Console.WriteLine("Kaprekar numbers below 10000")
For n = 1 To max - 1
If Kaprekar(n) Then
count = count + 1
If n < 10000 Then
Console.WriteLine("{0,2} {1,4}", count, n)
End If
End If
Next
Console.WriteLine()
Console.WriteLine("{0} numbers below {1} are kaprekar numbers", count, max)
End Sub
End Module
| public class Kaprekar {
private static String[] splitAt(String str, int idx){
String[] ans = new String[2];
ans[0] = str.substring(0, idx);
if(ans[0].equals("")) ans[0] = "0";
ans[1] = str.substring(idx);
return ans;
}
public static void main(String[] args){
int count = 0;
int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;
for(long i = 1; i <= 1000000; i++){
String sqrStr = Long.toString(i * i, base);
for(int j = 0; j < sqrStr.length() / 2 + 1; j++){
String[] parts = splitAt(sqrStr, j);
long firstNum = Long.parseLong(parts[0], base);
long secNum = Long.parseLong(parts[1], base);
if(secNum == 0) break;
if(firstNum + secNum == i){
System.out.println(i + "\t" + Long.toString(i, base) +
"\t" + sqrStr + "\t" + parts[0] + " + " + parts[1]);
count++;
break;
}
}
}
System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base);
}
}
|
Generate a Java translation of this VB snippet without changing its computational steps. | Module Module1
ReadOnly max As ULong = 1000000
Function Kaprekar(n As ULong) As Boolean
If n = 1 Then Return True
Dim sq = n * n
Dim sq_str = Str(sq)
Dim l = Len(sq_str)
For x = l - 1 To 1 Step -1
If sq_str(x) = "0" Then
l = l - 1
Else
Exit For
End If
Next
For x = 1 To l - 1
Dim p2 = Val(Mid(sq_str, x + 1))
If p2 > n Then
Continue For
End If
Dim p1 = Val(Left(sq_str, x))
If p1 > n Then Return False
If (p1 + p2) = n Then Return True
Next
Return False
End Function
Sub Main()
Dim count = 0
Console.WriteLine("Kaprekar numbers below 10000")
For n = 1 To max - 1
If Kaprekar(n) Then
count = count + 1
If n < 10000 Then
Console.WriteLine("{0,2} {1,4}", count, n)
End If
End If
Next
Console.WriteLine()
Console.WriteLine("{0} numbers below {1} are kaprekar numbers", count, max)
End Sub
End Module
| public class Kaprekar {
private static String[] splitAt(String str, int idx){
String[] ans = new String[2];
ans[0] = str.substring(0, idx);
if(ans[0].equals("")) ans[0] = "0";
ans[1] = str.substring(idx);
return ans;
}
public static void main(String[] args){
int count = 0;
int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;
for(long i = 1; i <= 1000000; i++){
String sqrStr = Long.toString(i * i, base);
for(int j = 0; j < sqrStr.length() / 2 + 1; j++){
String[] parts = splitAt(sqrStr, j);
long firstNum = Long.parseLong(parts[0], base);
long secNum = Long.parseLong(parts[1], base);
if(secNum == 0) break;
if(firstNum + secNum == i){
System.out.println(i + "\t" + Long.toString(i, base) +
"\t" + sqrStr + "\t" + parts[0] + " + " + parts[1]);
count++;
break;
}
}
}
System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base);
}
}
|
Can you help me rewrite this code in Java instead of VB, keeping it the same logically? | Option Explicit
Const numchars=127
Function LZWCompress(si)
Dim oDict, intMaxCode, i,z,ii,ss,strCurrent,strNext,j
Set oDict = CreateObject("Scripting.Dictionary")
ReDim a(Len(si))
intMaxCode = numchars
For i = 0 To numchars
oDict.Add Chr(i), i
Next
strCurrent = Left(si,1)
j=0
For ii=2 To Len(si)
strNext = Mid(si,ii,1)
ss=strCurrent & strNext
If oDict.Exists(ss) Then
strCurrent = ss
Else
a(j)=oDict.Item(strCurrent) :j=j+1
intMaxCode = intMaxCode + 1
oDict.Add ss, intMaxCode
strCurrent = strNext
End If
Next
a(j)=oDict.Item(strCurrent)
ReDim preserve a(j)
LZWCompress=a
Set oDict = Nothing
End Function
Function lzwUncompress(sc)
Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j
s=""
reDim dict(1000)
intMaxCode = numchars
For i = 0 To numchars : dict(i)= Chr(i) : Next
intCurrent=sc(0)
For j=1 To UBound(sc)
ss=dict(intCurrent)
s= s & ss
intMaxCode = intMaxCode + 1
intnext=sc(j)
If intNext<intMaxCode Then
dict(intMaxCode)=ss & Left(dict(intNext), 1)
Else
dict(intMaxCode)=ss & Left(ss, 1)
End If
intCurrent = intNext
Next
s= s & dict(intCurrent)
lzwUncompress=s
End function
Sub printvec(a)
Dim s,i,x
s="("
For i=0 To UBound (a)
s=s & x & a(i)
x=", "
Next
WScript.echo s &")"
End sub
Dim a,b
b="TOBEORNOTTOBEORTOBEORNOT"
WScript.Echo b
a=LZWCompress (b)
printvec(a)
WScript.echo lzwUncompress (a )
wscript.quit 1
| import java.util.*;
public class LZW {
public static List<Integer> compress(String uncompressed) {
int dictSize = 256;
Map<String,Integer> dictionary = new HashMap<String,Integer>();
for (int i = 0; i < 256; i++)
dictionary.put("" + (char)i, i);
String w = "";
List<Integer> result = new ArrayList<Integer>();
for (char c : uncompressed.toCharArray()) {
String wc = w + c;
if (dictionary.containsKey(wc))
w = wc;
else {
result.add(dictionary.get(w));
dictionary.put(wc, dictSize++);
w = "" + c;
}
}
if (!w.equals(""))
result.add(dictionary.get(w));
return result;
}
public static String decompress(List<Integer> compressed) {
int dictSize = 256;
Map<Integer,String> dictionary = new HashMap<Integer,String>();
for (int i = 0; i < 256; i++)
dictionary.put(i, "" + (char)i);
String w = "" + (char)(int)compressed.remove(0);
StringBuffer result = new StringBuffer(w);
for (int k : compressed) {
String entry;
if (dictionary.containsKey(k))
entry = dictionary.get(k);
else if (k == dictSize)
entry = w + w.charAt(0);
else
throw new IllegalArgumentException("Bad compressed k: " + k);
result.append(entry);
dictionary.put(dictSize++, w + entry.charAt(0));
w = entry;
}
return result.toString();
}
public static void main(String[] args) {
List<Integer> compressed = compress("TOBEORNOTTOBEORTOBEORNOT");
System.out.println(compressed);
String decompressed = decompress(compressed);
System.out.println(decompressed);
}
}
|
Generate an equivalent Java version of this VB code. | Private Function ffr(n As Long) As Long
Dim R As New Collection
Dim S As New Collection
R.Add 1
S.Add 2
For i = 2 To n
R.Add R(i - 1) + S(i - 1)
For j = S(S.Count) + 1 To R(i) - 1
S.Add j
Next j
For j = R(i) + 1 To R(i) + S(i - 1)
S.Add j
Next j
Next i
ffr = R(n)
Set R = Nothing
Set S = Nothing
End Function
Private Function ffs(n As Long) As Long
Dim R As New Collection
Dim S As New Collection
R.Add 1
S.Add 2
For i = 2 To n
R.Add R(i - 1) + S(i - 1)
For j = S(S.Count) + 1 To R(i) - 1
S.Add j
Next j
For j = R(i) + 1 To R(i) + S(i - 1)
S.Add j
Next j
If S.Count >= n Then Exit For
Next i
ffs = S(n)
Set R = Nothing
Set S = Nothing
End Function
Public Sub main()
Dim i As Long
Debug.Print "The first ten values of R are:"
For i = 1 To 10
Debug.Print ffr(i);
Next i
Debug.Print
Dim x As New Collection
For i = 1 To 1000
x.Add i, CStr(i)
Next i
For i = 1 To 40
x.Remove CStr(ffr(i))
Next i
For i = 1 To 960
x.Remove CStr(ffs(i))
Next i
Debug.Print "The first 40 values of ffr plus the first 960 values of ffs "
Debug.Print "include all the integers from 1 to 1000 exactly once is "; Format(x.Count = 0)
End Sub
| import java.util.*;
class Hofstadter
{
private static List<Integer> getSequence(int rlistSize, int slistSize)
{
List<Integer> rlist = new ArrayList<Integer>();
List<Integer> slist = new ArrayList<Integer>();
Collections.addAll(rlist, 1, 3, 7);
Collections.addAll(slist, 2, 4, 5, 6);
List<Integer> list = (rlistSize > 0) ? rlist : slist;
int targetSize = (rlistSize > 0) ? rlistSize : slistSize;
while (list.size() > targetSize)
list.remove(list.size() - 1);
while (list.size() < targetSize)
{
int lastIndex = rlist.size() - 1;
int lastr = rlist.get(lastIndex).intValue();
int r = lastr + slist.get(lastIndex).intValue();
rlist.add(Integer.valueOf(r));
for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)
slist.add(Integer.valueOf(s));
}
return list;
}
public static int ffr(int n)
{ return getSequence(n, 0).get(n - 1).intValue(); }
public static int ffs(int n)
{ return getSequence(0, n).get(n - 1).intValue(); }
public static void main(String[] args)
{
System.out.print("R():");
for (int n = 1; n <= 10; n++)
System.out.print(" " + ffr(n));
System.out.println();
Set<Integer> first40R = new HashSet<Integer>();
for (int n = 1; n <= 40; n++)
first40R.add(Integer.valueOf(ffr(n)));
Set<Integer> first960S = new HashSet<Integer>();
for (int n = 1; n <= 960; n++)
first960S.add(Integer.valueOf(ffs(n)));
for (int i = 1; i <= 1000; i++)
{
Integer n = Integer.valueOf(i);
if (first40R.contains(n) == first960S.contains(n))
System.out.println("Integer " + i + " either in both or neither set");
}
System.out.println("Done");
}
}
|
Can you help me rewrite this code in Java instead of VB, keeping it the same logically? | Private Function ffr(n As Long) As Long
Dim R As New Collection
Dim S As New Collection
R.Add 1
S.Add 2
For i = 2 To n
R.Add R(i - 1) + S(i - 1)
For j = S(S.Count) + 1 To R(i) - 1
S.Add j
Next j
For j = R(i) + 1 To R(i) + S(i - 1)
S.Add j
Next j
Next i
ffr = R(n)
Set R = Nothing
Set S = Nothing
End Function
Private Function ffs(n As Long) As Long
Dim R As New Collection
Dim S As New Collection
R.Add 1
S.Add 2
For i = 2 To n
R.Add R(i - 1) + S(i - 1)
For j = S(S.Count) + 1 To R(i) - 1
S.Add j
Next j
For j = R(i) + 1 To R(i) + S(i - 1)
S.Add j
Next j
If S.Count >= n Then Exit For
Next i
ffs = S(n)
Set R = Nothing
Set S = Nothing
End Function
Public Sub main()
Dim i As Long
Debug.Print "The first ten values of R are:"
For i = 1 To 10
Debug.Print ffr(i);
Next i
Debug.Print
Dim x As New Collection
For i = 1 To 1000
x.Add i, CStr(i)
Next i
For i = 1 To 40
x.Remove CStr(ffr(i))
Next i
For i = 1 To 960
x.Remove CStr(ffs(i))
Next i
Debug.Print "The first 40 values of ffr plus the first 960 values of ffs "
Debug.Print "include all the integers from 1 to 1000 exactly once is "; Format(x.Count = 0)
End Sub
| import java.util.*;
class Hofstadter
{
private static List<Integer> getSequence(int rlistSize, int slistSize)
{
List<Integer> rlist = new ArrayList<Integer>();
List<Integer> slist = new ArrayList<Integer>();
Collections.addAll(rlist, 1, 3, 7);
Collections.addAll(slist, 2, 4, 5, 6);
List<Integer> list = (rlistSize > 0) ? rlist : slist;
int targetSize = (rlistSize > 0) ? rlistSize : slistSize;
while (list.size() > targetSize)
list.remove(list.size() - 1);
while (list.size() < targetSize)
{
int lastIndex = rlist.size() - 1;
int lastr = rlist.get(lastIndex).intValue();
int r = lastr + slist.get(lastIndex).intValue();
rlist.add(Integer.valueOf(r));
for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)
slist.add(Integer.valueOf(s));
}
return list;
}
public static int ffr(int n)
{ return getSequence(n, 0).get(n - 1).intValue(); }
public static int ffs(int n)
{ return getSequence(0, n).get(n - 1).intValue(); }
public static void main(String[] args)
{
System.out.print("R():");
for (int n = 1; n <= 10; n++)
System.out.print(" " + ffr(n));
System.out.println();
Set<Integer> first40R = new HashSet<Integer>();
for (int n = 1; n <= 40; n++)
first40R.add(Integer.valueOf(ffr(n)));
Set<Integer> first960S = new HashSet<Integer>();
for (int n = 1; n <= 960; n++)
first960S.add(Integer.valueOf(ffs(n)));
for (int i = 1; i <= 1000; i++)
{
Integer n = Integer.valueOf(i);
if (first40R.contains(n) == first960S.contains(n))
System.out.println("Integer " + i + " either in both or neither set");
}
System.out.println("Done");
}
}
|
Produce a functionally identical Java code for the snippet given in VB. | Sub magicsquare()
Const n = 9
Dim i As Integer, j As Integer, v As Integer
Debug.Print "The square order is: " & n
For i = 1 To n
For j = 1 To n
Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1
Next j
Next i
Debug.Print "The magic number of"; n; "x"; n; "square is:"; n * (n * n + 1) \ 2
End Sub
| public class MagicSquare {
public static void main(String[] args) {
int n = 5;
for (int[] row : magicSquareOdd(n)) {
for (int x : row)
System.out.format("%2s ", x);
System.out.println();
}
System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2);
}
public static int[][] magicSquareOdd(final int base) {
if (base % 2 == 0 || base < 3)
throw new IllegalArgumentException("base must be odd and > 2");
int[][] grid = new int[base][base];
int r = 0, number = 0;
int size = base * base;
int c = base / 2;
while (number++ < size) {
grid[r][c] = number;
if (r == 0) {
if (c == base - 1) {
r++;
} else {
r = base - 1;
c++;
}
} else {
if (c == base - 1) {
r--;
c = 0;
} else {
if (grid[r - 1][c + 1] == 0) {
r--;
c++;
} else {
r++;
}
}
}
}
return grid;
}
}
|
Convert the following code from VB to Java, ensuring the logic remains intact. | Sub magicsquare()
Const n = 9
Dim i As Integer, j As Integer, v As Integer
Debug.Print "The square order is: " & n
For i = 1 To n
For j = 1 To n
Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1
Next j
Next i
Debug.Print "The magic number of"; n; "x"; n; "square is:"; n * (n * n + 1) \ 2
End Sub
| public class MagicSquare {
public static void main(String[] args) {
int n = 5;
for (int[] row : magicSquareOdd(n)) {
for (int x : row)
System.out.format("%2s ", x);
System.out.println();
}
System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2);
}
public static int[][] magicSquareOdd(final int base) {
if (base % 2 == 0 || base < 3)
throw new IllegalArgumentException("base must be odd and > 2");
int[][] grid = new int[base][base];
int r = 0, number = 0;
int size = base * base;
int c = base / 2;
while (number++ < size) {
grid[r][c] = number;
if (r == 0) {
if (c == base - 1) {
r++;
} else {
r = base - 1;
c++;
}
} else {
if (c == base - 1) {
r--;
c = 0;
} else {
if (grid[r - 1][c + 1] == 0) {
r--;
c++;
} else {
r++;
}
}
}
}
return grid;
}
}
|
Port the provided VB code into Java while preserving the original functionality. | Sub BenfordLaw()
Dim BenResult(1 To 9) As Long
BENref = "30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%"
For Each c In Selection.Cells
If InStr(1, "-0123456789", Left(c, 1)) > 0 Then
For i = 1 To 9
If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For
Next
End If
Next
Total= Application.Sum(BenResult)
biggest= Len(CStr(BenResult(1)))
txt = "# | Values | Real | Expected " & vbCrLf
For i = 1 To 9
If BenResult(i) > 0 Then
txt = txt & "#" & i & " | " & vbTab
txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, " ") & Format(BenResult(i), "0") & " | " & vbTab
txt = txt & String((Len(CStr(Format(BenResult(1) / Total, "##0.0%"))) - Len(CStr(Format(BenResult(i) / Total, "##0.0%")))) * 2, " ") & Format(BenResult(i) / Total, "##0.0%") & " | " & vbTab
txt = txt & Format(Split(BENref, "|")(i - 1), " ##0.0%") & vbCrLf
End If
Next
MsgBox txt, vbOKOnly, "Finish"
End Sub
}
| import java.math.BigInteger;
import java.util.Locale;
public class BenfordsLaw {
private static BigInteger[] generateFibonacci(int n) {
BigInteger[] fib = new BigInteger[n];
fib[0] = BigInteger.ONE;
fib[1] = BigInteger.ONE;
for (int i = 2; i < fib.length; i++) {
fib[i] = fib[i - 2].add(fib[i - 1]);
}
return fib;
}
public static void main(String[] args) {
BigInteger[] numbers = generateFibonacci(1000);
int[] firstDigits = new int[10];
for (BigInteger number : numbers) {
firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;
}
for (int i = 1; i < firstDigits.length; i++) {
System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n",
i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));
}
}
}
|
Generate an equivalent Java version of this VB code. | Sub BenfordLaw()
Dim BenResult(1 To 9) As Long
BENref = "30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%"
For Each c In Selection.Cells
If InStr(1, "-0123456789", Left(c, 1)) > 0 Then
For i = 1 To 9
If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For
Next
End If
Next
Total= Application.Sum(BenResult)
biggest= Len(CStr(BenResult(1)))
txt = "# | Values | Real | Expected " & vbCrLf
For i = 1 To 9
If BenResult(i) > 0 Then
txt = txt & "#" & i & " | " & vbTab
txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, " ") & Format(BenResult(i), "0") & " | " & vbTab
txt = txt & String((Len(CStr(Format(BenResult(1) / Total, "##0.0%"))) - Len(CStr(Format(BenResult(i) / Total, "##0.0%")))) * 2, " ") & Format(BenResult(i) / Total, "##0.0%") & " | " & vbTab
txt = txt & Format(Split(BENref, "|")(i - 1), " ##0.0%") & vbCrLf
End If
Next
MsgBox txt, vbOKOnly, "Finish"
End Sub
}
| import java.math.BigInteger;
import java.util.Locale;
public class BenfordsLaw {
private static BigInteger[] generateFibonacci(int n) {
BigInteger[] fib = new BigInteger[n];
fib[0] = BigInteger.ONE;
fib[1] = BigInteger.ONE;
for (int i = 2; i < fib.length; i++) {
fib[i] = fib[i - 2].add(fib[i - 1]);
}
return fib;
}
public static void main(String[] args) {
BigInteger[] numbers = generateFibonacci(1000);
int[] firstDigits = new int[10];
for (BigInteger number : numbers) {
firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;
}
for (int i = 1; i < firstDigits.length; i++) {
System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n",
i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));
}
}
}
|
Change the following VB code into Java without altering its purpose. | Sub Main()
Debug.Print F(-10)
Debug.Print F(10)
End Sub
Private Function F(N As Long) As Variant
If N < 0 Then
F = "Error. Negative argument"
ElseIf N <= 1 Then
F = N
Else
F = F(N - 1) + F(N - 2)
End If
End Function
| public static long fib(int n) {
if (n < 0)
throw new IllegalArgumentException("n can not be a negative number");
return new Object() {
private long fibInner(int n) {
return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));
}
}.fibInner(n);
}
|
Change the following VB code into Java without altering its purpose. | string = "Small Basic"
TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2))
TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1))
TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
| String strOrig = 'brooms';
String str1 = strOrig.substring(1, strOrig.length());
system.debug(str1);
String str2 = strOrig.substring(0, strOrig.length()-1);
system.debug(str2);
String str3 = strOrig.substring(1, strOrig.length()-1);
system.debug(str3);
String strOrig = 'brooms';
String str1 = strOrig.replaceAll( '^.', '' );
system.debug(str1);
String str2 = strOrig.replaceAll( '.$', '' ) ;
system.debug(str2);
String str3 = strOrig.replaceAll( '^.|.$', '' );
system.debug(str3);
|
Preserve the algorithm and functionality while converting the code from VB to Java. | string = "Small Basic"
TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2))
TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1))
TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
| String strOrig = 'brooms';
String str1 = strOrig.substring(1, strOrig.length());
system.debug(str1);
String str2 = strOrig.substring(0, strOrig.length()-1);
system.debug(str2);
String str3 = strOrig.substring(1, strOrig.length()-1);
system.debug(str3);
String strOrig = 'brooms';
String str1 = strOrig.replaceAll( '^.', '' );
system.debug(str1);
String str2 = strOrig.replaceAll( '.$', '' ) ;
system.debug(str2);
String str3 = strOrig.replaceAll( '^.|.$', '' );
system.debug(str3);
|
Ensure the translated Java code behaves exactly like the original VB snippet. | string = "Small Basic"
TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2))
TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1))
TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
| String strOrig = 'brooms';
String str1 = strOrig.substring(1, strOrig.length());
system.debug(str1);
String str2 = strOrig.substring(0, strOrig.length()-1);
system.debug(str2);
String str3 = strOrig.substring(1, strOrig.length()-1);
system.debug(str3);
String strOrig = 'brooms';
String str1 = strOrig.replaceAll( '^.', '' );
system.debug(str1);
String str2 = strOrig.replaceAll( '.$', '' ) ;
system.debug(str2);
String str3 = strOrig.replaceAll( '^.|.$', '' );
system.debug(str3);
|
Translate this program into Java but keep the logic exactly as in VB. |
Set objfso = CreateObject("Scripting.FileSystemObject")
Set objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_
"\input.txt",1)
list = ""
previous_line = ""
l = Len(previous_line)
Do Until objfile.AtEndOfStream
current_line = objfile.ReadLine
If Mid(current_line,l+1,1) <> "" Then
list = current_line & vbCrLf
previous_line = current_line
l = Len(previous_line)
ElseIf Mid(current_line,l,1) <> "" And Mid(current_line,(l+1),1) = "" Then
list = list & current_line & vbCrLf
End If
Loop
WScript.Echo list
objfile.Close
Set objfso = Nothing
| import java.io.File;
import java.util.Scanner;
public class LongestStringChallenge {
public static void main(String[] args) throws Exception {
String lines = "", longest = "";
try (Scanner sc = new Scanner(new File("lines.txt"))) {
while(sc.hasNext()) {
String line = sc.nextLine();
if (longer(longest, line))
lines = longest = line;
else if (!longer(line, longest))
lines = lines.concat("\n").concat(line);
}
}
System.out.println(lines);
}
static boolean longer(String a, String b) {
try {
String dummy = a.substring(b.length());
} catch (StringIndexOutOfBoundsException e) {
return true;
}
return false;
}
}
|
Generate a Java translation of this VB snippet without changing its computational steps. | Option Base 1
Public Enum sett
name_ = 1
initState
endState
blank
rules
End Enum
Public incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant
Private Sub init()
incrementer = Array("Simple incrementer", _
"q0", _
"qf", _
"B", _
Array( _
Array("q0", "1", "1", "right", "q0"), _
Array("q0", "B", "1", "stay", "qf")))
threeStateBB = Array("Three-state busy beaver", _
"a", _
"halt", _
"0", _
Array( _
Array("a", "0", "1", "right", "b"), _
Array("a", "1", "1", "left", "c"), _
Array("b", "0", "1", "left", "a"), _
Array("b", "1", "1", "right", "b"), _
Array("c", "0", "1", "left", "b"), _
Array("c", "1", "1", "stay", "halt")))
fiveStateBB = Array("Five-state busy beaver", _
"A", _
"H", _
"0", _
Array( _
Array("A", "0", "1", "right", "B"), _
Array("A", "1", "1", "left", "C"), _
Array("B", "0", "1", "right", "C"), _
Array("B", "1", "1", "right", "B"), _
Array("C", "0", "1", "right", "D"), _
Array("C", "1", "0", "left", "E"), _
Array("D", "0", "1", "left", "A"), _
Array("D", "1", "1", "left", "D"), _
Array("E", "0", "1", "stay", "H"), _
Array("E", "1", "0", "left", "A")))
End Sub
Private Sub show(state As String, headpos As Long, tape As Collection)
Debug.Print " "; state; String$(7 - Len(state), " "); "| ";
For p = 1 To tape.Count
Debug.Print IIf(p = headpos, "[" & tape(p) & "]", " " & tape(p) & " ");
Next p
Debug.Print
End Sub
Private Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)
Dim state As String: state = machine(initState)
Dim headpos As Long: headpos = 1
Dim counter As Long, rule As Variant
Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), "=")
If Not countOnly Then Debug.Print " State | Tape [head]" & vbCrLf & "---------------------"
Do While True
If headpos > tape.Count Then
tape.Add machine(blank)
Else
If headpos < 1 Then
tape.Add machine(blank), Before:=1
headpos = 1
End If
End If
If Not countOnly Then show state, headpos, tape
For i = LBound(machine(rules)) To UBound(machine(rules))
rule = machine(rules)(i)
If rule(1) = state And rule(2) = tape(headpos) Then
tape.Remove headpos
If headpos > tape.Count Then
tape.Add rule(3)
Else
tape.Add rule(3), Before:=headpos
End If
If rule(4) = "left" Then headpos = headpos - 1
If rule(4) = "right" Then headpos = headpos + 1
state = rule(5)
Exit For
End If
Next i
counter = counter + 1
If counter Mod 100000 = 0 Then
Debug.Print counter
DoEvents
DoEvents
End If
If state = machine(endState) Then Exit Do
Loop
DoEvents
If countOnly Then
Debug.Print "Steps taken: ", counter
Else
show state, headpos, tape
Debug.Print
End If
End Sub
Public Sub main()
init
Dim tap As New Collection
tap.Add "1": tap.Add "1": tap.Add "1"
UTM incrementer, tap
Set tap = New Collection
UTM threeStateBB, tap
Set tap = New Collection
UTM fiveStateBB, tap, countOnly:=-1
End Sub
| import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.List;
import java.util.Set;
import java.util.Map;
public class UTM {
private List<String> tape;
private String blankSymbol;
private ListIterator<String> head;
private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();
private Set<String> terminalStates;
private String initialState;
public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {
this.blankSymbol = blankSymbol;
for (Transition t : transitions) {
this.transitions.put(t.from, t);
}
this.terminalStates = terminalStates;
this.initialState = initialState;
}
public static class StateTapeSymbolPair {
private String state;
private String tapeSymbol;
public StateTapeSymbolPair(String state, String tapeSymbol) {
this.state = state;
this.tapeSymbol = tapeSymbol;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((state == null) ? 0 : state.hashCode());
result = prime
* result
+ ((tapeSymbol == null) ? 0 : tapeSymbol
.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StateTapeSymbolPair other = (StateTapeSymbolPair) obj;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
if (tapeSymbol == null) {
if (other.tapeSymbol != null)
return false;
} else if (!tapeSymbol.equals(other.tapeSymbol))
return false;
return true;
}
@Override
public String toString() {
return "(" + state + "," + tapeSymbol + ")";
}
}
public static class Transition {
private StateTapeSymbolPair from;
private StateTapeSymbolPair to;
private int direction;
public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {
this.from = from;
this.to = to;
this.direction = direction;
}
@Override
public String toString() {
return from + "=>" + to + "/" + direction;
}
}
public void initializeTape(List<String> input) {
tape = input;
}
public void initializeTape(String input) {
tape = new LinkedList<String>();
for (int i = 0; i < input.length(); i++) {
tape.add(input.charAt(i) + "");
}
}
public List<String> runTM() {
if (tape.size() == 0) {
tape.add(blankSymbol);
}
head = tape.listIterator();
head.next();
head.previous();
StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));
while (transitions.containsKey(tsp)) {
System.out.println(this + " --- " + transitions.get(tsp));
Transition trans = transitions.get(tsp);
head.set(trans.to.tapeSymbol);
tsp.state = trans.to.state;
if (trans.direction == -1) {
if (!head.hasPrevious()) {
head.add(blankSymbol);
}
tsp.tapeSymbol = head.previous();
} else if (trans.direction == 1) {
head.next();
if (!head.hasNext()) {
head.add(blankSymbol);
head.previous();
}
tsp.tapeSymbol = head.next();
head.previous();
} else {
tsp.tapeSymbol = trans.to.tapeSymbol;
}
}
System.out.println(this + " --- " + tsp);
if (terminalStates.contains(tsp.state)) {
return tape;
} else {
return null;
}
}
@Override
public String toString() {
try {
int headPos = head.previousIndex();
String s = "[ ";
for (int i = 0; i <= headPos; i++) {
s += tape.get(i) + " ";
}
s += "[H] ";
for (int i = headPos + 1; i < tape.size(); i++) {
s += tape.get(i) + " ";
}
return s + "]";
} catch (Exception e) {
return "";
}
}
public static void main(String[] args) {
String init = "q0";
String blank = "b";
Set<String> term = new HashSet<String>();
term.add("qf");
Set<Transition> trans = new HashSet<Transition>();
trans.add(new Transition(new StateTapeSymbolPair("q0", "1"), new StateTapeSymbolPair("q0", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("q0", "b"), new StateTapeSymbolPair("qf", "1"), 0));
UTM machine = new UTM(trans, term, init, blank);
machine.initializeTape("111");
System.out.println("Output (si): " + machine.runTM() + "\n");
init = "a";
term.clear();
term.add("halt");
blank = "0";
trans.clear();
trans.add(new Transition(new StateTapeSymbolPair("a", "0"), new StateTapeSymbolPair("b", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("a", "1"), new StateTapeSymbolPair("c", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("b", "0"), new StateTapeSymbolPair("a", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("b", "1"), new StateTapeSymbolPair("b", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("c", "0"), new StateTapeSymbolPair("b", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("c", "1"), new StateTapeSymbolPair("halt", "1"), 0));
machine = new UTM(trans, term, init, blank);
machine.initializeTape("");
System.out.println("Output (bb): " + machine.runTM());
init = "s0";
blank = "*";
term = new HashSet<String>();
term.add("see");
trans = new HashSet<Transition>();
trans.add(new Transition(new StateTapeSymbolPair("s0", "a"), new StateTapeSymbolPair("s0", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s0", "b"), new StateTapeSymbolPair("s1", "B"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s0", "*"), new StateTapeSymbolPair("se", "*"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "a"), new StateTapeSymbolPair("s1", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "b"), new StateTapeSymbolPair("s1", "b"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "*"), new StateTapeSymbolPair("s2", "*"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "a"), new StateTapeSymbolPair("s3", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "b"), new StateTapeSymbolPair("s2", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "B"), new StateTapeSymbolPair("se", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "a"), new StateTapeSymbolPair("s3", "a"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "b"), new StateTapeSymbolPair("s3", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "B"), new StateTapeSymbolPair("s0", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("se", "a"), new StateTapeSymbolPair("se", "a"), -1));
trans.add(new Transition(new StateTapeSymbolPair("se", "*"), new StateTapeSymbolPair("see", "*"), 1));
machine = new UTM(trans, term, init, blank);
machine.initializeTape("babbababaa");
System.out.println("Output (sort): " + machine.runTM() + "\n");
}
}
|
Port the provided VB code into Java while preserving the original functionality. | Option Base 1
Public Enum sett
name_ = 1
initState
endState
blank
rules
End Enum
Public incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant
Private Sub init()
incrementer = Array("Simple incrementer", _
"q0", _
"qf", _
"B", _
Array( _
Array("q0", "1", "1", "right", "q0"), _
Array("q0", "B", "1", "stay", "qf")))
threeStateBB = Array("Three-state busy beaver", _
"a", _
"halt", _
"0", _
Array( _
Array("a", "0", "1", "right", "b"), _
Array("a", "1", "1", "left", "c"), _
Array("b", "0", "1", "left", "a"), _
Array("b", "1", "1", "right", "b"), _
Array("c", "0", "1", "left", "b"), _
Array("c", "1", "1", "stay", "halt")))
fiveStateBB = Array("Five-state busy beaver", _
"A", _
"H", _
"0", _
Array( _
Array("A", "0", "1", "right", "B"), _
Array("A", "1", "1", "left", "C"), _
Array("B", "0", "1", "right", "C"), _
Array("B", "1", "1", "right", "B"), _
Array("C", "0", "1", "right", "D"), _
Array("C", "1", "0", "left", "E"), _
Array("D", "0", "1", "left", "A"), _
Array("D", "1", "1", "left", "D"), _
Array("E", "0", "1", "stay", "H"), _
Array("E", "1", "0", "left", "A")))
End Sub
Private Sub show(state As String, headpos As Long, tape As Collection)
Debug.Print " "; state; String$(7 - Len(state), " "); "| ";
For p = 1 To tape.Count
Debug.Print IIf(p = headpos, "[" & tape(p) & "]", " " & tape(p) & " ");
Next p
Debug.Print
End Sub
Private Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)
Dim state As String: state = machine(initState)
Dim headpos As Long: headpos = 1
Dim counter As Long, rule As Variant
Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), "=")
If Not countOnly Then Debug.Print " State | Tape [head]" & vbCrLf & "---------------------"
Do While True
If headpos > tape.Count Then
tape.Add machine(blank)
Else
If headpos < 1 Then
tape.Add machine(blank), Before:=1
headpos = 1
End If
End If
If Not countOnly Then show state, headpos, tape
For i = LBound(machine(rules)) To UBound(machine(rules))
rule = machine(rules)(i)
If rule(1) = state And rule(2) = tape(headpos) Then
tape.Remove headpos
If headpos > tape.Count Then
tape.Add rule(3)
Else
tape.Add rule(3), Before:=headpos
End If
If rule(4) = "left" Then headpos = headpos - 1
If rule(4) = "right" Then headpos = headpos + 1
state = rule(5)
Exit For
End If
Next i
counter = counter + 1
If counter Mod 100000 = 0 Then
Debug.Print counter
DoEvents
DoEvents
End If
If state = machine(endState) Then Exit Do
Loop
DoEvents
If countOnly Then
Debug.Print "Steps taken: ", counter
Else
show state, headpos, tape
Debug.Print
End If
End Sub
Public Sub main()
init
Dim tap As New Collection
tap.Add "1": tap.Add "1": tap.Add "1"
UTM incrementer, tap
Set tap = New Collection
UTM threeStateBB, tap
Set tap = New Collection
UTM fiveStateBB, tap, countOnly:=-1
End Sub
| import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.List;
import java.util.Set;
import java.util.Map;
public class UTM {
private List<String> tape;
private String blankSymbol;
private ListIterator<String> head;
private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();
private Set<String> terminalStates;
private String initialState;
public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {
this.blankSymbol = blankSymbol;
for (Transition t : transitions) {
this.transitions.put(t.from, t);
}
this.terminalStates = terminalStates;
this.initialState = initialState;
}
public static class StateTapeSymbolPair {
private String state;
private String tapeSymbol;
public StateTapeSymbolPair(String state, String tapeSymbol) {
this.state = state;
this.tapeSymbol = tapeSymbol;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((state == null) ? 0 : state.hashCode());
result = prime
* result
+ ((tapeSymbol == null) ? 0 : tapeSymbol
.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StateTapeSymbolPair other = (StateTapeSymbolPair) obj;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
if (tapeSymbol == null) {
if (other.tapeSymbol != null)
return false;
} else if (!tapeSymbol.equals(other.tapeSymbol))
return false;
return true;
}
@Override
public String toString() {
return "(" + state + "," + tapeSymbol + ")";
}
}
public static class Transition {
private StateTapeSymbolPair from;
private StateTapeSymbolPair to;
private int direction;
public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {
this.from = from;
this.to = to;
this.direction = direction;
}
@Override
public String toString() {
return from + "=>" + to + "/" + direction;
}
}
public void initializeTape(List<String> input) {
tape = input;
}
public void initializeTape(String input) {
tape = new LinkedList<String>();
for (int i = 0; i < input.length(); i++) {
tape.add(input.charAt(i) + "");
}
}
public List<String> runTM() {
if (tape.size() == 0) {
tape.add(blankSymbol);
}
head = tape.listIterator();
head.next();
head.previous();
StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));
while (transitions.containsKey(tsp)) {
System.out.println(this + " --- " + transitions.get(tsp));
Transition trans = transitions.get(tsp);
head.set(trans.to.tapeSymbol);
tsp.state = trans.to.state;
if (trans.direction == -1) {
if (!head.hasPrevious()) {
head.add(blankSymbol);
}
tsp.tapeSymbol = head.previous();
} else if (trans.direction == 1) {
head.next();
if (!head.hasNext()) {
head.add(blankSymbol);
head.previous();
}
tsp.tapeSymbol = head.next();
head.previous();
} else {
tsp.tapeSymbol = trans.to.tapeSymbol;
}
}
System.out.println(this + " --- " + tsp);
if (terminalStates.contains(tsp.state)) {
return tape;
} else {
return null;
}
}
@Override
public String toString() {
try {
int headPos = head.previousIndex();
String s = "[ ";
for (int i = 0; i <= headPos; i++) {
s += tape.get(i) + " ";
}
s += "[H] ";
for (int i = headPos + 1; i < tape.size(); i++) {
s += tape.get(i) + " ";
}
return s + "]";
} catch (Exception e) {
return "";
}
}
public static void main(String[] args) {
String init = "q0";
String blank = "b";
Set<String> term = new HashSet<String>();
term.add("qf");
Set<Transition> trans = new HashSet<Transition>();
trans.add(new Transition(new StateTapeSymbolPair("q0", "1"), new StateTapeSymbolPair("q0", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("q0", "b"), new StateTapeSymbolPair("qf", "1"), 0));
UTM machine = new UTM(trans, term, init, blank);
machine.initializeTape("111");
System.out.println("Output (si): " + machine.runTM() + "\n");
init = "a";
term.clear();
term.add("halt");
blank = "0";
trans.clear();
trans.add(new Transition(new StateTapeSymbolPair("a", "0"), new StateTapeSymbolPair("b", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("a", "1"), new StateTapeSymbolPair("c", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("b", "0"), new StateTapeSymbolPair("a", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("b", "1"), new StateTapeSymbolPair("b", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("c", "0"), new StateTapeSymbolPair("b", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("c", "1"), new StateTapeSymbolPair("halt", "1"), 0));
machine = new UTM(trans, term, init, blank);
machine.initializeTape("");
System.out.println("Output (bb): " + machine.runTM());
init = "s0";
blank = "*";
term = new HashSet<String>();
term.add("see");
trans = new HashSet<Transition>();
trans.add(new Transition(new StateTapeSymbolPair("s0", "a"), new StateTapeSymbolPair("s0", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s0", "b"), new StateTapeSymbolPair("s1", "B"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s0", "*"), new StateTapeSymbolPair("se", "*"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "a"), new StateTapeSymbolPair("s1", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "b"), new StateTapeSymbolPair("s1", "b"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "*"), new StateTapeSymbolPair("s2", "*"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "a"), new StateTapeSymbolPair("s3", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "b"), new StateTapeSymbolPair("s2", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "B"), new StateTapeSymbolPair("se", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "a"), new StateTapeSymbolPair("s3", "a"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "b"), new StateTapeSymbolPair("s3", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "B"), new StateTapeSymbolPair("s0", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("se", "a"), new StateTapeSymbolPair("se", "a"), -1));
trans.add(new Transition(new StateTapeSymbolPair("se", "*"), new StateTapeSymbolPair("see", "*"), 1));
machine = new UTM(trans, term, init, blank);
machine.initializeTape("babbababaa");
System.out.println("Output (sort): " + machine.runTM() + "\n");
}
}
|
Produce a functionally identical Java code for the snippet given in VB. | Public Sub create_file()
Dim FileNumber As Integer
FileNumber = FreeFile
MkDir "docs"
Open "docs\output.txt" For Output As #FreeFile
Close #FreeFile
MkDir "C:\docs"
Open "C:\docs\output.txt" For Output As #FreeFile
Close #FreeFile
End Sub
| import java.io.*;
public class CreateFileTest {
public static void main(String args[]) {
try {
new File("output.txt").createNewFile();
new File(File.separator + "output.txt").createNewFile();
new File("docs").mkdir();
new File(File.separator + "docs").mkdir();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
|
Convert the following code from VB to Java, ensuring the logic remains intact. | b=_
"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" &_
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" &_
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" &_
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" &_
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" &_
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" &_
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" &_
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" &_
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" &_
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"
s="SEQUENCE:"
acnt=0:ccnt=0:gcnt=0:tcnt=0
for i=0 to len(b)-1
if (i mod 30)=0 then s = s & vbcrlf & right(" "& i+1,3)&": "
if (i mod 5)=0 then s=s& " "
m=mid(b,i+1,1)
s=s & m
select case m
case "A":acnt=acnt+1
case "C":ccnt=ccnt+1
case "G":gcnt=gcnt+1
case "T":tcnt=tcnt+1
case else
wscript.echo "error at ",i+1, m
end select
next
wscript.echo s & vbcrlf
wscript.echo "Count: A="&acnt & " C=" & ccnt & " G=" & gcnt & " T=" & tcnt
| import java.util.HashMap;
import java.util.Map;
public class orderedSequence {
public static void main(String[] args) {
Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT");
gene.runSequence();
}
}
public class Sequence {
private final String seq;
public Sequence(String sq) {
this.seq = sq;
}
public void prettyPrint() {
System.out.println("Sequence:");
int i = 0;
for ( ; i < seq.length() - 50 ; i += 50) {
System.out.printf("%5s : %s\n", i + 50, seq.substring(i, i + 50));
}
System.out.printf("%5s : %s\n", seq.length(), seq.substring(i));
}
public void displayCount() {
Map<Character, Integer> counter = new HashMap<>();
for (int i = 0 ; i < seq.length() ; ++i) {
counter.merge(seq.charAt(i), 1, Integer::sum);
}
System.out.println("Base vs. Count:");
counter.forEach(
key, value -> System.out.printf("%5s : %s\n", key, value));
System.out.printf("%5s: %s\n", "SUM", seq.length());
}
public void runSequence() {
this.prettyPrint();
this.displayCount();
}
}
|
Translate the given VB code snippet into Java without altering its behavior. | b=_
"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" &_
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" &_
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" &_
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" &_
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" &_
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" &_
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" &_
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" &_
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" &_
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"
s="SEQUENCE:"
acnt=0:ccnt=0:gcnt=0:tcnt=0
for i=0 to len(b)-1
if (i mod 30)=0 then s = s & vbcrlf & right(" "& i+1,3)&": "
if (i mod 5)=0 then s=s& " "
m=mid(b,i+1,1)
s=s & m
select case m
case "A":acnt=acnt+1
case "C":ccnt=ccnt+1
case "G":gcnt=gcnt+1
case "T":tcnt=tcnt+1
case else
wscript.echo "error at ",i+1, m
end select
next
wscript.echo s & vbcrlf
wscript.echo "Count: A="&acnt & " C=" & ccnt & " G=" & gcnt & " T=" & tcnt
| import java.util.HashMap;
import java.util.Map;
public class orderedSequence {
public static void main(String[] args) {
Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT");
gene.runSequence();
}
}
public class Sequence {
private final String seq;
public Sequence(String sq) {
this.seq = sq;
}
public void prettyPrint() {
System.out.println("Sequence:");
int i = 0;
for ( ; i < seq.length() - 50 ; i += 50) {
System.out.printf("%5s : %s\n", i + 50, seq.substring(i, i + 50));
}
System.out.printf("%5s : %s\n", seq.length(), seq.substring(i));
}
public void displayCount() {
Map<Character, Integer> counter = new HashMap<>();
for (int i = 0 ; i < seq.length() ; ++i) {
counter.merge(seq.charAt(i), 1, Integer::sum);
}
System.out.println("Base vs. Count:");
counter.forEach(
key, value -> System.out.printf("%5s : %s\n", key, value));
System.out.printf("%5s: %s\n", "SUM", seq.length());
}
public void runSequence() {
this.prettyPrint();
this.displayCount();
}
}
|
Write the same code in Java as shown below in VB. |
Public Const HOLDON = False
Public Const DIJKSTRASOLUTION = True
Public Const X = 10
Public Const GETS = 0
Public Const PUTS = 1
Public Const EATS = 2
Public Const THKS = 5
Public Const FRSTFORK = 0
Public Const SCNDFORK = 1
Public Const SPAGHETI = 0
Public Const UNIVERSE = 1
Public Const MAXCOUNT = 100000
Public Const PHILOSOPHERS = 5
Public semaphore(PHILOSOPHERS - 1) As Integer
Public positi0n(1, PHILOSOPHERS - 1) As Integer
Public programcounter(PHILOSOPHERS - 1) As Long
Public statistics(PHILOSOPHERS - 1, 5, 1) As Long
Public names As Variant
Private Sub init()
names = [{"Aquinas","Babbage","Carroll","Derrida","Erasmus"}]
For j = 0 To PHILOSOPHERS - 2
positi0n(0, j) = j + 1
positi0n(1, j) = j
Next j
If DIJKSTRASOLUTION Then
positi0n(0, PHILOSOPHERS - 1) = j
positi0n(1, PHILOSOPHERS - 1) = 0
Else
positi0n(0, PHILOSOPHERS - 1) = 0
positi0n(1, PHILOSOPHERS - 1) = j
End If
End Sub
Private Sub philosopher(subject As Integer, verb As Integer, objekt As Integer)
statistics(subject, verb, objekt) = statistics(subject, verb, objekt) + 1
If verb < 2 Then
If semaphore(positi0n(objekt, subject)) <> verb Then
If Not HOLDON Then
semaphore(positi0n(FRSTFORK, subject)) = 1 - objekt
programcounter(subject) = 0
End If
Else
semaphore(positi0n(objekt, subject)) = 1 - verb
programcounter(subject) = (programcounter(subject) + 1) Mod 6
End If
Else
programcounter(subject) = IIf(X * Rnd > 1, verb, verb + 1) Mod 6
End If
End Sub
Private Sub dine()
Dim ph As Integer
Do While TC < MAXCOUNT
For ph = 0 To PHILOSOPHERS - 1
Select Case programcounter(ph)
Case 0: philosopher ph, GETS, FRSTFORK
Case 1: philosopher ph, GETS, SCNDFORK
Case 2: philosopher ph, EATS, SPAGHETI
Case 3: philosopher ph, PUTS, FRSTFORK
Case 4: philosopher ph, PUTS, SCNDFORK
Case 5: philosopher ph, THKS, UNIVERSE
End Select
TC = TC + 1
Next ph
Loop
End Sub
Private Sub show()
Debug.Print "Stats", "Gets", "Gets", "Eats", "Puts", "Puts", "Thinks"
Debug.Print "", "First", "Second", "Spag-", "First", "Second", "About"
Debug.Print "", "Fork", "Fork", "hetti", "Fork", "Fork", "Universe"
For subject = 0 To PHILOSOPHERS - 1
Debug.Print names(subject + 1),
For objekt = 0 To 1
Debug.Print statistics(subject, GETS, objekt),
Next objekt
Debug.Print statistics(subject, EATS, SPAGHETI),
For objekt = 0 To 1
Debug.Print statistics(subject, PUTS, objekt),
Next objekt
Debug.Print statistics(subject, THKS, UNIVERSE)
Next subject
End Sub
Public Sub main()
init
dine
show
End Sub
| package diningphilosophers;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
enum PhilosopherState { Get, Eat, Pon }
class Fork {
public static final int ON_TABLE = -1;
static int instances = 0;
public int id;
public AtomicInteger holder = new AtomicInteger(ON_TABLE);
Fork() { id = instances++; }
}
class Philosopher implements Runnable {
static final int maxWaitMs = 100;
static AtomicInteger token = new AtomicInteger(0);
static int instances = 0;
static Random rand = new Random();
AtomicBoolean end = new AtomicBoolean(false);
int id;
PhilosopherState state = PhilosopherState.Get;
Fork left;
Fork right;
int timesEaten = 0;
Philosopher() {
id = instances++;
left = Main.forks.get(id);
right = Main.forks.get((id+1)%Main.philosopherCount);
}
void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }
catch (InterruptedException ex) {} }
void waitForFork(Fork fork) {
do {
if (fork.holder.get() == Fork.ON_TABLE) {
fork.holder.set(id);
return;
} else {
sleep();
}
} while (true);
}
public void run() {
do {
if (state == PhilosopherState.Pon) {
state = PhilosopherState.Get;
} else {
if (token.get() == id) {
waitForFork(left);
waitForFork(right);
token.set((id+2)% Main.philosopherCount);
state = PhilosopherState.Eat;
timesEaten++;
sleep();
left.holder.set(Fork.ON_TABLE);
right.holder.set(Fork.ON_TABLE);
state = PhilosopherState.Pon;
sleep();
} else {
sleep();
}
}
} while (!end.get());
}
}
public class Main {
static final int philosopherCount = 5;
static final int runSeconds = 15;
static ArrayList<Fork> forks = new ArrayList<Fork>();
static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();
public static void main(String[] args) {
for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());
for (int i = 0 ; i < philosopherCount ; i++)
philosophers.add(new Philosopher());
for (Philosopher p : philosophers) new Thread(p).start();
long endTime = System.currentTimeMillis() + (runSeconds * 1000);
do {
StringBuilder sb = new StringBuilder("|");
for (Philosopher p : philosophers) {
sb.append(p.state.toString());
sb.append("|");
}
sb.append(" |");
for (Fork f : forks) {
int holder = f.holder.get();
sb.append(holder==-1?" ":String.format("P%02d",holder));
sb.append("|");
}
System.out.println(sb.toString());
try {Thread.sleep(1000);} catch (Exception ex) {}
} while (System.currentTimeMillis() < endTime);
for (Philosopher p : philosophers) p.end.set(true);
for (Philosopher p : philosophers)
System.out.printf("P%02d: ate %,d times, %,d/sec\n",
p.id, p.timesEaten, p.timesEaten/runSeconds);
}
}
|
Port the provided VB code into Java while preserving the original functionality. |
Dim fact()
nn1=9 : nn2=12
lim=1499999
ReDim fact(nn2)
fact(0)=1
For i=1 To nn2
fact(i)=fact(i-1)*i
Next
For base=nn1 To nn2
list=""
For i=1 To lim
s=0
t=i
Do While t<>0
d=t Mod base
s=s+fact(d)
t=t\base
Loop
If s=i Then list=list &" "& i
Next
Wscript.Echo "the factorions for base "& right(" "& base,2) &" are: "& list
Next
| public class Factorion {
public static void main(String [] args){
System.out.println("Base 9:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,9);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 10:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,10);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 11:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,11);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 12:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,12);
if(multiplied == i){
System.out.print(i + "\t");
}
}
}
public static int factorialRec(int n){
int result = 1;
return n == 0 ? result : result * n * factorialRec(n-1);
}
public static int operate(String s, int base){
int sum = 0;
String strx = fromDeci(base, Integer.parseInt(s));
for(int i = 0; i < strx.length(); i++){
if(strx.charAt(i) == 'A'){
sum += factorialRec(10);
}else if(strx.charAt(i) == 'B') {
sum += factorialRec(11);
}else if(strx.charAt(i) == 'C') {
sum += factorialRec(12);
}else {
sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));
}
}
return sum;
}
static char reVal(int num) {
if (num >= 0 && num <= 9)
return (char)(num + 48);
else
return (char)(num - 10 + 65);
}
static String fromDeci(int base, int num){
StringBuilder s = new StringBuilder();
while (num > 0) {
s.append(reVal(num % base));
num /= base;
}
return new String(new StringBuilder(s).reverse());
}
}
|
Write the same algorithm in Java as shown in this VB implementation. |
Dim fact()
nn1=9 : nn2=12
lim=1499999
ReDim fact(nn2)
fact(0)=1
For i=1 To nn2
fact(i)=fact(i-1)*i
Next
For base=nn1 To nn2
list=""
For i=1 To lim
s=0
t=i
Do While t<>0
d=t Mod base
s=s+fact(d)
t=t\base
Loop
If s=i Then list=list &" "& i
Next
Wscript.Echo "the factorions for base "& right(" "& base,2) &" are: "& list
Next
| public class Factorion {
public static void main(String [] args){
System.out.println("Base 9:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,9);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 10:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,10);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 11:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,11);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 12:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,12);
if(multiplied == i){
System.out.print(i + "\t");
}
}
}
public static int factorialRec(int n){
int result = 1;
return n == 0 ? result : result * n * factorialRec(n-1);
}
public static int operate(String s, int base){
int sum = 0;
String strx = fromDeci(base, Integer.parseInt(s));
for(int i = 0; i < strx.length(); i++){
if(strx.charAt(i) == 'A'){
sum += factorialRec(10);
}else if(strx.charAt(i) == 'B') {
sum += factorialRec(11);
}else if(strx.charAt(i) == 'C') {
sum += factorialRec(12);
}else {
sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));
}
}
return sum;
}
static char reVal(int num) {
if (num >= 0 && num <= 9)
return (char)(num + 48);
else
return (char)(num - 10 + 65);
}
static String fromDeci(int base, int num){
StringBuilder s = new StringBuilder();
while (num > 0) {
s.append(reVal(num % base));
num /= base;
}
return new String(new StringBuilder(s).reverse());
}
}
|
Convert this VB block to Java, preserving its control flow and logic. | Private Function ValidateUserWords(userstring As String) As String
Dim s As String
Dim user_words() As String
Dim command_table As Scripting.Dictionary
Set command_table = New Scripting.Dictionary
Dim abbreviations As Scripting.Dictionary
Set abbreviations = New Scripting.Dictionary
abbreviations.CompareMode = TextCompare
Dim commandtable() As String
Dim commands As String
s = s & "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
s = s & "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
s = s & "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
s = s & "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
s = s & "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
s = s & "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
s = s & "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up "
commandtable = Split(s, " ")
Dim i As Integer
For Each word In commandtable
If Len(word) > 0 Then
i = 1
Do While Mid(word, i, 1) >= "A" And Mid(word, i, 1) <= "Z"
i = i + 1
Loop
command_table.Add Key:=word, Item:=i - 1
End If
Next word
For Each word In command_table
For i = command_table(word) To Len(word)
On Error Resume Next
abbreviations.Add Key:=Left(word, i), Item:=UCase(word)
Next i
Next word
user_words() = Split(userstring, " ")
For Each word In user_words
If Len(word) > 0 Then
If abbreviations.exists(word) Then
commands = commands & abbreviations(word) & " "
Else
commands = commands & "*error* "
End If
End If
Next word
ValidateUserWords = commands
End Function
Public Sub program()
Dim guserstring As String
guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin"
Debug.Print "user words:", guserstring
Debug.Print "full words:", ValidateUserWords(guserstring)
End Sub
| import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class AbbreviationsEasy {
private static final Scanner input = new Scanner(System.in);
private static final String COMMAND_TABLE
= " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n" +
" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n" +
" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n" +
" Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n" +
" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n" +
" READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n" +
" RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
public static void main(String[] args) {
String[] cmdTableArr = COMMAND_TABLE.split("\\s+");
Map<String, Integer> cmd_table = new HashMap<String, Integer>();
for (String word : cmdTableArr) {
cmd_table.put(word, countCaps(word));
}
System.out.print("Please enter your command to verify: ");
String userInput = input.nextLine();
String[] user_input = userInput.split("\\s+");
for (String s : user_input) {
boolean match = false;
for (String cmd : cmd_table.keySet()) {
if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {
String temp = cmd.toUpperCase();
if (temp.startsWith(s.toUpperCase())) {
System.out.print(temp + " ");
match = true;
}
}
}
if (!match) {
System.out.print("*error* ");
}
}
}
private static int countCaps(String word) {
int numCaps = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
numCaps++;
}
}
return numCaps;
}
}
|
Change the following VB code into Java without altering its purpose. | Private Function ValidateUserWords(userstring As String) As String
Dim s As String
Dim user_words() As String
Dim command_table As Scripting.Dictionary
Set command_table = New Scripting.Dictionary
Dim abbreviations As Scripting.Dictionary
Set abbreviations = New Scripting.Dictionary
abbreviations.CompareMode = TextCompare
Dim commandtable() As String
Dim commands As String
s = s & "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
s = s & "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
s = s & "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
s = s & "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
s = s & "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
s = s & "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
s = s & "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up "
commandtable = Split(s, " ")
Dim i As Integer
For Each word In commandtable
If Len(word) > 0 Then
i = 1
Do While Mid(word, i, 1) >= "A" And Mid(word, i, 1) <= "Z"
i = i + 1
Loop
command_table.Add Key:=word, Item:=i - 1
End If
Next word
For Each word In command_table
For i = command_table(word) To Len(word)
On Error Resume Next
abbreviations.Add Key:=Left(word, i), Item:=UCase(word)
Next i
Next word
user_words() = Split(userstring, " ")
For Each word In user_words
If Len(word) > 0 Then
If abbreviations.exists(word) Then
commands = commands & abbreviations(word) & " "
Else
commands = commands & "*error* "
End If
End If
Next word
ValidateUserWords = commands
End Function
Public Sub program()
Dim guserstring As String
guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin"
Debug.Print "user words:", guserstring
Debug.Print "full words:", ValidateUserWords(guserstring)
End Sub
| import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class AbbreviationsEasy {
private static final Scanner input = new Scanner(System.in);
private static final String COMMAND_TABLE
= " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n" +
" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n" +
" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n" +
" Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n" +
" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n" +
" READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n" +
" RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
public static void main(String[] args) {
String[] cmdTableArr = COMMAND_TABLE.split("\\s+");
Map<String, Integer> cmd_table = new HashMap<String, Integer>();
for (String word : cmdTableArr) {
cmd_table.put(word, countCaps(word));
}
System.out.print("Please enter your command to verify: ");
String userInput = input.nextLine();
String[] user_input = userInput.split("\\s+");
for (String s : user_input) {
boolean match = false;
for (String cmd : cmd_table.keySet()) {
if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {
String temp = cmd.toUpperCase();
if (temp.startsWith(s.toUpperCase())) {
System.out.print(temp + " ");
match = true;
}
}
}
if (!match) {
System.out.print("*error* ");
}
}
}
private static int countCaps(String word) {
int numCaps = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
numCaps++;
}
}
return numCaps;
}
}
|
Change the following VB code into Java without altering its purpose. | Private Function ValidateUserWords(userstring As String) As String
Dim s As String
Dim user_words() As String
Dim command_table As Scripting.Dictionary
Set command_table = New Scripting.Dictionary
Dim abbreviations As Scripting.Dictionary
Set abbreviations = New Scripting.Dictionary
abbreviations.CompareMode = TextCompare
Dim commandtable() As String
Dim commands As String
s = s & "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
s = s & "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
s = s & "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
s = s & "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
s = s & "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
s = s & "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
s = s & "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up "
commandtable = Split(s, " ")
Dim i As Integer
For Each word In commandtable
If Len(word) > 0 Then
i = 1
Do While Mid(word, i, 1) >= "A" And Mid(word, i, 1) <= "Z"
i = i + 1
Loop
command_table.Add Key:=word, Item:=i - 1
End If
Next word
For Each word In command_table
For i = command_table(word) To Len(word)
On Error Resume Next
abbreviations.Add Key:=Left(word, i), Item:=UCase(word)
Next i
Next word
user_words() = Split(userstring, " ")
For Each word In user_words
If Len(word) > 0 Then
If abbreviations.exists(word) Then
commands = commands & abbreviations(word) & " "
Else
commands = commands & "*error* "
End If
End If
Next word
ValidateUserWords = commands
End Function
Public Sub program()
Dim guserstring As String
guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin"
Debug.Print "user words:", guserstring
Debug.Print "full words:", ValidateUserWords(guserstring)
End Sub
| import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class AbbreviationsEasy {
private static final Scanner input = new Scanner(System.in);
private static final String COMMAND_TABLE
= " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n" +
" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n" +
" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n" +
" Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n" +
" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n" +
" READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n" +
" RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
public static void main(String[] args) {
String[] cmdTableArr = COMMAND_TABLE.split("\\s+");
Map<String, Integer> cmd_table = new HashMap<String, Integer>();
for (String word : cmdTableArr) {
cmd_table.put(word, countCaps(word));
}
System.out.print("Please enter your command to verify: ");
String userInput = input.nextLine();
String[] user_input = userInput.split("\\s+");
for (String s : user_input) {
boolean match = false;
for (String cmd : cmd_table.keySet()) {
if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {
String temp = cmd.toUpperCase();
if (temp.startsWith(s.toUpperCase())) {
System.out.print(temp + " ");
match = true;
}
}
}
if (!match) {
System.out.print("*error* ");
}
}
}
private static int countCaps(String word) {
int numCaps = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
numCaps++;
}
}
return numCaps;
}
}
|
Port the provided VB code into Java while preserving the original functionality. | Imports System.Text
Module Module1
ReadOnly CODES As New Dictionary(Of Char, String) From {
{"a", "AAAAA"}, {"b", "AAAAB"}, {"c", "AAABA"}, {"d", "AAABB"}, {"e", "AABAA"},
{"f", "AABAB"}, {"g", "AABBA"}, {"h", "AABBB"}, {"i", "ABAAA"}, {"j", "ABAAB"},
{"k", "ABABA"}, {"l", "ABABB"}, {"m", "ABBAA"}, {"n", "ABBAB"}, {"o", "ABBBA"},
{"p", "ABBBB"}, {"q", "BAAAA"}, {"r", "BAAAB"}, {"s", "BAABA"}, {"t", "BAABB"},
{"u", "BABAA"}, {"v", "BABAB"}, {"w", "BABBA"}, {"x", "BABBB"}, {"y", "BBAAA"},
{"z", "BBAAB"}, {" ", "BBBAA"}
}
Function Encode(plainText As String, message As String) As String
Dim pt = plainText.ToLower()
Dim sb As New StringBuilder()
For Each c In pt
If "a" <= c AndAlso c <= "z" Then
sb.Append(CODES(c))
Else
sb.Append(CODES(" "))
End If
Next
Dim et = sb.ToString()
Dim mg = message.ToLower()
sb.Length = 0
Dim count = 0
For Each c In mg
If "a" <= c AndAlso c <= "z" Then
If et(count) = "A" Then
sb.Append(c)
Else
sb.Append(Chr(Asc(c) - 32))
End If
count += 1
If count = et.Length Then
Exit For
End If
Else
sb.Append(c)
End If
Next
Return sb.ToString()
End Function
Function Decode(message As String) As String
Dim sb As New StringBuilder
For Each c In message
If "a" <= c AndAlso c <= "z" Then
sb.Append("A")
ElseIf "A" <= c AndAlso c <= "Z" Then
sb.Append("B")
End If
Next
Dim et = sb.ToString()
sb.Length = 0
For index = 0 To et.Length - 1 Step 5
Dim quintet = et.Substring(index, 5)
Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key
sb.Append(key)
Next
Return sb.ToString()
End Function
Sub Main()
Dim plainText = "the quick brown fox jumps over the lazy dog"
Dim message =
"bacon
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space."
Dim cipherText = Encode(plainText, message)
Console.WriteLine("Cipher text ->" & Environment.NewLine & "{0}", cipherText)
Dim decodedText = Decode(cipherText)
Console.WriteLine(Environment.NewLine & "Hidden text ->" & Environment.NewLine & "{0}", decodedText)
End Sub
End Module
| import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class BaconCipher {
private static final Map<Character, String> codes;
static {
codes = new HashMap<>();
codes.putAll(Map.of(
'a', "AAAAA", 'b', "AAAAB", 'c', "AAABA", 'd', "AAABB", 'e', "AABAA",
'f', "AABAB", 'g', "AABBA", 'h', "AABBB", 'i', "ABAAA", 'j', "ABAAB"
));
codes.putAll(Map.of(
'k', "ABABA", 'l', "ABABB", 'm', "ABBAA", 'n', "ABBAB", 'o', "ABBBA",
'p', "ABBBB", 'q', "BAAAA", 'r', "BAAAB", 's', "BAABA", 't', "BAABB"
));
codes.putAll(Map.of(
'u', "BABAA", 'v', "BABAB", 'w', "BABBA", 'x', "BABBB", 'y', "BBAAA",
'z', "BBAAB", ' ', "BBBAA"
));
}
private static String encode(String plainText, String message) {
String pt = plainText.toLowerCase();
StringBuilder sb = new StringBuilder();
for (char c : pt.toCharArray()) {
if ('a' <= c && c <= 'z') sb.append(codes.get(c));
else sb.append(codes.get(' '));
}
String et = sb.toString();
String mg = message.toLowerCase();
sb.setLength(0);
int count = 0;
for (char c : mg.toCharArray()) {
if ('a' <= c && c <= 'z') {
if (et.charAt(count) == 'A') sb.append(c);
else sb.append(((char) (c - 32)));
count++;
if (count == et.length()) break;
} else sb.append(c);
}
return sb.toString();
}
private static String decode(String message) {
StringBuilder sb = new StringBuilder();
for (char c : message.toCharArray()) {
if ('a' <= c && c <= 'z') sb.append('A');
if ('A' <= c && c <= 'Z') sb.append('B');
}
String et = sb.toString();
sb.setLength(0);
for (int i = 0; i < et.length(); i += 5) {
String quintet = et.substring(i, i + 5);
Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);
sb.append(key);
}
return sb.toString();
}
public static void main(String[] args) {
String plainText = "the quick brown fox jumps over the lazy dog";
String message = "bacon's cipher is a method of steganography created by francis bacon. " +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space.";
String cipherText = encode(plainText, message);
System.out.printf("Cipher text ->\n\n%s\n", cipherText);
String decodedText = decode(cipherText);
System.out.printf("\nHidden text ->\n\n%s\n", decodedText);
}
}
|
Convert this VB block to Java, preserving its control flow and logic. | Imports System.Text
Module Module1
ReadOnly CODES As New Dictionary(Of Char, String) From {
{"a", "AAAAA"}, {"b", "AAAAB"}, {"c", "AAABA"}, {"d", "AAABB"}, {"e", "AABAA"},
{"f", "AABAB"}, {"g", "AABBA"}, {"h", "AABBB"}, {"i", "ABAAA"}, {"j", "ABAAB"},
{"k", "ABABA"}, {"l", "ABABB"}, {"m", "ABBAA"}, {"n", "ABBAB"}, {"o", "ABBBA"},
{"p", "ABBBB"}, {"q", "BAAAA"}, {"r", "BAAAB"}, {"s", "BAABA"}, {"t", "BAABB"},
{"u", "BABAA"}, {"v", "BABAB"}, {"w", "BABBA"}, {"x", "BABBB"}, {"y", "BBAAA"},
{"z", "BBAAB"}, {" ", "BBBAA"}
}
Function Encode(plainText As String, message As String) As String
Dim pt = plainText.ToLower()
Dim sb As New StringBuilder()
For Each c In pt
If "a" <= c AndAlso c <= "z" Then
sb.Append(CODES(c))
Else
sb.Append(CODES(" "))
End If
Next
Dim et = sb.ToString()
Dim mg = message.ToLower()
sb.Length = 0
Dim count = 0
For Each c In mg
If "a" <= c AndAlso c <= "z" Then
If et(count) = "A" Then
sb.Append(c)
Else
sb.Append(Chr(Asc(c) - 32))
End If
count += 1
If count = et.Length Then
Exit For
End If
Else
sb.Append(c)
End If
Next
Return sb.ToString()
End Function
Function Decode(message As String) As String
Dim sb As New StringBuilder
For Each c In message
If "a" <= c AndAlso c <= "z" Then
sb.Append("A")
ElseIf "A" <= c AndAlso c <= "Z" Then
sb.Append("B")
End If
Next
Dim et = sb.ToString()
sb.Length = 0
For index = 0 To et.Length - 1 Step 5
Dim quintet = et.Substring(index, 5)
Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key
sb.Append(key)
Next
Return sb.ToString()
End Function
Sub Main()
Dim plainText = "the quick brown fox jumps over the lazy dog"
Dim message =
"bacon
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space."
Dim cipherText = Encode(plainText, message)
Console.WriteLine("Cipher text ->" & Environment.NewLine & "{0}", cipherText)
Dim decodedText = Decode(cipherText)
Console.WriteLine(Environment.NewLine & "Hidden text ->" & Environment.NewLine & "{0}", decodedText)
End Sub
End Module
| import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class BaconCipher {
private static final Map<Character, String> codes;
static {
codes = new HashMap<>();
codes.putAll(Map.of(
'a', "AAAAA", 'b', "AAAAB", 'c', "AAABA", 'd', "AAABB", 'e', "AABAA",
'f', "AABAB", 'g', "AABBA", 'h', "AABBB", 'i', "ABAAA", 'j', "ABAAB"
));
codes.putAll(Map.of(
'k', "ABABA", 'l', "ABABB", 'm', "ABBAA", 'n', "ABBAB", 'o', "ABBBA",
'p', "ABBBB", 'q', "BAAAA", 'r', "BAAAB", 's', "BAABA", 't', "BAABB"
));
codes.putAll(Map.of(
'u', "BABAA", 'v', "BABAB", 'w', "BABBA", 'x', "BABBB", 'y', "BBAAA",
'z', "BBAAB", ' ', "BBBAA"
));
}
private static String encode(String plainText, String message) {
String pt = plainText.toLowerCase();
StringBuilder sb = new StringBuilder();
for (char c : pt.toCharArray()) {
if ('a' <= c && c <= 'z') sb.append(codes.get(c));
else sb.append(codes.get(' '));
}
String et = sb.toString();
String mg = message.toLowerCase();
sb.setLength(0);
int count = 0;
for (char c : mg.toCharArray()) {
if ('a' <= c && c <= 'z') {
if (et.charAt(count) == 'A') sb.append(c);
else sb.append(((char) (c - 32)));
count++;
if (count == et.length()) break;
} else sb.append(c);
}
return sb.toString();
}
private static String decode(String message) {
StringBuilder sb = new StringBuilder();
for (char c : message.toCharArray()) {
if ('a' <= c && c <= 'z') sb.append('A');
if ('A' <= c && c <= 'Z') sb.append('B');
}
String et = sb.toString();
sb.setLength(0);
for (int i = 0; i < et.length(); i += 5) {
String quintet = et.substring(i, i + 5);
Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);
sb.append(key);
}
return sb.toString();
}
public static void main(String[] args) {
String plainText = "the quick brown fox jumps over the lazy dog";
String message = "bacon's cipher is a method of steganography created by francis bacon. " +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space.";
String cipherText = encode(plainText, message);
System.out.printf("Cipher text ->\n\n%s\n", cipherText);
String decodedText = decode(cipherText);
System.out.printf("\nHidden text ->\n\n%s\n", decodedText);
}
}
|
Please provide an equivalent version of this VB code in Java. | Function build_spiral(n)
botcol = 0 : topcol = n - 1
botrow = 0 : toprow = n - 1
Dim matrix()
ReDim matrix(topcol,toprow)
dir = 0 : col = 0 : row = 0
For i = 0 To n*n-1
matrix(col,row) = i
Select Case dir
Case 0
If col < topcol Then
col = col + 1
Else
dir = 1 : row = row + 1 : botrow = botrow + 1
End If
Case 1
If row < toprow Then
row = row + 1
Else
dir = 2 : col = col - 1 : topcol = topcol - 1
End If
Case 2
If col > botcol Then
col = col - 1
Else
dir = 3 : row = row - 1 : toprow = toprow - 1
End If
Case 3
If row > botrow Then
row = row - 1
Else
dir = 0 : col = col + 1 : botcol = botcol + 1
End If
End Select
Next
For y = 0 To n-1
For x = 0 To n-1
WScript.StdOut.Write matrix(x,y) & vbTab
Next
WScript.StdOut.WriteLine
Next
End Function
build_spiral(CInt(WScript.Arguments(0)))
| public class Blah {
public static void main(String[] args) {
print2dArray(getSpiralArray(5));
}
public static int[][] getSpiralArray(int dimension) {
int[][] spiralArray = new int[dimension][dimension];
int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);
int j;
int sideLen = dimension;
int currNum = 0;
for (int i = 0; i < numConcentricSquares; i++) {
for (j = 0; j < sideLen; j++) {
spiralArray[i][i + j] = currNum++;
}
for (j = 1; j < sideLen; j++) {
spiralArray[i + j][dimension - 1 - i] = currNum++;
}
for (j = sideLen - 2; j > -1; j--) {
spiralArray[dimension - 1 - i][i + j] = currNum++;
}
for (j = sideLen - 2; j > 0; j--) {
spiralArray[i + j][i] = currNum++;
}
sideLen -= 2;
}
return spiralArray;
}
public static void print2dArray(int[][] array) {
for (int[] row : array) {
for (int elem : row) {
System.out.printf("%3d", elem);
}
System.out.println();
}
}
}
|
Generate an equivalent Java version of this VB code. | Private Sub optional_parameters(theRange As String, _
Optional ordering As Integer = 0, _
Optional column As Integer = 1, _
Optional reverse As Integer = 1)
ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add _
Key:=Range(theRange).Columns(column), _
SortOn:=SortOnValues, _
Order:=reverse, _
DataOption:=ordering
With ActiveSheet.Sort
.SetRange Range(theRange)
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
Public Sub main()
optional_parameters theRange:="A1:C4", ordering:=1, column:=2, reverse:=1
End Sub
| module OptionalParameters
{
typedef Type<String >.Orderer as ColumnOrderer;
typedef Type<String[]>.Orderer as RowOrderer;
static String[][] sort(String[][] table,
ColumnOrderer? orderer = Null,
Int column = 0,
Boolean reverse = False,
)
{
orderer ?:= (s1, s2) -> s1 <=> s2;
ColumnOrderer byString = reverse
? ((s1, s2) -> orderer(s1, s2).reversed)
: orderer;
RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]);
return table.sorted(byColumn);
}
void run()
{
String[][] table =
[
["c", "x", "i"],
["a", "y", "p"],
["b", "z", "a"],
];
show("original input", table);
show("by default sort on column 0", sort(table));
show("by column 2", sort(table, column=2));
show("by column 2 reversed", sort(table, column=2, reverse=True));
}
void show(String title, String[][] table)
{
@Inject Console console;
console.print($"{title}:");
for (val row : table)
{
console.print($" {row}");
}
console.print();
}
}
|
Convert this VB block to Java, preserving its control flow and logic. | Declare Function CreateFileW Lib "Kernel32" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _
CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer
Declare Function WriteFile Lib "Kernel32" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _
overlapped As Ptr) As Boolean
Declare Function GetLastError Lib "Kernel32" () As Integer
Declare Function CloseHandle Lib "kernel32" (hObject As Integer) As Boolean
Const FILE_SHARE_READ = &h00000001
Const FILE_SHARE_WRITE = &h00000002
Const OPEN_EXISTING = 3
Dim fHandle As Integer = CreateFileW("C:\foo.txt", 0, FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)
If fHandle > 0 Then
Dim mb As MemoryBlock = "Hello, World!"
Dim bytesWritten As Integer
If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then
MsgBox("Error Number: " + Str(GetLastError))
End If
Call CloseHandle(fHandle)
Else
MsgBox("Error Number: " + Str(GetLastError))
End If
| public class JNIDemo
{
static
{ System.loadLibrary("JNIDemo"); }
public static void main(String[] args)
{
System.out.println(callStrdup("Hello World!"));
}
private static native String callStrdup(String s);
}
|
Translate the given VB code snippet into Java without altering its behavior. | Module Module1
Class Frac
Private ReadOnly num As Long
Private ReadOnly denom As Long
Public Shared ReadOnly ZERO = New Frac(0, 1)
Public Shared ReadOnly ONE = New Frac(1, 1)
Public Sub New(n As Long, d As Long)
If d = 0 Then
Throw New ArgumentException("d must not be zero")
End If
Dim nn = n
Dim dd = d
If nn = 0 Then
dd = 1
ElseIf dd < 0 Then
nn = -nn
dd = -dd
End If
Dim g = Math.Abs(Gcd(nn, dd))
If g > 1 Then
nn /= g
dd /= g
End If
num = nn
denom = dd
End Sub
Private Shared Function Gcd(a As Long, b As Long) As Long
If b = 0 Then
Return a
Else
Return Gcd(b, a Mod b)
End If
End Function
Public Shared Operator -(self As Frac) As Frac
Return New Frac(-self.num, self.denom)
End Operator
Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac
Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom)
End Operator
Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac
Return lhs + -rhs
End Operator
Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac
Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom)
End Operator
Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean
Dim x = lhs.num / lhs.denom
Dim y = rhs.num / rhs.denom
Return x < y
End Operator
Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean
Dim x = lhs.num / lhs.denom
Dim y = rhs.num / rhs.denom
Return x > y
End Operator
Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean
Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom
End Operator
Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean
Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom
End Operator
Public Overrides Function ToString() As String
If denom = 1 Then
Return num.ToString
Else
Return String.Format("{0}/{1}", num, denom)
End If
End Function
Public Overrides Function Equals(obj As Object) As Boolean
Dim frac = CType(obj, Frac)
Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom
End Function
End Class
Function Bernoulli(n As Integer) As Frac
If n < 0 Then
Throw New ArgumentException("n may not be negative or zero")
End If
Dim a(n + 1) As Frac
For m = 0 To n
a(m) = New Frac(1, m + 1)
For j = m To 1 Step -1
a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1)
Next
Next
If n <> 1 Then
Return a(0)
Else
Return -a(0)
End If
End Function
Function Binomial(n As Integer, k As Integer) As Integer
If n < 0 OrElse k < 0 OrElse n < k Then
Throw New ArgumentException()
End If
If n = 0 OrElse k = 0 Then
Return 1
End If
Dim num = 1
For i = k + 1 To n
num *= i
Next
Dim denom = 1
For i = 2 To n - k
denom *= i
Next
Return num \ denom
End Function
Function FaulhaberTriangle(p As Integer) As Frac()
Dim coeffs(p + 1) As Frac
For i = 1 To p + 1
coeffs(i - 1) = Frac.ZERO
Next
Dim q As New Frac(1, p + 1)
Dim sign = -1
For j = 0 To p
sign *= -1
coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j)
Next
Return coeffs
End Function
Sub Main()
For i = 1 To 10
Dim coeffs = FaulhaberTriangle(i - 1)
For Each coeff In coeffs
Console.Write("{0,5} ", coeff)
Next
Console.WriteLine()
Next
End Sub
End Module
| import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Arrays;
import java.util.stream.LongStream;
public class FaulhabersTriangle {
private static final MathContext MC = new MathContext(256);
private static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
private static class Frac implements Comparable<Frac> {
private long num;
private long denom;
public static final Frac ZERO = new Frac(0, 1);
public Frac(long n, long d) {
if (d == 0) throw new IllegalArgumentException("d must not be zero");
long nn = n;
long dd = d;
if (nn == 0) {
dd = 1;
} else if (dd < 0) {
nn = -nn;
dd = -dd;
}
long g = Math.abs(gcd(nn, dd));
if (g > 1) {
nn /= g;
dd /= g;
}
num = nn;
denom = dd;
}
public Frac plus(Frac rhs) {
return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);
}
public Frac unaryMinus() {
return new Frac(-num, denom);
}
public Frac minus(Frac rhs) {
return this.plus(rhs.unaryMinus());
}
public Frac times(Frac rhs) {
return new Frac(this.num * rhs.num, this.denom * rhs.denom);
}
@Override
public int compareTo(Frac o) {
double diff = toDouble() - o.toDouble();
return Double.compare(diff, 0.0);
}
@Override
public boolean equals(Object obj) {
return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;
}
@Override
public String toString() {
if (denom == 1) {
return Long.toString(num);
}
return String.format("%d/%d", num, denom);
}
public double toDouble() {
return (double) num / denom;
}
public BigDecimal toBigDecimal() {
return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);
}
}
private static Frac bernoulli(int n) {
if (n < 0) throw new IllegalArgumentException("n may not be negative or zero");
Frac[] a = new Frac[n + 1];
Arrays.fill(a, Frac.ZERO);
for (int m = 0; m <= n; ++m) {
a[m] = new Frac(1, m + 1);
for (int j = m; j >= 1; --j) {
a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));
}
}
if (n != 1) return a[0];
return a[0].unaryMinus();
}
private static long binomial(int n, int k) {
if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();
if (n == 0 || k == 0) return 1;
long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);
long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);
return num / den;
}
private static Frac[] faulhaberTriangle(int p) {
Frac[] coeffs = new Frac[p + 1];
Arrays.fill(coeffs, Frac.ZERO);
Frac q = new Frac(1, p + 1);
int sign = -1;
for (int j = 0; j <= p; ++j) {
sign *= -1;
coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));
}
return coeffs;
}
public static void main(String[] args) {
for (int i = 0; i <= 9; ++i) {
Frac[] coeffs = faulhaberTriangle(i);
for (Frac coeff : coeffs) {
System.out.printf("%5s ", coeff);
}
System.out.println();
}
System.out.println();
int k = 17;
Frac[] cc = faulhaberTriangle(k);
int n = 1000;
BigDecimal nn = BigDecimal.valueOf(n);
BigDecimal np = BigDecimal.ONE;
BigDecimal sum = BigDecimal.ZERO;
for (Frac c : cc) {
np = np.multiply(nn);
sum = sum.add(np.multiply(c.toBigDecimal()));
}
System.out.println(sum.toBigInteger());
}
}
|
Preserve the algorithm and functionality while converting the code from VB to Java. | Function Run(args() as String) As Integer
For each arg As String In args
Stdout.WriteLine(arg)
Next
End Function
| public class Arguments {
public static void main(String[] args) {
System.out.println("There are " + args.length + " arguments given.");
for(int i = 0; i < args.length; i++)
System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i);
}
}
|
Change the programming language of this snippet from VB to Java without modifying what it does. | Function Run(args() as String) As Integer
For each arg As String In args
Stdout.WriteLine(arg)
Next
End Function
| public class Arguments {
public static void main(String[] args) {
System.out.println("There are " + args.length + " arguments given.");
for(int i = 0; i < args.length; i++)
System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i);
}
}
|
Convert the following code from VB to Java, ensuring the logic remains intact. | Function Run(args() as String) As Integer
For each arg As String In args
Stdout.WriteLine(arg)
Next
End Function
| public class Arguments {
public static void main(String[] args) {
System.out.println("There are " + args.length + " arguments given.");
for(int i = 0; i < args.length; i++)
System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i);
}
}
|
Preserve the algorithm and functionality while converting the code from VB to Java. | DEFINT A(1 to 4) = {1, 2, 3, 4}
DEFINT B(1 to 4) = {10, 20, 30, 40}
Redim A(1 to 8) as integer
MEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)
| String[] fruits = ["apples", "oranges"];
String[] grains = ["wheat", "corn"];
String[] all = fruits + grains;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.