Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Change the following Java code into C++ without altering its purpose. | import java.util.Scanner;
public class Pigdice {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int players = 0;
while(true) {
System.out.println("Hello, welcome to Pig Dice the game! How many players? ");
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if(nextInt > 0) {
players = nextInt;
break;
}
}
else {
System.out.println("That wasn't an integer. Try again. \n");
scan.next();
}
}
System.out.println("Alright, starting with " + players + " players. \n");
play(players, scan);
scan.close();
}
public static void play(int group, Scanner scan) {
final int STRATEGIES = 5;
Dice dice = new Dice();
Player[] players = new Player[group];
for(int count = 0; count < group; count++) {
players[count] = new Player(count);
System.out.println("Player " + players[count].getNumber() + " is alive! ");
}
System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: ");
System.out.println(">> Enter '0' for a human player. ");
System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.");
System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. ");
System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. ");
System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. ");
for(Player player : players) {
System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? ");
while(true) {
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if (nextInt < Strategy.STRATEGIES.length) {
player.setStrategy(Strategy.STRATEGIES[nextInt]);
break;
}
}
else {
System.out.println("That wasn't an option. Try again. ");
scan.next();
}
}
}
int max = 0;
while(max < 100) {
for(Player player : players) {
System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. ");
player.setTurnPoints(0);
player.setMax(max);
while(true) {
Move choice = player.choose();
if(choice == Move.ROLL) {
int roll = dice.roll();
System.out.println(" A " + roll + " was rolled. ");
player.setTurnPoints(player.getTurnPoints() + roll);
player.incIter();
if(roll == 1) {
player.setTurnPoints(0);
break;
}
}
else {
System.out.println(" The player has held. ");
break;
}
}
player.addPoints(player.getTurnPoints());
System.out.println(" Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n");
player.resetIter();
if(max < player.getPoints()) {
max = player.getPoints();
}
if(max >= 100) {
System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: ");
for(Player p : players) {
System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. ");
}
break;
}
}
}
}
}
| #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
const int PLAYERS = 4, MAX_POINTS = 100;
enum Moves { ROLL, HOLD };
class player
{
public:
player() { current_score = round_score = 0; }
void addCurrScore() { current_score += round_score; }
int getCurrScore() { return current_score; }
int getRoundScore() { return round_score; }
void addRoundScore( int rs ) { round_score += rs; }
void zeroRoundScore() { round_score = 0; }
virtual int getMove() = 0;
virtual ~player() {}
protected:
int current_score, round_score;
};
class RAND_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( rand() % 10 < 5 ) return ROLL;
if( round_score > 0 ) return HOLD;
return ROLL;
}
};
class Q2WIN_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int q = MAX_POINTS - current_score;
if( q < 6 ) return ROLL;
q /= 4;
if( round_score < q ) return ROLL;
return HOLD;
}
};
class AL20_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( round_score < 20 ) return ROLL;
return HOLD;
}
};
class AL20T_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int d = ( 100 * round_score ) / 20;
if( round_score < 20 && d < rand() % 100 ) return ROLL;
return HOLD;
}
};
class Auto_pigGame
{
public:
Auto_pigGame()
{
_players[0] = new RAND_Player();
_players[1] = new Q2WIN_Player();
_players[2] = new AL20_Player();
_players[3] = new AL20T_Player();
}
~Auto_pigGame()
{
delete _players[0];
delete _players[1];
delete _players[2];
delete _players[3];
}
void play()
{
int die, p = 0;
bool endGame = false;
while( !endGame )
{
switch( _players[p]->getMove() )
{
case ROLL:
die = rand() % 6 + 1;
if( die == 1 )
{
cout << "Player " << p + 1 << " rolled " << die << " - current score: " << _players[p]->getCurrScore() << endl << endl;
nextTurn( p );
continue;
}
_players[p]->addRoundScore( die );
cout << "Player " << p + 1 << " rolled " << die << " - round score: " << _players[p]->getRoundScore() << endl;
break;
case HOLD:
_players[p]->addCurrScore();
cout << "Player " << p + 1 << " holds - current score: " << _players[p]->getCurrScore() << endl << endl;
if( _players[p]->getCurrScore() >= MAX_POINTS )
endGame = true;
else nextTurn( p );
}
}
showScore();
}
private:
void nextTurn( int& p )
{
_players[p]->zeroRoundScore();
++p %= PLAYERS;
}
void showScore()
{
cout << endl;
cout << "Player I (RAND): " << _players[0]->getCurrScore() << endl;
cout << "Player II (Q2WIN): " << _players[1]->getCurrScore() << endl;
cout << "Player III (AL20): " << _players[2]->getCurrScore() << endl;
cout << "Player IV (AL20T): " << _players[3]->getCurrScore() << endl << endl << endl;
system( "pause" );
}
player* _players[PLAYERS];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
Auto_pigGame pg;
pg.play();
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. | import java.util.Scanner;
public class Pigdice {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int players = 0;
while(true) {
System.out.println("Hello, welcome to Pig Dice the game! How many players? ");
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if(nextInt > 0) {
players = nextInt;
break;
}
}
else {
System.out.println("That wasn't an integer. Try again. \n");
scan.next();
}
}
System.out.println("Alright, starting with " + players + " players. \n");
play(players, scan);
scan.close();
}
public static void play(int group, Scanner scan) {
final int STRATEGIES = 5;
Dice dice = new Dice();
Player[] players = new Player[group];
for(int count = 0; count < group; count++) {
players[count] = new Player(count);
System.out.println("Player " + players[count].getNumber() + " is alive! ");
}
System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: ");
System.out.println(">> Enter '0' for a human player. ");
System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.");
System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. ");
System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. ");
System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. ");
for(Player player : players) {
System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? ");
while(true) {
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if (nextInt < Strategy.STRATEGIES.length) {
player.setStrategy(Strategy.STRATEGIES[nextInt]);
break;
}
}
else {
System.out.println("That wasn't an option. Try again. ");
scan.next();
}
}
}
int max = 0;
while(max < 100) {
for(Player player : players) {
System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. ");
player.setTurnPoints(0);
player.setMax(max);
while(true) {
Move choice = player.choose();
if(choice == Move.ROLL) {
int roll = dice.roll();
System.out.println(" A " + roll + " was rolled. ");
player.setTurnPoints(player.getTurnPoints() + roll);
player.incIter();
if(roll == 1) {
player.setTurnPoints(0);
break;
}
}
else {
System.out.println(" The player has held. ");
break;
}
}
player.addPoints(player.getTurnPoints());
System.out.println(" Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n");
player.resetIter();
if(max < player.getPoints()) {
max = player.getPoints();
}
if(max >= 100) {
System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: ");
for(Player p : players) {
System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. ");
}
break;
}
}
}
}
}
| #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
const int PLAYERS = 4, MAX_POINTS = 100;
enum Moves { ROLL, HOLD };
class player
{
public:
player() { current_score = round_score = 0; }
void addCurrScore() { current_score += round_score; }
int getCurrScore() { return current_score; }
int getRoundScore() { return round_score; }
void addRoundScore( int rs ) { round_score += rs; }
void zeroRoundScore() { round_score = 0; }
virtual int getMove() = 0;
virtual ~player() {}
protected:
int current_score, round_score;
};
class RAND_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( rand() % 10 < 5 ) return ROLL;
if( round_score > 0 ) return HOLD;
return ROLL;
}
};
class Q2WIN_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int q = MAX_POINTS - current_score;
if( q < 6 ) return ROLL;
q /= 4;
if( round_score < q ) return ROLL;
return HOLD;
}
};
class AL20_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( round_score < 20 ) return ROLL;
return HOLD;
}
};
class AL20T_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int d = ( 100 * round_score ) / 20;
if( round_score < 20 && d < rand() % 100 ) return ROLL;
return HOLD;
}
};
class Auto_pigGame
{
public:
Auto_pigGame()
{
_players[0] = new RAND_Player();
_players[1] = new Q2WIN_Player();
_players[2] = new AL20_Player();
_players[3] = new AL20T_Player();
}
~Auto_pigGame()
{
delete _players[0];
delete _players[1];
delete _players[2];
delete _players[3];
}
void play()
{
int die, p = 0;
bool endGame = false;
while( !endGame )
{
switch( _players[p]->getMove() )
{
case ROLL:
die = rand() % 6 + 1;
if( die == 1 )
{
cout << "Player " << p + 1 << " rolled " << die << " - current score: " << _players[p]->getCurrScore() << endl << endl;
nextTurn( p );
continue;
}
_players[p]->addRoundScore( die );
cout << "Player " << p + 1 << " rolled " << die << " - round score: " << _players[p]->getRoundScore() << endl;
break;
case HOLD:
_players[p]->addCurrScore();
cout << "Player " << p + 1 << " holds - current score: " << _players[p]->getCurrScore() << endl << endl;
if( _players[p]->getCurrScore() >= MAX_POINTS )
endGame = true;
else nextTurn( p );
}
}
showScore();
}
private:
void nextTurn( int& p )
{
_players[p]->zeroRoundScore();
++p %= PLAYERS;
}
void showScore()
{
cout << endl;
cout << "Player I (RAND): " << _players[0]->getCurrScore() << endl;
cout << "Player II (Q2WIN): " << _players[1]->getCurrScore() << endl;
cout << "Player III (AL20): " << _players[2]->getCurrScore() << endl;
cout << "Player IV (AL20T): " << _players[3]->getCurrScore() << endl << endl << endl;
system( "pause" );
}
player* _players[PLAYERS];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
Auto_pigGame pg;
pg.play();
return 0;
}
|
Change the programming language of this snippet from Java to C++ without modifying what it does. | import java.math.BigInteger;
import java.util.*;
public class Lychrel {
static Map<BigInteger, Tuple> cache = new HashMap<>();
static class Tuple {
final Boolean flag;
final BigInteger bi;
Tuple(boolean f, BigInteger b) {
flag = f;
bi = b;
}
}
static BigInteger rev(BigInteger bi) {
String s = new StringBuilder(bi.toString()).reverse().toString();
return new BigInteger(s);
}
static Tuple lychrel(BigInteger n) {
Tuple res;
if ((res = cache.get(n)) != null)
return res;
BigInteger r = rev(n);
res = new Tuple(true, n);
List<BigInteger> seen = new ArrayList<>();
for (int i = 0; i < 500; i++) {
n = n.add(r);
r = rev(n);
if (n.equals(r)) {
res = new Tuple(false, BigInteger.ZERO);
break;
}
if (cache.containsKey(n)) {
res = cache.get(n);
break;
}
seen.add(n);
}
for (BigInteger bi : seen)
cache.put(bi, res);
return res;
}
public static void main(String[] args) {
List<BigInteger> seeds = new ArrayList<>();
List<BigInteger> related = new ArrayList<>();
List<BigInteger> palin = new ArrayList<>();
for (int i = 1; i <= 10_000; i++) {
BigInteger n = BigInteger.valueOf(i);
Tuple t = lychrel(n);
if (!t.flag)
continue;
if (n.equals(t.bi))
seeds.add(t.bi);
else
related.add(t.bi);
if (n.equals(t.bi))
palin.add(t.bi);
}
System.out.printf("%d Lychrel seeds: %s%n", seeds.size(), seeds);
System.out.printf("%d Lychrel related%n", related.size());
System.out.printf("%d Lychrel palindromes: %s%n", palin.size(), palin);
}
}
| #include <iostream>
#include <map>
#include <vector>
#include <gmpxx.h>
using integer = mpz_class;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
void print_vector(const std::vector<integer>& vec) {
if (vec.empty())
return;
auto i = vec.begin();
std::cout << *i++;
for (; i != vec.end(); ++i)
std::cout << ", " << *i;
std::cout << '\n';
}
int main() {
std::map<integer, std::pair<bool, integer>> cache;
std::vector<integer> seeds, related, palindromes;
for (integer n = 1; n <= 10000; ++n) {
std::pair<bool, integer> p(true, n);
std::vector<integer> seen;
integer rev = reverse(n);
integer sum = n;
for (int i = 0; i < 500; ++i) {
sum += rev;
rev = reverse(sum);
if (rev == sum) {
p.first = false;
p.second = 0;
break;
}
auto iter = cache.find(sum);
if (iter != cache.end()) {
p = iter->second;
break;
}
seen.push_back(sum);
}
for (integer s : seen)
cache.emplace(s, p);
if (!p.first)
continue;
if (p.second == n)
seeds.push_back(n);
else
related.push_back(n);
if (n == reverse(n))
palindromes.push_back(n);
}
std::cout << "number of seeds: " << seeds.size() << '\n';
std::cout << "seeds: ";
print_vector(seeds);
std::cout << "number of related: " << related.size() << '\n';
std::cout << "palindromes: ";
print_vector(palindromes);
return 0;
}
|
Translate the given Java code snippet into C++ without altering its behavior. | import java.math.BigInteger;
import java.util.*;
public class Lychrel {
static Map<BigInteger, Tuple> cache = new HashMap<>();
static class Tuple {
final Boolean flag;
final BigInteger bi;
Tuple(boolean f, BigInteger b) {
flag = f;
bi = b;
}
}
static BigInteger rev(BigInteger bi) {
String s = new StringBuilder(bi.toString()).reverse().toString();
return new BigInteger(s);
}
static Tuple lychrel(BigInteger n) {
Tuple res;
if ((res = cache.get(n)) != null)
return res;
BigInteger r = rev(n);
res = new Tuple(true, n);
List<BigInteger> seen = new ArrayList<>();
for (int i = 0; i < 500; i++) {
n = n.add(r);
r = rev(n);
if (n.equals(r)) {
res = new Tuple(false, BigInteger.ZERO);
break;
}
if (cache.containsKey(n)) {
res = cache.get(n);
break;
}
seen.add(n);
}
for (BigInteger bi : seen)
cache.put(bi, res);
return res;
}
public static void main(String[] args) {
List<BigInteger> seeds = new ArrayList<>();
List<BigInteger> related = new ArrayList<>();
List<BigInteger> palin = new ArrayList<>();
for (int i = 1; i <= 10_000; i++) {
BigInteger n = BigInteger.valueOf(i);
Tuple t = lychrel(n);
if (!t.flag)
continue;
if (n.equals(t.bi))
seeds.add(t.bi);
else
related.add(t.bi);
if (n.equals(t.bi))
palin.add(t.bi);
}
System.out.printf("%d Lychrel seeds: %s%n", seeds.size(), seeds);
System.out.printf("%d Lychrel related%n", related.size());
System.out.printf("%d Lychrel palindromes: %s%n", palin.size(), palin);
}
}
| #include <iostream>
#include <map>
#include <vector>
#include <gmpxx.h>
using integer = mpz_class;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
void print_vector(const std::vector<integer>& vec) {
if (vec.empty())
return;
auto i = vec.begin();
std::cout << *i++;
for (; i != vec.end(); ++i)
std::cout << ", " << *i;
std::cout << '\n';
}
int main() {
std::map<integer, std::pair<bool, integer>> cache;
std::vector<integer> seeds, related, palindromes;
for (integer n = 1; n <= 10000; ++n) {
std::pair<bool, integer> p(true, n);
std::vector<integer> seen;
integer rev = reverse(n);
integer sum = n;
for (int i = 0; i < 500; ++i) {
sum += rev;
rev = reverse(sum);
if (rev == sum) {
p.first = false;
p.second = 0;
break;
}
auto iter = cache.find(sum);
if (iter != cache.end()) {
p = iter->second;
break;
}
seen.push_back(sum);
}
for (integer s : seen)
cache.emplace(s, p);
if (!p.first)
continue;
if (p.second == n)
seeds.push_back(n);
else
related.push_back(n);
if (n == reverse(n))
palindromes.push_back(n);
}
std::cout << "number of seeds: " << seeds.size() << '\n';
std::cout << "seeds: ";
print_vector(seeds);
std::cout << "number of related: " << related.size() << '\n';
std::cout << "palindromes: ";
print_vector(palindromes);
return 0;
}
|
Rewrite the snippet below in C++ so it works the same as the original Java code. | import java.util.*;
public class ErdosSelfridge {
private int[] primes;
private int[] category;
public static void main(String[] args) {
ErdosSelfridge es = new ErdosSelfridge(1000000);
System.out.println("First 200 primes:");
for (var e : es.getPrimesByCategory(200).entrySet()) {
int category = e.getKey();
List<Integer> primes = e.getValue();
System.out.printf("Category %d:\n", category);
for (int i = 0, n = primes.size(); i != n; ++i)
System.out.printf("%4d%c", primes.get(i), (i + 1) % 15 == 0 ? '\n' : ' ');
System.out.printf("\n\n");
}
System.out.println("First 1,000,000 primes:");
for (var e : es.getPrimesByCategory(1000000).entrySet()) {
int category = e.getKey();
List<Integer> primes = e.getValue();
System.out.printf("Category %2d: first = %7d last = %8d count = %d\n", category,
primes.get(0), primes.get(primes.size() - 1), primes.size());
}
}
private ErdosSelfridge(int limit) {
PrimeGenerator primeGen = new PrimeGenerator(100000, 200000);
List<Integer> primeList = new ArrayList<>();
for (int i = 0; i < limit; ++i)
primeList.add(primeGen.nextPrime());
primes = new int[primeList.size()];
for (int i = 0; i < primes.length; ++i)
primes[i] = primeList.get(i);
category = new int[primes.length];
}
private Map<Integer, List<Integer>> getPrimesByCategory(int limit) {
Map<Integer, List<Integer>> result = new TreeMap<>();
for (int i = 0; i < limit; ++i) {
var p = result.computeIfAbsent(getCategory(i), k -> new ArrayList<Integer>());
p.add(primes[i]);
}
return result;
}
private int getCategory(int index) {
if (category[index] != 0)
return category[index];
int maxCategory = 0;
int n = primes[index] + 1;
for (int i = 0; n > 1; ++i) {
int p = primes[i];
if (p * p > n)
break;
int count = 0;
for (; n % p == 0; ++count)
n /= p;
if (count != 0) {
int category = (p <= 3) ? 1 : 1 + getCategory(i);
maxCategory = Math.max(maxCategory, category);
}
}
if (n > 1) {
int category = (n <= 3) ? 1 : 1 + getCategory(getIndex(n));
maxCategory = Math.max(maxCategory, category);
}
category[index] = maxCategory;
return maxCategory;
}
private int getIndex(int prime) {
return Arrays.binarySearch(primes, prime);
}
}
| #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <map>
#include <vector>
#include <primesieve.hpp>
class erdos_selfridge {
public:
explicit erdos_selfridge(int limit);
uint64_t get_prime(int index) const { return primes_[index].first; }
int get_category(int index);
private:
std::vector<std::pair<uint64_t, int>> primes_;
size_t get_index(uint64_t prime) const;
};
erdos_selfridge::erdos_selfridge(int limit) {
primesieve::iterator iter;
for (int i = 0; i < limit; ++i)
primes_.emplace_back(iter.next_prime(), 0);
}
int erdos_selfridge::get_category(int index) {
auto& pair = primes_[index];
if (pair.second != 0)
return pair.second;
int max_category = 0;
uint64_t n = pair.first + 1;
for (int i = 0; n > 1; ++i) {
uint64_t p = primes_[i].first;
if (p * p > n)
break;
int count = 0;
for (; n % p == 0; ++count)
n /= p;
if (count != 0) {
int category = (p <= 3) ? 1 : 1 + get_category(i);
max_category = std::max(max_category, category);
}
}
if (n > 1) {
int category = (n <= 3) ? 1 : 1 + get_category(get_index(n));
max_category = std::max(max_category, category);
}
pair.second = max_category;
return max_category;
}
size_t erdos_selfridge::get_index(uint64_t prime) const {
auto it = std::lower_bound(primes_.begin(), primes_.end(), prime,
[](const std::pair<uint64_t, int>& p,
uint64_t n) { return p.first < n; });
assert(it != primes_.end());
assert(it->first == prime);
return std::distance(primes_.begin(), it);
}
auto get_primes_by_category(erdos_selfridge& es, int limit) {
std::map<int, std::vector<uint64_t>> primes_by_category;
for (int i = 0; i < limit; ++i) {
uint64_t prime = es.get_prime(i);
int category = es.get_category(i);
primes_by_category[category].push_back(prime);
}
return primes_by_category;
}
int main() {
const int limit1 = 200, limit2 = 1000000;
erdos_selfridge es(limit2);
std::cout << "First 200 primes:\n";
for (const auto& p : get_primes_by_category(es, limit1)) {
std::cout << "Category " << p.first << ":\n";
for (size_t i = 0, n = p.second.size(); i != n; ++i) {
std::cout << std::setw(4) << p.second[i]
<< ((i + 1) % 15 == 0 ? '\n' : ' ');
}
std::cout << "\n\n";
}
std::cout << "First 1,000,000 primes:\n";
for (const auto& p : get_primes_by_category(es, limit2)) {
const auto& v = p.second;
std::cout << "Category " << std::setw(2) << p.first << ": "
<< "first = " << std::setw(7) << v.front()
<< " last = " << std::setw(8) << v.back()
<< " count = " << v.size() << '\n';
}
}
|
Maintain the same structure and functionality when rewriting this code in C++. | import java.io.*;
public class SierpinskiSquareCurve {
public static void main(final String[] args) {
try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_square.svg"))) {
SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);
int size = 635, length = 5;
s.currentAngle = 0;
s.currentX = (size - length)/2;
s.currentY = length;
s.lineLength = length;
s.begin(size);
s.execute(rewrite(5));
s.end();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private SierpinskiSquareCurve(final Writer writer) {
this.writer = writer;
}
private void begin(final int size) throws IOException {
write("<svg xmlns='http:
write("<rect width='100%%' height='100%%' fill='white'/>\n");
write("<path stroke-width='1' stroke='black' fill='none' d='");
}
private void end() throws IOException {
write("'/>\n</svg>\n");
}
private void execute(final String s) throws IOException {
write("M%g,%g\n", currentX, currentY);
for (int i = 0, n = s.length(); i < n; ++i) {
switch (s.charAt(i)) {
case 'F':
line(lineLength);
break;
case '+':
turn(ANGLE);
break;
case '-':
turn(-ANGLE);
break;
}
}
}
private void line(final double length) throws IOException {
final double theta = (Math.PI * currentAngle) / 180.0;
currentX += length * Math.cos(theta);
currentY += length * Math.sin(theta);
write("L%g,%g\n", currentX, currentY);
}
private void turn(final int angle) {
currentAngle = (currentAngle + angle) % 360;
}
private void write(final String format, final Object... args) throws IOException {
writer.write(String.format(format, args));
}
private static String rewrite(final int order) {
String s = AXIOM;
for (int i = 0; i < order; ++i) {
final StringBuilder sb = new StringBuilder();
for (int j = 0, n = s.length(); j < n; ++j) {
final char ch = s.charAt(j);
if (ch == 'X')
sb.append(PRODUCTION);
else
sb.append(ch);
}
s = sb.toString();
}
return s;
}
private final Writer writer;
private double lineLength;
private double currentX;
private double currentY;
private int currentAngle;
private static final String AXIOM = "F+XF+F+XF";
private static final String PRODUCTION = "XF-F+F-XF+F+XF-F+F-X";
private static final int ANGLE = 90;
}
|
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
class sierpinski_square {
public:
void write(std::ostream& out, int size, int length, int order);
private:
static std::string rewrite(const std::string& s);
void line(std::ostream& out);
void execute(std::ostream& out, const std::string& s);
double x_;
double y_;
int angle_;
int length_;
};
void sierpinski_square::write(std::ostream& out, int size, int length, int order) {
length_ = length;
x_ = (size - length)/2;
y_ = length;
angle_ = 0;
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
std::string s = "F+XF+F+XF";
for (int i = 0; i < order; ++i)
s = rewrite(s);
execute(out, s);
out << "'/>\n</svg>\n";
}
std::string sierpinski_square::rewrite(const std::string& s) {
std::string t;
for (char c : s) {
if (c == 'X')
t += "XF-F+F-XF+F+XF-F+F-X";
else
t += c;
}
return t;
}
void sierpinski_square::line(std::ostream& out) {
double theta = (3.14159265359 * angle_)/180.0;
x_ += length_ * std::cos(theta);
y_ += length_ * std::sin(theta);
out << " L" << x_ << ',' << y_;
}
void sierpinski_square::execute(std::ostream& out, const std::string& s) {
out << 'M' << x_ << ',' << y_;
for (char c : s) {
switch (c) {
case 'F':
line(out);
break;
case '+':
angle_ = (angle_ + 90) % 360;
break;
case '-':
angle_ = (angle_ - 90) % 360;
break;
}
}
}
int main() {
std::ofstream out("sierpinski_square.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return 1;
}
sierpinski_square s;
s.write(out, 635, 5, 5);
return 0;
}
|
Write the same code in C++ as shown below in Java. | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PowerfulNumbers {
public static void main(String[] args) {
System.out.printf("Task: For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
BigInteger max = BigInteger.valueOf(10).pow(k);
List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);
System.out.printf("There are %d %d-powerful numbers between 1 and %d. %nList: %s%n", powerfulNumbers.size(), k, max, getList(powerfulNumbers));
}
System.out.printf("%nTask: For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
List<Integer> powCount = new ArrayList<>();
for ( int j = 0 ; j < k+10 ; j++ ) {
BigInteger max = BigInteger.valueOf(10).pow(j);
powCount.add(countPowerFulNumbers(max, k));
}
System.out.printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n", k, k+9, powCount);
}
}
private static String getList(List<BigInteger> list) {
StringBuilder sb = new StringBuilder();
sb.append(list.subList(0, 5).toString().replace("]", ""));
sb.append(" ... ");
sb.append(list.subList(list.size()-5, list.size()).toString().replace("[", ""));
return sb.toString();
}
private static int countPowerFulNumbers(BigInteger max, int k) {
return potentialPowerful(max, k).size();
}
private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {
List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));
Collections.sort(powerfulNumbers);
return powerfulNumbers;
}
private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {
int[] indexes = new int[k];
for ( int i = 0 ; i < k ; i++ ) {
indexes[i] = 1;
}
Set<BigInteger> powerful = new HashSet<>();
boolean foundPower = true;
while ( foundPower ) {
boolean genPowerful = false;
for ( int index = 0 ; index < k ; index++ ) {
BigInteger power = BigInteger.ONE;
for ( int i = 0 ; i < k ; i++ ) {
power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));
}
if ( power.compareTo(max) <= 0 ) {
powerful.add(power);
indexes[0] += 1;
genPowerful = true;
break;
}
else {
indexes[index] = 1;
if ( index < k-1 ) {
indexes[index+1] += 1;
}
}
}
if ( ! genPowerful ) {
foundPower = false;
}
}
return powerful;
}
}
| #include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
bool is_square_free(uint64_t n) {
static constexpr uint64_t primes[] {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
};
for (auto p : primes) {
auto p2 = p * p;
if (p2 > n)
break;
if (n % p2 == 0)
return false;
}
return true;
}
uint64_t iroot(uint64_t n, uint64_t r) {
static constexpr double adj = 1e-6;
return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);
}
uint64_t ipow(uint64_t n, uint64_t p) {
uint64_t prod = 1;
for (; p > 0; p >>= 1) {
if (p & 1)
prod *= n;
n *= n;
}
return prod;
}
std::vector<uint64_t> powerful(uint64_t n, uint64_t k) {
std::vector<uint64_t> result;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r < k) {
result.push_back(m);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))
continue;
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
std::sort(result.begin(), result.end());
return result;
}
uint64_t powerful_count(uint64_t n, uint64_t k) {
uint64_t count = 0;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r <= k) {
count += iroot(n/m, r);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (is_square_free(v) && std::gcd(m, v) == 1)
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
return count;
}
int main() {
const size_t max = 5;
for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {
auto result = powerful(p, k);
std::cout << result.size() << " " << k
<< "-powerful numbers <= 10^" << k << ":";
for (size_t i = 0; i < result.size(); ++i) {
if (i == max)
std::cout << " ...";
else if (i < max || i + max >= result.size())
std::cout << ' ' << result[i];
}
std::cout << '\n';
}
std::cout << '\n';
for (uint64_t k = 2; k <= 10; ++k) {
std::cout << "Count of " << k << "-powerful numbers <= 10^j for 0 <= j < "
<< k + 10 << ":";
for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)
std::cout << ' ' << powerful_count(p, k);
std::cout << '\n';
}
}
|
Convert this Java snippet to C++ and keep its semantics consistent. | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PowerfulNumbers {
public static void main(String[] args) {
System.out.printf("Task: For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
BigInteger max = BigInteger.valueOf(10).pow(k);
List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);
System.out.printf("There are %d %d-powerful numbers between 1 and %d. %nList: %s%n", powerfulNumbers.size(), k, max, getList(powerfulNumbers));
}
System.out.printf("%nTask: For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
List<Integer> powCount = new ArrayList<>();
for ( int j = 0 ; j < k+10 ; j++ ) {
BigInteger max = BigInteger.valueOf(10).pow(j);
powCount.add(countPowerFulNumbers(max, k));
}
System.out.printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n", k, k+9, powCount);
}
}
private static String getList(List<BigInteger> list) {
StringBuilder sb = new StringBuilder();
sb.append(list.subList(0, 5).toString().replace("]", ""));
sb.append(" ... ");
sb.append(list.subList(list.size()-5, list.size()).toString().replace("[", ""));
return sb.toString();
}
private static int countPowerFulNumbers(BigInteger max, int k) {
return potentialPowerful(max, k).size();
}
private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {
List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));
Collections.sort(powerfulNumbers);
return powerfulNumbers;
}
private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {
int[] indexes = new int[k];
for ( int i = 0 ; i < k ; i++ ) {
indexes[i] = 1;
}
Set<BigInteger> powerful = new HashSet<>();
boolean foundPower = true;
while ( foundPower ) {
boolean genPowerful = false;
for ( int index = 0 ; index < k ; index++ ) {
BigInteger power = BigInteger.ONE;
for ( int i = 0 ; i < k ; i++ ) {
power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));
}
if ( power.compareTo(max) <= 0 ) {
powerful.add(power);
indexes[0] += 1;
genPowerful = true;
break;
}
else {
indexes[index] = 1;
if ( index < k-1 ) {
indexes[index+1] += 1;
}
}
}
if ( ! genPowerful ) {
foundPower = false;
}
}
return powerful;
}
}
| #include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
bool is_square_free(uint64_t n) {
static constexpr uint64_t primes[] {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
};
for (auto p : primes) {
auto p2 = p * p;
if (p2 > n)
break;
if (n % p2 == 0)
return false;
}
return true;
}
uint64_t iroot(uint64_t n, uint64_t r) {
static constexpr double adj = 1e-6;
return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);
}
uint64_t ipow(uint64_t n, uint64_t p) {
uint64_t prod = 1;
for (; p > 0; p >>= 1) {
if (p & 1)
prod *= n;
n *= n;
}
return prod;
}
std::vector<uint64_t> powerful(uint64_t n, uint64_t k) {
std::vector<uint64_t> result;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r < k) {
result.push_back(m);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))
continue;
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
std::sort(result.begin(), result.end());
return result;
}
uint64_t powerful_count(uint64_t n, uint64_t k) {
uint64_t count = 0;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r <= k) {
count += iroot(n/m, r);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (is_square_free(v) && std::gcd(m, v) == 1)
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
return count;
}
int main() {
const size_t max = 5;
for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {
auto result = powerful(p, k);
std::cout << result.size() << " " << k
<< "-powerful numbers <= 10^" << k << ":";
for (size_t i = 0; i < result.size(); ++i) {
if (i == max)
std::cout << " ...";
else if (i < max || i + max >= result.size())
std::cout << ' ' << result[i];
}
std::cout << '\n';
}
std::cout << '\n';
for (uint64_t k = 2; k <= 10; ++k) {
std::cout << "Count of " << k << "-powerful numbers <= 10^j for 0 <= j < "
<< k + 10 << ":";
for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)
std::cout << ' ' << powerful_count(p, k);
std::cout << '\n';
}
}
|
Translate the given Java code snippet into C++ without altering its behavior. | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PowerfulNumbers {
public static void main(String[] args) {
System.out.printf("Task: For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
BigInteger max = BigInteger.valueOf(10).pow(k);
List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);
System.out.printf("There are %d %d-powerful numbers between 1 and %d. %nList: %s%n", powerfulNumbers.size(), k, max, getList(powerfulNumbers));
}
System.out.printf("%nTask: For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
List<Integer> powCount = new ArrayList<>();
for ( int j = 0 ; j < k+10 ; j++ ) {
BigInteger max = BigInteger.valueOf(10).pow(j);
powCount.add(countPowerFulNumbers(max, k));
}
System.out.printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n", k, k+9, powCount);
}
}
private static String getList(List<BigInteger> list) {
StringBuilder sb = new StringBuilder();
sb.append(list.subList(0, 5).toString().replace("]", ""));
sb.append(" ... ");
sb.append(list.subList(list.size()-5, list.size()).toString().replace("[", ""));
return sb.toString();
}
private static int countPowerFulNumbers(BigInteger max, int k) {
return potentialPowerful(max, k).size();
}
private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {
List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));
Collections.sort(powerfulNumbers);
return powerfulNumbers;
}
private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {
int[] indexes = new int[k];
for ( int i = 0 ; i < k ; i++ ) {
indexes[i] = 1;
}
Set<BigInteger> powerful = new HashSet<>();
boolean foundPower = true;
while ( foundPower ) {
boolean genPowerful = false;
for ( int index = 0 ; index < k ; index++ ) {
BigInteger power = BigInteger.ONE;
for ( int i = 0 ; i < k ; i++ ) {
power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));
}
if ( power.compareTo(max) <= 0 ) {
powerful.add(power);
indexes[0] += 1;
genPowerful = true;
break;
}
else {
indexes[index] = 1;
if ( index < k-1 ) {
indexes[index+1] += 1;
}
}
}
if ( ! genPowerful ) {
foundPower = false;
}
}
return powerful;
}
}
| #include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
bool is_square_free(uint64_t n) {
static constexpr uint64_t primes[] {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
};
for (auto p : primes) {
auto p2 = p * p;
if (p2 > n)
break;
if (n % p2 == 0)
return false;
}
return true;
}
uint64_t iroot(uint64_t n, uint64_t r) {
static constexpr double adj = 1e-6;
return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);
}
uint64_t ipow(uint64_t n, uint64_t p) {
uint64_t prod = 1;
for (; p > 0; p >>= 1) {
if (p & 1)
prod *= n;
n *= n;
}
return prod;
}
std::vector<uint64_t> powerful(uint64_t n, uint64_t k) {
std::vector<uint64_t> result;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r < k) {
result.push_back(m);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))
continue;
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
std::sort(result.begin(), result.end());
return result;
}
uint64_t powerful_count(uint64_t n, uint64_t k) {
uint64_t count = 0;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r <= k) {
count += iroot(n/m, r);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (is_square_free(v) && std::gcd(m, v) == 1)
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
return count;
}
int main() {
const size_t max = 5;
for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {
auto result = powerful(p, k);
std::cout << result.size() << " " << k
<< "-powerful numbers <= 10^" << k << ":";
for (size_t i = 0; i < result.size(); ++i) {
if (i == max)
std::cout << " ...";
else if (i < max || i + max >= result.size())
std::cout << ' ' << result[i];
}
std::cout << '\n';
}
std::cout << '\n';
for (uint64_t k = 2; k <= 10; ++k) {
std::cout << "Count of " << k << "-powerful numbers <= 10^j for 0 <= j < "
<< k + 10 << ":";
for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)
std::cout << ' ' << powerful_count(p, k);
std::cout << '\n';
}
}
|
Port the following code from Java to C++ with equivalent syntax and logic. | import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] N = {1, -12, 0, -42};
int[] D = {1, -3};
System.out.printf("%s / %s = %s",
Arrays.toString(N),
Arrays.toString(D),
Arrays.deepToString(extendedSyntheticDivision(N, D)));
}
static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {
int[] out = dividend.clone();
int normalizer = divisor[0];
for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {
out[i] /= normalizer;
int coef = out[i];
if (coef != 0) {
for (int j = 1; j < divisor.length; j++)
out[i + j] += -divisor[j] * coef;
}
}
int separator = out.length - (divisor.length - 1);
return new int[][]{
Arrays.copyOfRange(out, 0, separator),
Arrays.copyOfRange(out, separator, out.length)
};
}
}
|
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)
{
std::string r = "";
if (remainder)
{
r = " r: " + std::to_string(polynomial.back());
polynomial.pop_back();
}
std::string formatted = "";
int degree = polynomial.size() - 1;
int d = degree;
for (int i : polynomial)
{
if (d < degree)
{
if (i >= 0)
{
formatted += " + ";
}
else
{
formatted += " - ";
}
}
formatted += std::to_string(abs(i));
if (d > 1)
{
formatted += "x^" + std::to_string(d);
}
else if (d == 1)
{
formatted += "x";
}
d--;
}
return formatted;
}
std::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)
{
std::vector<int> quotient;
quotient = dividend;
int normalizer = divisor[0];
for (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)
{
quotient[i] /= normalizer;
int coef = quotient[i];
if (coef != 0)
{
for (int j = 1; j < divisor.size(); j++)
{
quotient[i + j] += -divisor[j] * coef;
}
}
}
return quotient;
}
int main(int argc, char **argv)
{
std::vector<int> dividend{ 1, -12, 0, -42};
std::vector<int> divisor{ 1, -3};
std::cout << frmtPolynomial(dividend) << "\n";
std::cout << frmtPolynomial(divisor) << "\n";
std::vector<int> quotient = syntheticDiv(dividend, divisor);
std::cout << frmtPolynomial(quotient, true) << "\n";
}
|
Change the programming language of this snippet from Java to C++ without modifying what it does. | import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] N = {1, -12, 0, -42};
int[] D = {1, -3};
System.out.printf("%s / %s = %s",
Arrays.toString(N),
Arrays.toString(D),
Arrays.deepToString(extendedSyntheticDivision(N, D)));
}
static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {
int[] out = dividend.clone();
int normalizer = divisor[0];
for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {
out[i] /= normalizer;
int coef = out[i];
if (coef != 0) {
for (int j = 1; j < divisor.length; j++)
out[i + j] += -divisor[j] * coef;
}
}
int separator = out.length - (divisor.length - 1);
return new int[][]{
Arrays.copyOfRange(out, 0, separator),
Arrays.copyOfRange(out, separator, out.length)
};
}
}
|
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)
{
std::string r = "";
if (remainder)
{
r = " r: " + std::to_string(polynomial.back());
polynomial.pop_back();
}
std::string formatted = "";
int degree = polynomial.size() - 1;
int d = degree;
for (int i : polynomial)
{
if (d < degree)
{
if (i >= 0)
{
formatted += " + ";
}
else
{
formatted += " - ";
}
}
formatted += std::to_string(abs(i));
if (d > 1)
{
formatted += "x^" + std::to_string(d);
}
else if (d == 1)
{
formatted += "x";
}
d--;
}
return formatted;
}
std::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)
{
std::vector<int> quotient;
quotient = dividend;
int normalizer = divisor[0];
for (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)
{
quotient[i] /= normalizer;
int coef = quotient[i];
if (coef != 0)
{
for (int j = 1; j < divisor.size(); j++)
{
quotient[i + j] += -divisor[j] * coef;
}
}
}
return quotient;
}
int main(int argc, char **argv)
{
std::vector<int> dividend{ 1, -12, 0, -42};
std::vector<int> divisor{ 1, -3};
std::cout << frmtPolynomial(dividend) << "\n";
std::cout << frmtPolynomial(divisor) << "\n";
std::vector<int> quotient = syntheticDiv(dividend, divisor);
std::cout << frmtPolynomial(quotient, true) << "\n";
}
|
Translate this program into C++ but keep the logic exactly as in Java. | import java.io.*;
import java.util.*;
public class OddWords {
public static void main(String[] args) {
try {
Set<String> dictionary = new TreeSet<>();
final int minLength = 5;
String fileName = "unixdict.txt";
if (args.length != 0)
fileName = args[0];
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.length() >= minLength)
dictionary.add(line);
}
}
StringBuilder word1 = new StringBuilder();
StringBuilder word2 = new StringBuilder();
List<StringPair> evenWords = new ArrayList<>();
List<StringPair> oddWords = new ArrayList<>();
for (String word : dictionary) {
int length = word.length();
if (length < minLength + 2 * (minLength/2))
continue;
word1.setLength(0);
word2.setLength(0);
for (int i = 0; i < length; ++i) {
if ((i & 1) == 0)
word1.append(word.charAt(i));
else
word2.append(word.charAt(i));
}
String oddWord = word1.toString();
String evenWord = word2.toString();
if (dictionary.contains(oddWord))
oddWords.add(new StringPair(word, oddWord));
if (dictionary.contains(evenWord))
evenWords.add(new StringPair(word, evenWord));
}
System.out.println("Odd words:");
printWords(oddWords);
System.out.println("\nEven words:");
printWords(evenWords);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printWords(List<StringPair> strings) {
int n = 1;
for (StringPair pair : strings) {
System.out.printf("%2d: %-14s%s\n", n++,
pair.string1, pair.string2);
}
}
private static class StringPair {
private String string1;
private String string2;
private StringPair(String s1, String s2) {
string1 = s1;
string2 = s2;
}
}
}
| #include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <string>
#include <utility>
#include <vector>
using word_list = std::vector<std::pair<std::string, std::string>>;
void print_words(std::ostream& out, const word_list& words) {
int n = 1;
for (const auto& pair : words) {
out << std::right << std::setw(2) << n++ << ": "
<< std::left << std::setw(14) << pair.first
<< pair.second << '\n';
}
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
const int min_length = 5;
std::string line;
std::set<std::string> dictionary;
while (getline(in, line)) {
if (line.size() >= min_length)
dictionary.insert(line);
}
word_list odd_words, even_words;
for (const std::string& word : dictionary) {
if (word.size() < min_length + 2*(min_length/2))
continue;
std::string odd_word, even_word;
for (auto w = word.begin(); w != word.end(); ++w) {
odd_word += *w;
if (++w == word.end())
break;
even_word += *w;
}
if (dictionary.find(odd_word) != dictionary.end())
odd_words.emplace_back(word, odd_word);
if (dictionary.find(even_word) != dictionary.end())
even_words.emplace_back(word, even_word);
}
std::cout << "Odd words:\n";
print_words(std::cout, odd_words);
std::cout << "\nEven words:\n";
print_words(std::cout, even_words);
return EXIT_SUCCESS;
}
|
Convert this Java block to C++, preserving its control flow and logic. | import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Arrays;
import java.util.List;
public class RamanujanConstant {
public static void main(String[] args) {
System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100));
System.out.printf("Heegner numbers yielding 'almost' integers:%n");
List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);
List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);
for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {
int heegnerNumber = heegnerNumbers.get(i);
int heegnerVal = heegnerVals.get(i);
BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));
BigDecimal compute = ramanujanConstant(heegnerNumber, 50);
System.out.printf("%3d : %50s ~ %18s (diff ~ %s)%n", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());
}
}
public static BigDecimal ramanujanConstant(int sqrt, int digits) {
MathContext mc = new MathContext(digits + 5);
return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));
}
public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {
BigDecimal e = BigDecimal.ONE;
BigDecimal ak = e;
int k = 0;
BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));
while ( true ) {
k++;
ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);
e = e.add(ak, mc);
if ( ak.compareTo(min) < 0 ) {
break;
}
}
return e;
}
public static BigDecimal bigPi(MathContext mc) {
int k = 0;
BigDecimal ak = BigDecimal.ONE;
BigDecimal a = ak;
BigDecimal b = BigDecimal.ZERO;
BigDecimal c = BigDecimal.valueOf(640320);
BigDecimal c3 = c.pow(3);
double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);
double digits = 0;
while ( digits < mc.getPrecision() ) {
k++;
digits += digitePerTerm;
BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));
BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);
ak = ak.multiply(term, mc);
a = a.add(ak, mc);
b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);
}
BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);
return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);
}
public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {
double sqrt = Math.sqrt(squareDecimal.doubleValue());
BigDecimal x0 = new BigDecimal(sqrt, mc);
BigDecimal two = BigDecimal.valueOf(2);
while ( true ) {
BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);
String x1String = x1.toPlainString();
String x0String = x0.toPlainString();
if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {
break;
}
x0 = x1;
}
return x0;
}
}
| #include <iomanip>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using big_float = boost::multiprecision::cpp_dec_float_100;
big_float f(unsigned int n) {
big_float pi(boost::math::constants::pi<big_float>());
return exp(sqrt(big_float(n)) * pi);
}
int main() {
std::cout << "Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\n"
<< std::setprecision(80) << f(163) << '\n';
std::cout << "\nResult with last four Heegner numbers:\n";
std::cout << std::setprecision(30);
for (unsigned int n : {19, 43, 67, 163}) {
auto x = f(n);
auto c = ceil(x);
auto pc = 100.0 * (x/c);
std::cout << "f(" << n << ") = " << x << " = "
<< pc << "% of " << c << '\n';
}
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Java. | import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Arrays;
import java.util.List;
public class RamanujanConstant {
public static void main(String[] args) {
System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100));
System.out.printf("Heegner numbers yielding 'almost' integers:%n");
List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);
List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);
for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {
int heegnerNumber = heegnerNumbers.get(i);
int heegnerVal = heegnerVals.get(i);
BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));
BigDecimal compute = ramanujanConstant(heegnerNumber, 50);
System.out.printf("%3d : %50s ~ %18s (diff ~ %s)%n", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());
}
}
public static BigDecimal ramanujanConstant(int sqrt, int digits) {
MathContext mc = new MathContext(digits + 5);
return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));
}
public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {
BigDecimal e = BigDecimal.ONE;
BigDecimal ak = e;
int k = 0;
BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));
while ( true ) {
k++;
ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);
e = e.add(ak, mc);
if ( ak.compareTo(min) < 0 ) {
break;
}
}
return e;
}
public static BigDecimal bigPi(MathContext mc) {
int k = 0;
BigDecimal ak = BigDecimal.ONE;
BigDecimal a = ak;
BigDecimal b = BigDecimal.ZERO;
BigDecimal c = BigDecimal.valueOf(640320);
BigDecimal c3 = c.pow(3);
double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);
double digits = 0;
while ( digits < mc.getPrecision() ) {
k++;
digits += digitePerTerm;
BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));
BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);
ak = ak.multiply(term, mc);
a = a.add(ak, mc);
b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);
}
BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);
return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);
}
public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {
double sqrt = Math.sqrt(squareDecimal.doubleValue());
BigDecimal x0 = new BigDecimal(sqrt, mc);
BigDecimal two = BigDecimal.valueOf(2);
while ( true ) {
BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);
String x1String = x1.toPlainString();
String x0String = x0.toPlainString();
if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {
break;
}
x0 = x1;
}
return x0;
}
}
| #include <iomanip>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using big_float = boost::multiprecision::cpp_dec_float_100;
big_float f(unsigned int n) {
big_float pi(boost::math::constants::pi<big_float>());
return exp(sqrt(big_float(n)) * pi);
}
int main() {
std::cout << "Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\n"
<< std::setprecision(80) << f(163) << '\n';
std::cout << "\nResult with last four Heegner numbers:\n";
std::cout << std::setprecision(30);
for (unsigned int n : {19, 43, 67, 163}) {
auto x = f(n);
auto c = ceil(x);
auto pc = 100.0 * (x/c);
std::cout << "f(" << n << ") = " << x << " = "
<< pc << "% of " << c << '\n';
}
return 0;
}
|
Generate an equivalent C++ version of this Java code. | import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class WordBreak {
public static void main(String[] args) {
List<String> dict = Arrays.asList("a", "aa", "b", "ab", "aab");
for ( String testString : Arrays.asList("aab", "aa b") ) {
List<List<String>> matches = wordBreak(testString, dict);
System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size());
for ( List<String> match : matches ) {
System.out.printf(" Word Break = %s%n", match);
}
System.out.printf("%n");
}
dict = Arrays.asList("abc", "a", "ac", "b", "c", "cb", "d");
for ( String testString : Arrays.asList("abcd", "abbc", "abcbcd", "acdbc", "abcdd") ) {
List<List<String>> matches = wordBreak(testString, dict);
System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size());
for ( List<String> match : matches ) {
System.out.printf(" Word Break = %s%n", match);
}
System.out.printf("%n");
}
}
private static List<List<String>> wordBreak(String s, List<String> dictionary) {
List<List<String>> matches = new ArrayList<>();
Queue<Node> queue = new LinkedList<>();
queue.add(new Node(s));
while ( ! queue.isEmpty() ) {
Node node = queue.remove();
if ( node.val.length() == 0 ) {
matches.add(node.parsed);
}
else {
for ( String word : dictionary ) {
if ( node.val.startsWith(word) ) {
String valNew = node.val.substring(word.length(), node.val.length());
List<String> parsedNew = new ArrayList<>();
parsedNew.addAll(node.parsed);
parsedNew.add(word);
queue.add(new Node(valNew, parsedNew));
}
}
}
}
return matches;
}
private static class Node {
private String val;
private List<String> parsed;
public Node(String initial) {
val = initial;
parsed = new ArrayList<>();
}
public Node(String s, List<String> p) {
val = s;
parsed = p;
}
}
}
| #include <algorithm>
#include <iostream>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <vector>
struct string_comparator {
using is_transparent = void;
bool operator()(const std::string& lhs, const std::string& rhs) const {
return lhs < rhs;
}
bool operator()(const std::string& lhs, const std::string_view& rhs) const {
return lhs < rhs;
}
bool operator()(const std::string_view& lhs, const std::string& rhs) const {
return lhs < rhs;
}
};
using dictionary = std::set<std::string, string_comparator>;
template <typename iterator, typename separator>
std::string join(iterator begin, iterator end, separator sep) {
std::string result;
if (begin != end) {
result += *begin++;
for (; begin != end; ++begin) {
result += sep;
result += *begin;
}
}
return result;
}
auto create_string(const std::string_view& s,
const std::vector<std::optional<size_t>>& v) {
auto idx = s.size();
std::vector<std::string_view> sv;
while (v[idx].has_value()) {
size_t prev = v[idx].value();
sv.push_back(s.substr(prev, idx - prev));
idx = prev;
}
std::reverse(sv.begin(), sv.end());
return join(sv.begin(), sv.end(), ' ');
}
std::optional<std::string> word_break(const std::string_view& str,
const dictionary& dict) {
auto size = str.size() + 1;
std::vector<std::optional<size_t>> possible(size);
auto check_word = [&dict, &str](size_t i, size_t j)
-> std::optional<size_t> {
if (dict.find(str.substr(i, j - i)) != dict.end())
return i;
return std::nullopt;
};
for (size_t i = 1; i < size; ++i) {
if (!possible[i].has_value())
possible[i] = check_word(0, i);
if (possible[i].has_value()) {
for (size_t j = i + 1; j < size; ++j) {
if (!possible[j].has_value())
possible[j] = check_word(i, j);
}
if (possible[str.size()].has_value())
return create_string(str, possible);
}
}
return std::nullopt;
}
int main(int argc, char** argv) {
dictionary dict;
dict.insert("a");
dict.insert("bc");
dict.insert("abc");
dict.insert("cd");
dict.insert("b");
auto result = word_break("abcd", dict);
if (result.has_value())
std::cout << result.value() << '\n';
return 0;
}
|
Please provide an equivalent version of this Java code in C++. | import java.util.*;
public class BrilliantNumbers {
public static void main(String[] args) {
var primesByDigits = getPrimesByDigits(100000000);
System.out.println("First 100 brilliant numbers:");
List<Integer> brilliantNumbers = new ArrayList<>();
for (var primes : primesByDigits) {
int n = primes.size();
for (int i = 0; i < n; ++i) {
int prime1 = primes.get(i);
for (int j = i; j < n; ++j) {
int prime2 = primes.get(j);
brilliantNumbers.add(prime1 * prime2);
}
}
if (brilliantNumbers.size() >= 100)
break;
}
Collections.sort(brilliantNumbers);
for (int i = 0; i < 100; ++i) {
char c = (i + 1) % 10 == 0 ? '\n' : ' ';
System.out.printf("%,5d%c", brilliantNumbers.get(i), c);
}
System.out.println();
long power = 10;
long count = 0;
for (int p = 1; p < 2 * primesByDigits.size(); ++p) {
var primes = primesByDigits.get(p / 2);
long position = count + 1;
long minProduct = 0;
int n = primes.size();
for (int i = 0; i < n; ++i) {
long prime1 = primes.get(i);
var primes2 = primes.subList(i, n);
int q = (int)((power + prime1 - 1) / prime1);
int j = Collections.binarySearch(primes2, q);
if (j == n)
continue;
if (j < 0)
j = -(j + 1);
long prime2 = primes2.get(j);
long product = prime1 * prime2;
if (minProduct == 0 || product < minProduct)
minProduct = product;
position += j;
if (prime1 >= prime2)
break;
}
System.out.printf("First brilliant number >= 10^%d is %,d at position %,d\n",
p, minProduct, position);
power *= 10;
if (p % 2 == 1) {
long size = primes.size();
count += size * (size + 1) / 2;
}
}
}
private static List<List<Integer>> getPrimesByDigits(int limit) {
PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);
List<List<Integer>> primesByDigits = new ArrayList<>();
List<Integer> primes = new ArrayList<>();
for (int p = 10; p <= limit; ) {
int prime = primeGen.nextPrime();
if (prime > p) {
primesByDigits.add(primes);
primes = new ArrayList<>();
p *= 10;
}
primes.add(prime);
}
return primesByDigits;
}
}
| #include <algorithm>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <locale>
#include <vector>
#include <primesieve.hpp>
auto get_primes_by_digits(uint64_t limit) {
primesieve::iterator pi;
std::vector<std::vector<uint64_t>> primes_by_digits;
std::vector<uint64_t> primes;
for (uint64_t p = 10; p <= limit;) {
uint64_t prime = pi.next_prime();
if (prime > p) {
primes_by_digits.push_back(std::move(primes));
p *= 10;
}
primes.push_back(prime);
}
return primes_by_digits;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
auto primes_by_digits = get_primes_by_digits(1000000000);
std::cout << "First 100 brilliant numbers:\n";
std::vector<uint64_t> brilliant_numbers;
for (const auto& primes : primes_by_digits) {
for (auto i = primes.begin(); i != primes.end(); ++i)
for (auto j = i; j != primes.end(); ++j)
brilliant_numbers.push_back(*i * *j);
if (brilliant_numbers.size() >= 100)
break;
}
std::sort(brilliant_numbers.begin(), brilliant_numbers.end());
for (size_t i = 0; i < 100; ++i) {
std::cout << std::setw(5) << brilliant_numbers[i]
<< ((i + 1) % 10 == 0 ? '\n' : ' ');
}
std::cout << '\n';
uint64_t power = 10;
size_t count = 0;
for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {
const auto& primes = primes_by_digits[p / 2];
size_t position = count + 1;
uint64_t min_product = 0;
for (auto i = primes.begin(); i != primes.end(); ++i) {
uint64_t p1 = *i;
auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);
if (j != primes.end()) {
uint64_t p2 = *j;
uint64_t product = p1 * p2;
if (min_product == 0 || product < min_product)
min_product = product;
position += std::distance(i, j);
if (p1 >= p2)
break;
}
}
std::cout << "First brilliant number >= 10^" << p << " is "
<< min_product << " at position " << position << '\n';
power *= 10;
if (p % 2 == 1) {
size_t size = primes.size();
count += size * (size + 1) / 2;
}
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Java version. | import java.util.*;
public class BrilliantNumbers {
public static void main(String[] args) {
var primesByDigits = getPrimesByDigits(100000000);
System.out.println("First 100 brilliant numbers:");
List<Integer> brilliantNumbers = new ArrayList<>();
for (var primes : primesByDigits) {
int n = primes.size();
for (int i = 0; i < n; ++i) {
int prime1 = primes.get(i);
for (int j = i; j < n; ++j) {
int prime2 = primes.get(j);
brilliantNumbers.add(prime1 * prime2);
}
}
if (brilliantNumbers.size() >= 100)
break;
}
Collections.sort(brilliantNumbers);
for (int i = 0; i < 100; ++i) {
char c = (i + 1) % 10 == 0 ? '\n' : ' ';
System.out.printf("%,5d%c", brilliantNumbers.get(i), c);
}
System.out.println();
long power = 10;
long count = 0;
for (int p = 1; p < 2 * primesByDigits.size(); ++p) {
var primes = primesByDigits.get(p / 2);
long position = count + 1;
long minProduct = 0;
int n = primes.size();
for (int i = 0; i < n; ++i) {
long prime1 = primes.get(i);
var primes2 = primes.subList(i, n);
int q = (int)((power + prime1 - 1) / prime1);
int j = Collections.binarySearch(primes2, q);
if (j == n)
continue;
if (j < 0)
j = -(j + 1);
long prime2 = primes2.get(j);
long product = prime1 * prime2;
if (minProduct == 0 || product < minProduct)
minProduct = product;
position += j;
if (prime1 >= prime2)
break;
}
System.out.printf("First brilliant number >= 10^%d is %,d at position %,d\n",
p, minProduct, position);
power *= 10;
if (p % 2 == 1) {
long size = primes.size();
count += size * (size + 1) / 2;
}
}
}
private static List<List<Integer>> getPrimesByDigits(int limit) {
PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);
List<List<Integer>> primesByDigits = new ArrayList<>();
List<Integer> primes = new ArrayList<>();
for (int p = 10; p <= limit; ) {
int prime = primeGen.nextPrime();
if (prime > p) {
primesByDigits.add(primes);
primes = new ArrayList<>();
p *= 10;
}
primes.add(prime);
}
return primesByDigits;
}
}
| #include <algorithm>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <locale>
#include <vector>
#include <primesieve.hpp>
auto get_primes_by_digits(uint64_t limit) {
primesieve::iterator pi;
std::vector<std::vector<uint64_t>> primes_by_digits;
std::vector<uint64_t> primes;
for (uint64_t p = 10; p <= limit;) {
uint64_t prime = pi.next_prime();
if (prime > p) {
primes_by_digits.push_back(std::move(primes));
p *= 10;
}
primes.push_back(prime);
}
return primes_by_digits;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
auto primes_by_digits = get_primes_by_digits(1000000000);
std::cout << "First 100 brilliant numbers:\n";
std::vector<uint64_t> brilliant_numbers;
for (const auto& primes : primes_by_digits) {
for (auto i = primes.begin(); i != primes.end(); ++i)
for (auto j = i; j != primes.end(); ++j)
brilliant_numbers.push_back(*i * *j);
if (brilliant_numbers.size() >= 100)
break;
}
std::sort(brilliant_numbers.begin(), brilliant_numbers.end());
for (size_t i = 0; i < 100; ++i) {
std::cout << std::setw(5) << brilliant_numbers[i]
<< ((i + 1) % 10 == 0 ? '\n' : ' ');
}
std::cout << '\n';
uint64_t power = 10;
size_t count = 0;
for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {
const auto& primes = primes_by_digits[p / 2];
size_t position = count + 1;
uint64_t min_product = 0;
for (auto i = primes.begin(); i != primes.end(); ++i) {
uint64_t p1 = *i;
auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);
if (j != primes.end()) {
uint64_t p2 = *j;
uint64_t product = p1 * p2;
if (min_product == 0 || product < min_product)
min_product = product;
position += std::distance(i, j);
if (p1 >= p2)
break;
}
}
std::cout << "First brilliant number >= 10^" << p << " is "
<< min_product << " at position " << position << '\n';
power *= 10;
if (p % 2 == 1) {
size_t size = primes.size();
count += size * (size + 1) / 2;
}
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
|
Produce a language-to-language conversion: from Java to C++, same semantics. | import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.stream.IntStream;
public class WordLadder {
private static int distance(String s1, String s2) {
assert s1.length() == s2.length();
return (int) IntStream.range(0, s1.length())
.filter(i -> s1.charAt(i) != s2.charAt(i))
.count();
}
private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {
wordLadder(words, fw, tw, 8);
}
private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {
if (fw.length() != tw.length()) {
throw new IllegalArgumentException("From word and to word must have the same length");
}
Set<String> ws = words.get(fw.length());
if (ws.contains(fw)) {
List<String> primeList = new ArrayList<>();
primeList.add(fw);
PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {
int cmp1 = Integer.compare(chain1.size(), chain2.size());
if (cmp1 == 0) {
String last1 = chain1.get(chain1.size() - 1);
int d1 = distance(last1, tw);
String last2 = chain2.get(chain2.size() - 1);
int d2 = distance(last2, tw);
return Integer.compare(d1, d2);
}
return cmp1;
});
queue.add(primeList);
while (queue.size() > 0) {
List<String> curr = queue.remove();
if (curr.size() > limit) {
continue;
}
String last = curr.get(curr.size() - 1);
for (String word : ws) {
if (distance(last, word) == 1) {
if (word.equals(tw)) {
curr.add(word);
System.out.println(String.join(" -> ", curr));
return;
}
if (!curr.contains(word)) {
List<String> cp = new ArrayList<>(curr);
cp.add(word);
queue.add(cp);
}
}
}
}
}
System.err.printf("Cannot turn `%s` into `%s`%n", fw, tw);
}
public static void main(String[] args) throws IOException {
Map<Integer, Set<String>> words = new HashMap<>();
for (String line : Files.readAllLines(Path.of("unixdict.txt"))) {
Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);
wl.add(line);
}
wordLadder(words, "boy", "man");
wordLadder(words, "girl", "lady");
wordLadder(words, "john", "jane");
wordLadder(words, "child", "adult");
wordLadder(words, "cat", "dog");
wordLadder(words, "lead", "gold");
wordLadder(words, "white", "black");
wordLadder(words, "bubble", "tickle", 12);
}
}
| #include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using word_map = std::map<size_t, std::vector<std::string>>;
bool one_away(const std::string& s1, const std::string& s2) {
if (s1.size() != s2.size())
return false;
bool result = false;
for (size_t i = 0, n = s1.size(); i != n; ++i) {
if (s1[i] != s2[i]) {
if (result)
return false;
result = true;
}
}
return result;
}
template <typename iterator_type, typename separator_type>
std::string join(iterator_type begin, iterator_type end,
separator_type separator) {
std::string result;
if (begin != end) {
result += *begin++;
for (; begin != end; ++begin) {
result += separator;
result += *begin;
}
}
return result;
}
bool word_ladder(const word_map& words, const std::string& from,
const std::string& to) {
auto w = words.find(from.size());
if (w != words.end()) {
auto poss = w->second;
std::vector<std::vector<std::string>> queue{{from}};
while (!queue.empty()) {
auto curr = queue.front();
queue.erase(queue.begin());
for (auto i = poss.begin(); i != poss.end();) {
if (!one_away(*i, curr.back())) {
++i;
continue;
}
if (to == *i) {
curr.push_back(to);
std::cout << join(curr.begin(), curr.end(), " -> ") << '\n';
return true;
}
std::vector<std::string> temp(curr);
temp.push_back(*i);
queue.push_back(std::move(temp));
i = poss.erase(i);
}
}
}
std::cout << from << " into " << to << " cannot be done.\n";
return false;
}
int main() {
word_map words;
std::ifstream in("unixdict.txt");
if (!in) {
std::cerr << "Cannot open file unixdict.txt.\n";
return EXIT_FAILURE;
}
std::string word;
while (getline(in, word))
words[word.size()].push_back(word);
word_ladder(words, "boy", "man");
word_ladder(words, "girl", "lady");
word_ladder(words, "john", "jane");
word_ladder(words, "child", "adult");
word_ladder(words, "cat", "dog");
word_ladder(words, "lead", "gold");
word_ladder(words, "white", "black");
word_ladder(words, "bubble", "tickle");
return EXIT_SUCCESS;
}
|
Translate this program into C++ but keep the logic exactly as in Java. | import java.util.HashMap;
import java.util.Map;
public class PrimeGaps {
private Map<Integer, Integer> gapStarts = new HashMap<>();
private int lastPrime;
private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);
public static void main(String[] args) {
final int limit = 100000000;
PrimeGaps pg = new PrimeGaps();
for (int pm = 10, gap1 = 2;;) {
int start1 = pg.findGapStart(gap1);
int gap2 = gap1 + 2;
int start2 = pg.findGapStart(gap2);
int diff = start2 > start1 ? start2 - start1 : start1 - start2;
if (diff > pm) {
System.out.printf(
"Earliest difference > %,d between adjacent prime gap starting primes:\n"
+ "Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\n\n",
pm, gap1, start1, gap2, start2, diff);
if (pm == limit)
break;
pm *= 10;
} else {
gap1 = gap2;
}
}
}
private int findGapStart(int gap) {
Integer start = gapStarts.get(gap);
if (start != null)
return start;
for (;;) {
int prev = lastPrime;
lastPrime = primeGenerator.nextPrime();
int diff = lastPrime - prev;
gapStarts.putIfAbsent(diff, prev);
if (diff == gap)
return prev;
}
}
}
| #include <iostream>
#include <locale>
#include <unordered_map>
#include <primesieve.hpp>
class prime_gaps {
public:
prime_gaps() { last_prime_ = iterator_.next_prime(); }
uint64_t find_gap_start(uint64_t gap);
private:
primesieve::iterator iterator_;
uint64_t last_prime_;
std::unordered_map<uint64_t, uint64_t> gap_starts_;
};
uint64_t prime_gaps::find_gap_start(uint64_t gap) {
auto i = gap_starts_.find(gap);
if (i != gap_starts_.end())
return i->second;
for (;;) {
uint64_t prev = last_prime_;
last_prime_ = iterator_.next_prime();
uint64_t diff = last_prime_ - prev;
gap_starts_.emplace(diff, prev);
if (gap == diff)
return prev;
}
}
int main() {
std::cout.imbue(std::locale(""));
const uint64_t limit = 100000000000;
prime_gaps pg;
for (uint64_t pm = 10, gap1 = 2;;) {
uint64_t start1 = pg.find_gap_start(gap1);
uint64_t gap2 = gap1 + 2;
uint64_t start2 = pg.find_gap_start(gap2);
uint64_t diff = start2 > start1 ? start2 - start1 : start1 - start2;
if (diff > pm) {
std::cout << "Earliest difference > " << pm
<< " between adjacent prime gap starting primes:\n"
<< "Gap " << gap1 << " starts at " << start1 << ", gap "
<< gap2 << " starts at " << start2 << ", difference is "
<< diff << ".\n\n";
if (pm == limit)
break;
pm *= 10;
} else {
gap1 = gap2;
}
}
}
|
Write the same algorithm in C++ as shown in this Java implementation. | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LatinSquaresInReducedForm {
public static void main(String[] args) {
System.out.printf("Reduced latin squares of order 4:%n");
for ( LatinSquare square : getReducedLatinSquares(4) ) {
System.out.printf("%s%n", square);
}
System.out.printf("Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n");
for ( int n = 1 ; n <= 6 ; n++ ) {
List<LatinSquare> list = getReducedLatinSquares(n);
System.out.printf("Size = %d, %d * %d * %d = %,d%n", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1));
}
}
private static long fact(int n) {
if ( n == 0 ) {
return 1;
}
int prod = 1;
for ( int i = 1 ; i <= n ; i++ ) {
prod *= i;
}
return prod;
}
private static List<LatinSquare> getReducedLatinSquares(int n) {
List<LatinSquare> squares = new ArrayList<>();
squares.add(new LatinSquare(n));
PermutationGenerator permGen = new PermutationGenerator(n);
for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) {
List<LatinSquare> squaresNext = new ArrayList<>();
for ( LatinSquare square : squares ) {
while ( permGen.hasMore() ) {
int[] perm = permGen.getNext();
if ( (perm[0]+1) != (fillRow+1) ) {
continue;
}
boolean permOk = true;
done:
for ( int row = 0 ; row < fillRow ; row++ ) {
for ( int col = 0 ; col < n ; col++ ) {
if ( square.get(row, col) == (perm[col]+1) ) {
permOk = false;
break done;
}
}
}
if ( permOk ) {
LatinSquare newSquare = new LatinSquare(square);
for ( int col = 0 ; col < n ; col++ ) {
newSquare.set(fillRow, col, perm[col]+1);
}
squaresNext.add(newSquare);
}
}
permGen.reset();
}
squares = squaresNext;
}
return squares;
}
@SuppressWarnings("unused")
private static int[] display(int[] in) {
int [] out = new int[in.length];
for ( int i = 0 ; i < in.length ; i++ ) {
out[i] = in[i] + 1;
}
return out;
}
private static class LatinSquare {
int[][] square;
int size;
public LatinSquare(int n) {
square = new int[n][n];
size = n;
for ( int col = 0 ; col < n ; col++ ) {
set(0, col, col + 1);
}
}
public LatinSquare(LatinSquare ls) {
int n = ls.size;
square = new int[n][n];
size = n;
for ( int row = 0 ; row < n ; row++ ) {
for ( int col = 0 ; col < n ; col++ ) {
set(row, col, ls.get(row, col));
}
}
}
public void set(int row, int col, int value) {
square[row][col] = value;
}
public int get(int row, int col) {
return square[row][col];
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for ( int row = 0 ; row < size ; row++ ) {
sb.append(Arrays.toString(square[row]));
sb.append("\n");
}
return sb.toString();
}
}
private static class PermutationGenerator {
private int[] a;
private BigInteger numLeft;
private BigInteger total;
public PermutationGenerator (int n) {
if (n < 1) {
throw new IllegalArgumentException ("Min 1");
}
a = new int[n];
total = getFactorial(n);
reset();
}
private void reset () {
for ( int i = 0 ; i < a.length ; i++ ) {
a[i] = i;
}
numLeft = new BigInteger(total.toString());
}
public boolean hasMore() {
return numLeft.compareTo(BigInteger.ZERO) == 1;
}
private static BigInteger getFactorial (int n) {
BigInteger fact = BigInteger.ONE;
for ( int i = n ; i > 1 ; i-- ) {
fact = fact.multiply(new BigInteger(Integer.toString(i)));
}
return fact;
}
public int[] getNext() {
if ( numLeft.equals(total) ) {
numLeft = numLeft.subtract (BigInteger.ONE);
return a;
}
int j = a.length - 2;
while ( a[j] > a[j+1] ) {
j--;
}
int k = a.length - 1;
while ( a[j] > a[k] ) {
k--;
}
int temp = a[k];
a[k] = a[j];
a[j] = temp;
int r = a.length - 1;
int s = j + 1;
while (r > s) {
int temp2 = a[s];
a[s] = a[r];
a[r] = temp2;
r--;
s++;
}
numLeft = numLeft.subtract(BigInteger.ONE);
return a;
}
}
}
| #include <algorithm>
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
typedef std::vector<std::vector<int>> matrix;
matrix dList(int n, int start) {
start--;
std::vector<int> a(n);
std::iota(a.begin(), a.end(), 0);
a[start] = a[0];
a[0] = start;
std::sort(a.begin() + 1, a.end());
auto first = a[1];
matrix r;
std::function<void(int)> recurse;
recurse = [&](int last) {
if (last == first) {
for (size_t j = 1; j < a.size(); j++) {
auto v = a[j];
if (j == v) {
return;
}
}
std::vector<int> b;
std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; });
r.push_back(b);
return;
}
for (int i = last; i >= 1; i--) {
std::swap(a[i], a[last]);
recurse(last - 1);
std::swap(a[i], a[last]);
}
};
recurse(n - 1);
return r;
}
void printSquare(const matrix &latin, int n) {
for (auto &row : latin) {
auto it = row.cbegin();
auto end = row.cend();
std::cout << '[';
if (it != end) {
std::cout << *it;
it = std::next(it);
}
while (it != end) {
std::cout << ", " << *it;
it = std::next(it);
}
std::cout << "]\n";
}
std::cout << '\n';
}
unsigned long reducedLatinSquares(int n, bool echo) {
if (n <= 0) {
if (echo) {
std::cout << "[]\n";
}
return 0;
} else if (n == 1) {
if (echo) {
std::cout << "[1]\n";
}
return 1;
}
matrix rlatin;
for (int i = 0; i < n; i++) {
rlatin.push_back({});
for (int j = 0; j < n; j++) {
rlatin[i].push_back(j);
}
}
for (int j = 0; j < n; j++) {
rlatin[0][j] = j + 1;
}
unsigned long count = 0;
std::function<void(int)> recurse;
recurse = [&](int i) {
auto rows = dList(n, i);
for (size_t r = 0; r < rows.size(); r++) {
rlatin[i - 1] = rows[r];
for (int k = 0; k < i - 1; k++) {
for (int j = 1; j < n; j++) {
if (rlatin[k][j] == rlatin[i - 1][j]) {
if (r < rows.size() - 1) {
goto outer;
}
if (i > 2) {
return;
}
}
}
}
if (i < n) {
recurse(i + 1);
} else {
count++;
if (echo) {
printSquare(rlatin, n);
}
}
outer: {}
}
};
recurse(2);
return count;
}
unsigned long factorial(unsigned long n) {
if (n <= 0) return 1;
unsigned long prod = 1;
for (unsigned long i = 2; i <= n; i++) {
prod *= i;
}
return prod;
}
int main() {
std::cout << "The four reduced lating squares of order 4 are:\n";
reducedLatinSquares(4, true);
std::cout << "The size of the set of reduced latin squares for the following orders\n";
std::cout << "and hence the total number of latin squares of these orders are:\n\n";
for (int n = 1; n < 7; n++) {
auto size = reducedLatinSquares(n, false);
auto f = factorial(n - 1);
f *= f * n * size;
std::cout << "Order " << n << ": Size " << size << " x " << n << "! x " << (n - 1) << "! => Total " << f << '\n';
}
return 0;
}
|
Produce a language-to-language conversion: from Java to C++, same semantics. | import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
public class UPC {
private static final int SEVEN = 7;
private static final Map<String, Integer> LEFT_DIGITS = Map.of(
" ## #", 0,
" ## #", 1,
" # ##", 2,
" #### #", 3,
" # ##", 4,
" ## #", 5,
" # ####", 6,
" ### ##", 7,
" ## ###", 8,
" # ##", 9
);
private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()
.stream()
.collect(Collectors.toMap(
entry -> entry.getKey()
.replace(' ', 's')
.replace('#', ' ')
.replace('s', '#'),
Map.Entry::getValue
));
private static final String END_SENTINEL = "# #";
private static final String MID_SENTINEL = " # # ";
private static void decodeUPC(String input) {
Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {
int pos = 0;
var part = candidate.substring(pos, pos + END_SENTINEL.length());
List<Integer> output = new ArrayList<>();
if (END_SENTINEL.equals(part)) {
pos += END_SENTINEL.length();
} else {
return Map.entry(false, output);
}
for (int i = 1; i < SEVEN; i++) {
part = candidate.substring(pos, pos + SEVEN);
pos += SEVEN;
if (LEFT_DIGITS.containsKey(part)) {
output.add(LEFT_DIGITS.get(part));
} else {
return Map.entry(false, output);
}
}
part = candidate.substring(pos, pos + MID_SENTINEL.length());
if (MID_SENTINEL.equals(part)) {
pos += MID_SENTINEL.length();
} else {
return Map.entry(false, output);
}
for (int i = 1; i < SEVEN; i++) {
part = candidate.substring(pos, pos + SEVEN);
pos += SEVEN;
if (RIGHT_DIGITS.containsKey(part)) {
output.add(RIGHT_DIGITS.get(part));
} else {
return Map.entry(false, output);
}
}
part = candidate.substring(pos, pos + END_SENTINEL.length());
if (!END_SENTINEL.equals(part)) {
return Map.entry(false, output);
}
int sum = 0;
for (int i = 0; i < output.size(); i++) {
if (i % 2 == 0) {
sum += 3 * output.get(i);
} else {
sum += output.get(i);
}
}
return Map.entry(sum % 10 == 0, output);
};
Consumer<List<Integer>> printList = list -> {
var it = list.iterator();
System.out.print('[');
if (it.hasNext()) {
System.out.print(it.next());
}
while (it.hasNext()) {
System.out.print(", ");
System.out.print(it.next());
}
System.out.print(']');
};
var candidate = input.trim();
var out = decode.apply(candidate);
if (out.getKey()) {
printList.accept(out.getValue());
System.out.println();
} else {
StringBuilder builder = new StringBuilder(candidate);
builder.reverse();
out = decode.apply(builder.toString());
if (out.getKey()) {
printList.accept(out.getValue());
System.out.println(" Upside down");
} else if (out.getValue().size() == 12) {
System.out.println("Invalid checksum");
} else {
System.out.println("Invalid digit(s)");
}
}
}
public static void main(String[] args) {
var barcodes = List.of(
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "
);
barcodes.forEach(UPC::decodeUPC);
}
}
| #include <iostream>
#include <locale>
#include <map>
#include <vector>
std::string trim(const std::string &str) {
auto s = str;
auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
s.erase(it1.base(), s.end());
auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
s.erase(s.begin(), it2);
return s;
}
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << ']';
}
const std::map<std::string, int> LEFT_DIGITS = {
{" ## #", 0},
{" ## #", 1},
{" # ##", 2},
{" #### #", 3},
{" # ##", 4},
{" ## #", 5},
{" # ####", 6},
{" ### ##", 7},
{" ## ###", 8},
{" # ##", 9}
};
const std::map<std::string, int> RIGHT_DIGITS = {
{"### # ", 0},
{"## ## ", 1},
{"## ## ", 2},
{"# # ", 3},
{"# ### ", 4},
{"# ### ", 5},
{"# # ", 6},
{"# # ", 7},
{"# # ", 8},
{"### # ", 9}
};
const std::string END_SENTINEL = "# #";
const std::string MID_SENTINEL = " # # ";
void decodeUPC(const std::string &input) {
auto decode = [](const std::string &candidate) {
using OT = std::vector<int>;
OT output;
size_t pos = 0;
auto part = candidate.substr(pos, END_SENTINEL.length());
if (part == END_SENTINEL) {
pos += END_SENTINEL.length();
} else {
return std::make_pair(false, OT{});
}
for (size_t i = 0; i < 6; i++) {
part = candidate.substr(pos, 7);
pos += 7;
auto e = LEFT_DIGITS.find(part);
if (e != LEFT_DIGITS.end()) {
output.push_back(e->second);
} else {
return std::make_pair(false, output);
}
}
part = candidate.substr(pos, MID_SENTINEL.length());
if (part == MID_SENTINEL) {
pos += MID_SENTINEL.length();
} else {
return std::make_pair(false, OT{});
}
for (size_t i = 0; i < 6; i++) {
part = candidate.substr(pos, 7);
pos += 7;
auto e = RIGHT_DIGITS.find(part);
if (e != RIGHT_DIGITS.end()) {
output.push_back(e->second);
} else {
return std::make_pair(false, output);
}
}
part = candidate.substr(pos, END_SENTINEL.length());
if (part == END_SENTINEL) {
pos += END_SENTINEL.length();
} else {
return std::make_pair(false, OT{});
}
int sum = 0;
for (size_t i = 0; i < output.size(); i++) {
if (i % 2 == 0) {
sum += 3 * output[i];
} else {
sum += output[i];
}
}
return std::make_pair(sum % 10 == 0, output);
};
auto candidate = trim(input);
auto out = decode(candidate);
if (out.first) {
std::cout << out.second << '\n';
} else {
std::reverse(candidate.begin(), candidate.end());
out = decode(candidate);
if (out.first) {
std::cout << out.second << " Upside down\n";
} else if (out.second.size()) {
std::cout << "Invalid checksum\n";
} else {
std::cout << "Invalid digit(s)\n";
}
}
}
int main() {
std::vector<std::string> barcodes = {
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ",
};
for (auto &barcode : barcodes) {
decodeUPC(barcode);
}
return 0;
}
|
Write the same code in C++ as shown below in Java. | import java.awt.Point;
import java.util.Scanner;
public class PlayfairCipher {
private static char[][] charTable;
private static Point[] positions;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n: ", sc, 1);
boolean changeJtoI = jti.equalsIgnoreCase("y");
createTable(key, changeJtoI);
String enc = encode(prepareText(txt, changeJtoI));
System.out.printf("%nEncoded message: %n%s%n", enc);
System.out.printf("%nDecoded message: %n%s%n", decode(enc));
}
private static String prompt(String promptText, Scanner sc, int minLen) {
String s;
do {
System.out.print(promptText);
s = sc.nextLine().trim();
} while (s.length() < minLen);
return s;
}
private static String prepareText(String s, boolean changeJtoI) {
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return changeJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTable(String key, boolean changeJtoI) {
charTable = new char[5][5];
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++) {
char c = s.charAt(i);
if (positions[c - 'A'] == null) {
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5);
k++;
}
}
}
private static String encode(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2) {
if (i == sb.length() - 1)
sb.append(sb.length() % 2 == 1 ? 'X' : "");
else if (sb.charAt(i) == sb.charAt(i + 1))
sb.insert(i + 1, 'X');
}
return codec(sb, 1);
}
private static String decode(String s) {
return codec(new StringBuilder(s), 4);
}
private static String codec(StringBuilder text, int direction) {
int len = text.length();
for (int i = 0; i < len; i += 2) {
char a = text.charAt(i);
char b = text.charAt(i + 1);
int row1 = positions[a - 'A'].y;
int row2 = positions[b - 'A'].y;
int col1 = positions[a - 'A'].x;
int col2 = positions[b - 'A'].x;
if (row1 == row2) {
col1 = (col1 + direction) % 5;
col2 = (col2 + direction) % 5;
} else if (col1 == col2) {
row1 = (row1 + direction) % 5;
row2 = (row2 + direction) % 5;
} else {
int tmp = col1;
col1 = col2;
col2 = tmp;
}
text.setCharAt(i, charTable[row1][col1]);
text.setCharAt(i + 1, charTable[row2][col2]);
}
return text.toString();
}
}
| #include <iostream>
#include <string>
using namespace std;
class playfair
{
public:
void doIt( string k, string t, bool ij, bool e )
{
createGrid( k, ij ); getTextReady( t, ij, e );
if( e ) doIt( 1 ); else doIt( -1 );
display();
}
private:
void doIt( int dir )
{
int a, b, c, d; string ntxt;
for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )
{
if( getCharPos( *ti++, a, b ) )
if( getCharPos( *ti, c, d ) )
{
if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }
else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }
else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }
}
}
_txt = ntxt;
}
void display()
{
cout << "\n\n OUTPUT:\n=========" << endl;
string::iterator si = _txt.begin(); int cnt = 0;
while( si != _txt.end() )
{
cout << *si; si++; cout << *si << " "; si++;
if( ++cnt >= 26 ) cout << endl, cnt = 0;
}
cout << endl << endl;
}
char getChar( int a, int b )
{
return _m[ (b + 5) % 5 ][ (a + 5) % 5 ];
}
bool getCharPos( char l, int &a, int &b )
{
for( int y = 0; y < 5; y++ )
for( int x = 0; x < 5; x++ )
if( _m[y][x] == l )
{ a = x; b = y; return true; }
return false;
}
void getTextReady( string t, bool ij, bool e )
{
for( string::iterator si = t.begin(); si != t.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( *si == 'J' && ij ) *si = 'I';
else if( *si == 'Q' && !ij ) continue;
_txt += *si;
}
if( e )
{
string ntxt = ""; size_t len = _txt.length();
for( size_t x = 0; x < len; x += 2 )
{
ntxt += _txt[x];
if( x + 1 < len )
{
if( _txt[x] == _txt[x + 1] ) ntxt += 'X';
ntxt += _txt[x + 1];
}
}
_txt = ntxt;
}
if( _txt.length() & 1 ) _txt += 'X';
}
void createGrid( string k, bool ij )
{
if( k.length() < 1 ) k = "KEYWORD";
k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = "";
for( string::iterator si = k.begin(); si != k.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;
if( nk.find( *si ) == -1 ) nk += *si;
}
copy( nk.begin(), nk.end(), &_m[0][0] );
}
string _txt; char _m[5][5];
};
int main( int argc, char* argv[] )
{
string key, i, txt; bool ij, e;
cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );
cout << "Enter a en/decryption key: "; getline( cin, key );
cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );
cout << "Enter the text: "; getline( cin, txt );
playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" );
}
|
Produce a functionally identical C++ code for the snippet given in Java. | import java.awt.Point;
import java.util.Scanner;
public class PlayfairCipher {
private static char[][] charTable;
private static Point[] positions;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n: ", sc, 1);
boolean changeJtoI = jti.equalsIgnoreCase("y");
createTable(key, changeJtoI);
String enc = encode(prepareText(txt, changeJtoI));
System.out.printf("%nEncoded message: %n%s%n", enc);
System.out.printf("%nDecoded message: %n%s%n", decode(enc));
}
private static String prompt(String promptText, Scanner sc, int minLen) {
String s;
do {
System.out.print(promptText);
s = sc.nextLine().trim();
} while (s.length() < minLen);
return s;
}
private static String prepareText(String s, boolean changeJtoI) {
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return changeJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTable(String key, boolean changeJtoI) {
charTable = new char[5][5];
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++) {
char c = s.charAt(i);
if (positions[c - 'A'] == null) {
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5);
k++;
}
}
}
private static String encode(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2) {
if (i == sb.length() - 1)
sb.append(sb.length() % 2 == 1 ? 'X' : "");
else if (sb.charAt(i) == sb.charAt(i + 1))
sb.insert(i + 1, 'X');
}
return codec(sb, 1);
}
private static String decode(String s) {
return codec(new StringBuilder(s), 4);
}
private static String codec(StringBuilder text, int direction) {
int len = text.length();
for (int i = 0; i < len; i += 2) {
char a = text.charAt(i);
char b = text.charAt(i + 1);
int row1 = positions[a - 'A'].y;
int row2 = positions[b - 'A'].y;
int col1 = positions[a - 'A'].x;
int col2 = positions[b - 'A'].x;
if (row1 == row2) {
col1 = (col1 + direction) % 5;
col2 = (col2 + direction) % 5;
} else if (col1 == col2) {
row1 = (row1 + direction) % 5;
row2 = (row2 + direction) % 5;
} else {
int tmp = col1;
col1 = col2;
col2 = tmp;
}
text.setCharAt(i, charTable[row1][col1]);
text.setCharAt(i + 1, charTable[row2][col2]);
}
return text.toString();
}
}
| #include <iostream>
#include <string>
using namespace std;
class playfair
{
public:
void doIt( string k, string t, bool ij, bool e )
{
createGrid( k, ij ); getTextReady( t, ij, e );
if( e ) doIt( 1 ); else doIt( -1 );
display();
}
private:
void doIt( int dir )
{
int a, b, c, d; string ntxt;
for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )
{
if( getCharPos( *ti++, a, b ) )
if( getCharPos( *ti, c, d ) )
{
if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }
else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }
else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }
}
}
_txt = ntxt;
}
void display()
{
cout << "\n\n OUTPUT:\n=========" << endl;
string::iterator si = _txt.begin(); int cnt = 0;
while( si != _txt.end() )
{
cout << *si; si++; cout << *si << " "; si++;
if( ++cnt >= 26 ) cout << endl, cnt = 0;
}
cout << endl << endl;
}
char getChar( int a, int b )
{
return _m[ (b + 5) % 5 ][ (a + 5) % 5 ];
}
bool getCharPos( char l, int &a, int &b )
{
for( int y = 0; y < 5; y++ )
for( int x = 0; x < 5; x++ )
if( _m[y][x] == l )
{ a = x; b = y; return true; }
return false;
}
void getTextReady( string t, bool ij, bool e )
{
for( string::iterator si = t.begin(); si != t.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( *si == 'J' && ij ) *si = 'I';
else if( *si == 'Q' && !ij ) continue;
_txt += *si;
}
if( e )
{
string ntxt = ""; size_t len = _txt.length();
for( size_t x = 0; x < len; x += 2 )
{
ntxt += _txt[x];
if( x + 1 < len )
{
if( _txt[x] == _txt[x + 1] ) ntxt += 'X';
ntxt += _txt[x + 1];
}
}
_txt = ntxt;
}
if( _txt.length() & 1 ) _txt += 'X';
}
void createGrid( string k, bool ij )
{
if( k.length() < 1 ) k = "KEYWORD";
k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = "";
for( string::iterator si = k.begin(); si != k.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;
if( nk.find( *si ) == -1 ) nk += *si;
}
copy( nk.begin(), nk.end(), &_m[0][0] );
}
string _txt; char _m[5][5];
};
int main( int argc, char* argv[] )
{
string key, i, txt; bool ij, e;
cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );
cout << "Enter a en/decryption key: "; getline( cin, key );
cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );
cout << "Enter the text: "; getline( cin, txt );
playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" );
}
|
Produce a language-to-language conversion: from Java to C++, same semantics. | import java.util.*;
public class ClosestPair
{
public static class Point
{
public final double x;
public final double y;
public Point(double x, double y)
{
this.x = x;
this.y = y;
}
public String toString()
{ return "(" + x + ", " + y + ")"; }
}
public static class Pair
{
public Point point1 = null;
public Point point2 = null;
public double distance = 0.0;
public Pair()
{ }
public Pair(Point point1, Point point2)
{
this.point1 = point1;
this.point2 = point2;
calcDistance();
}
public void update(Point point1, Point point2, double distance)
{
this.point1 = point1;
this.point2 = point2;
this.distance = distance;
}
public void calcDistance()
{ this.distance = distance(point1, point2); }
public String toString()
{ return point1 + "-" + point2 + " : " + distance; }
}
public static double distance(Point p1, Point p2)
{
double xdist = p2.x - p1.x;
double ydist = p2.y - p1.y;
return Math.hypot(xdist, ydist);
}
public static Pair bruteForce(List<? extends Point> points)
{
int numPoints = points.size();
if (numPoints < 2)
return null;
Pair pair = new Pair(points.get(0), points.get(1));
if (numPoints > 2)
{
for (int i = 0; i < numPoints - 1; i++)
{
Point point1 = points.get(i);
for (int j = i + 1; j < numPoints; j++)
{
Point point2 = points.get(j);
double distance = distance(point1, point2);
if (distance < pair.distance)
pair.update(point1, point2, distance);
}
}
}
return pair;
}
public static void sortByX(List<? extends Point> points)
{
Collections.sort(points, new Comparator<Point>() {
public int compare(Point point1, Point point2)
{
if (point1.x < point2.x)
return -1;
if (point1.x > point2.x)
return 1;
return 0;
}
}
);
}
public static void sortByY(List<? extends Point> points)
{
Collections.sort(points, new Comparator<Point>() {
public int compare(Point point1, Point point2)
{
if (point1.y < point2.y)
return -1;
if (point1.y > point2.y)
return 1;
return 0;
}
}
);
}
public static Pair divideAndConquer(List<? extends Point> points)
{
List<Point> pointsSortedByX = new ArrayList<Point>(points);
sortByX(pointsSortedByX);
List<Point> pointsSortedByY = new ArrayList<Point>(points);
sortByY(pointsSortedByY);
return divideAndConquer(pointsSortedByX, pointsSortedByY);
}
private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY)
{
int numPoints = pointsSortedByX.size();
if (numPoints <= 3)
return bruteForce(pointsSortedByX);
int dividingIndex = numPoints >>> 1;
List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex);
List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints);
List<Point> tempList = new ArrayList<Point>(leftOfCenter);
sortByY(tempList);
Pair closestPair = divideAndConquer(leftOfCenter, tempList);
tempList.clear();
tempList.addAll(rightOfCenter);
sortByY(tempList);
Pair closestPairRight = divideAndConquer(rightOfCenter, tempList);
if (closestPairRight.distance < closestPair.distance)
closestPair = closestPairRight;
tempList.clear();
double shortestDistance =closestPair.distance;
double centerX = rightOfCenter.get(0).x;
for (Point point : pointsSortedByY)
if (Math.abs(centerX - point.x) < shortestDistance)
tempList.add(point);
for (int i = 0; i < tempList.size() - 1; i++)
{
Point point1 = tempList.get(i);
for (int j = i + 1; j < tempList.size(); j++)
{
Point point2 = tempList.get(j);
if ((point2.y - point1.y) >= shortestDistance)
break;
double distance = distance(point1, point2);
if (distance < closestPair.distance)
{
closestPair.update(point1, point2, distance);
shortestDistance = distance;
}
}
}
return closestPair;
}
public static void main(String[] args)
{
int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]);
List<Point> points = new ArrayList<Point>();
Random r = new Random();
for (int i = 0; i < numPoints; i++)
points.add(new Point(r.nextDouble(), r.nextDouble()));
System.out.println("Generated " + numPoints + " random points");
long startTime = System.currentTimeMillis();
Pair bruteForceClosestPair = bruteForce(points);
long elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("Brute force (" + elapsedTime + " ms): " + bruteForceClosestPair);
startTime = System.currentTimeMillis();
Pair dqClosestPair = divideAndConquer(points);
elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("Divide and conquer (" + elapsedTime + " ms): " + dqClosestPair);
if (bruteForceClosestPair.distance != dqClosestPair.distance)
System.out.println("MISMATCH");
}
}
|
#include <iostream>
#include <vector>
#include <utility>
#include <cmath>
#include <random>
#include <chrono>
#include <algorithm>
#include <iterator>
typedef std::pair<double, double> point_t;
typedef std::pair<point_t, point_t> points_t;
double distance_between(const point_t& a, const point_t& b) {
return std::sqrt(std::pow(b.first - a.first, 2)
+ std::pow(b.second - a.second, 2));
}
std::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {
if (points.size() < 2) {
return { -1, { { 0, 0 }, { 0, 0 } } };
}
auto minDistance = std::abs(distance_between(points.at(0), points.at(1)));
points_t minPoints = { points.at(0), points.at(1) };
for (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {
for (auto j = i + 1; j < std::end(points); ++j) {
auto newDistance = std::abs(distance_between(*i, *j));
if (newDistance < minDistance) {
minDistance = newDistance;
minPoints.first = *i;
minPoints.second = *j;
}
}
}
return { minDistance, minPoints };
}
std::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,
const std::vector<point_t>& yP) {
if (xP.size() <= 3) {
return find_closest_brute(xP);
}
auto N = xP.size();
auto xL = std::vector<point_t>();
auto xR = std::vector<point_t>();
std::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));
std::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));
auto xM = xP.at((N-1) / 2).first;
auto yL = std::vector<point_t>();
auto yR = std::vector<point_t>();
std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {
return p.first <= xM;
});
std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {
return p.first > xM;
});
auto p1 = find_closest_optimized(xL, yL);
auto p2 = find_closest_optimized(xR, yR);
auto minPair = (p1.first <= p2.first) ? p1 : p2;
auto yS = std::vector<point_t>();
std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {
return std::abs(xM - p.first) < minPair.first;
});
auto result = minPair;
for (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {
for (auto k = i + 1; k != std::end(yS) &&
((k->second - i->second) < minPair.first); ++k) {
auto newDistance = std::abs(distance_between(*k, *i));
if (newDistance < result.first) {
result = { newDistance, { *k, *i } };
}
}
}
return result;
}
void print_point(const point_t& point) {
std::cout << "(" << point.first
<< ", " << point.second
<< ")";
}
int main(int argc, char * argv[]) {
std::default_random_engine re(std::chrono::system_clock::to_time_t(
std::chrono::system_clock::now()));
std::uniform_real_distribution<double> urd(-500.0, 500.0);
std::vector<point_t> points(100);
std::generate(std::begin(points), std::end(points), [&urd, &re]() {
return point_t { 1000 + urd(re), 1000 + urd(re) };
});
auto answer = find_closest_brute(points);
std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {
return a.first < b.first;
});
auto xP = points;
std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {
return a.second < b.second;
});
auto yP = points;
std::cout << "Min distance (brute): " << answer.first << " ";
print_point(answer.second.first);
std::cout << ", ";
print_point(answer.second.second);
answer = find_closest_optimized(xP, yP);
std::cout << "\nMin distance (optimized): " << answer.first << " ";
print_point(answer.second.first);
std::cout << ", ";
print_point(answer.second.second);
return 0;
}
|
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically? | public class Animal{
}
| class Animal
{
};
class Dog: public Animal
{
};
class Lab: public Dog
{
};
class Collie: public Dog
{
};
class Cat: public Animal
{
};
|
Convert the following code from Java to C++, ensuring the logic remains intact. | public class Animal{
}
| class Animal
{
};
class Dog: public Animal
{
};
class Lab: public Dog
{
};
class Collie: public Dog
{
};
class Cat: public Animal
{
};
|
Write a version of this Java function in C++ with identical behavior. | Map<String, Int> map = new HashMap();
map["foo"] = 5;
map["bar"] = 10;
map["baz"] = 15;
map["foo"] = 6;
| #include <map>
|
Translate the given Java code snippet into C++ without altering its behavior. | import java.math.BigInteger;
import java.util.*;
public class WilsonPrimes {
public static void main(String[] args) {
final int limit = 11000;
BigInteger[] f = new BigInteger[limit];
f[0] = BigInteger.ONE;
BigInteger factorial = BigInteger.ONE;
for (int i = 1; i < limit; ++i) {
factorial = factorial.multiply(BigInteger.valueOf(i));
f[i] = factorial;
}
List<Integer> primes = generatePrimes(limit);
System.out.printf(" n | Wilson primes\n--------------------\n");
BigInteger s = BigInteger.valueOf(-1);
for (int n = 1; n <= 11; ++n) {
System.out.printf("%2d |", n);
for (int p : primes) {
if (p >= n && f[n - 1].multiply(f[p - n]).subtract(s)
.mod(BigInteger.valueOf(p * p))
.equals(BigInteger.ZERO))
System.out.printf(" %d", p);
}
s = s.negate();
System.out.println();
}
}
private static List<Integer> generatePrimes(int limit) {
boolean[] sieve = new boolean[limit >> 1];
Arrays.fill(sieve, true);
for (int p = 3, s = 9; s < limit; p += 2) {
if (sieve[p >> 1]) {
for (int q = s; q < limit; q += p << 1)
sieve[q >> 1] = false;
}
s += (p + 1) << 2;
}
List<Integer> primes = new ArrayList<>();
if (limit > 2)
primes.add(2);
for (int i = 1; i < sieve.length; ++i) {
if (sieve[i])
primes.add((i << 1) + 1);
}
return primes;
}
}
| #include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
std::vector<int> generate_primes(int limit) {
std::vector<bool> sieve(limit >> 1, true);
for (int p = 3, s = 9; s < limit; p += 2) {
if (sieve[p >> 1]) {
for (int q = s; q < limit; q += p << 1)
sieve[q >> 1] = false;
}
s += (p + 1) << 2;
}
std::vector<int> primes;
if (limit > 2)
primes.push_back(2);
for (int i = 1; i < sieve.size(); ++i) {
if (sieve[i])
primes.push_back((i << 1) + 1);
}
return primes;
}
int main() {
using big_int = mpz_class;
const int limit = 11000;
std::vector<big_int> f{1};
f.reserve(limit);
big_int factorial = 1;
for (int i = 1; i < limit; ++i) {
factorial *= i;
f.push_back(factorial);
}
std::vector<int> primes = generate_primes(limit);
std::cout << " n | Wilson primes\n--------------------\n";
for (int n = 1, s = -1; n <= 11; ++n, s = -s) {
std::cout << std::setw(2) << n << " |";
for (int p : primes) {
if (p >= n && (f[n - 1] * f[p - n] - s) % (p * p) == 0)
std::cout << ' ' << p;
}
std::cout << '\n';
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Java version. | import java.awt.*;
import javax.swing.*;
public class ColorWheel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ColorWheelFrame frame = new ColorWheelFrame();
frame.setVisible(true);
}
});
}
private static class ColorWheelFrame extends JFrame {
private ColorWheelFrame() {
super("Color Wheel");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new ColorWheelPanel());
pack();
}
}
private static class ColorWheelPanel extends JComponent {
private ColorWheelPanel() {
setPreferredSize(new Dimension(400, 400));
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
int margin = 10;
int radius = (Math.min(w, h) - 2 * margin)/2;
int cx = w/2;
int cy = h/2;
float[] dist = {0.F, 1.0F};
g2.setColor(Color.BLACK);
g2.fillRect(0, 0, w, h);
for (int angle = 0; angle < 360; ++angle) {
Color color = hsvToRgb(angle, 1.0, 1.0);
Color[] colors = {Color.WHITE, color};
RadialGradientPaint paint = new RadialGradientPaint(cx, cy,
radius, dist, colors);
g2.setPaint(paint);
g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,
angle, 1);
}
}
}
private static Color hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - Math.abs(hp % 2.0 - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <= 1) {
r = c;
g = x;
} else if (hp <= 2) {
r = x;
g = c;
} else if (hp <= 3) {
g = c;
b = x;
} else if (hp <= 4) {
g = x;
b = c;
} else if (hp <= 5) {
r = x;
b = c;
} else {
r = c;
b = x;
}
r += m;
g += m;
b += m;
return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));
}
}
|
#include "colorwheelwidget.h"
#include <QPainter>
#include <QPaintEvent>
#include <cmath>
namespace {
QColor hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <= 1) {
r = c;
g = x;
} else if (hp <= 2) {
r = x;
g = c;
} else if (hp <= 3) {
g = c;
b = x;
} else if (hp <= 4) {
g = x;
b = c;
} else if (hp <= 5) {
r = x;
b = c;
} else {
r = c;
b = x;
}
r += m;
g += m;
b += m;
return QColor(r * 255, g * 255, b * 255);
}
}
ColorWheelWidget::ColorWheelWidget(QWidget *parent)
: QWidget(parent) {
setWindowTitle(tr("Color Wheel"));
resize(400, 400);
}
void ColorWheelWidget::paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
const QColor backgroundColor(0, 0, 0);
const QColor white(255, 255, 255);
painter.fillRect(event->rect(), backgroundColor);
const int margin = 10;
const double diameter = std::min(width(), height()) - 2*margin;
QPointF center(width()/2.0, height()/2.0);
QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,
diameter, diameter);
for (int angle = 0; angle < 360; ++angle) {
QColor color(hsvToRgb(angle, 1.0, 1.0));
QRadialGradient gradient(center, diameter/2.0);
gradient.setColorAt(0, white);
gradient.setColorAt(1, color);
QBrush brush(gradient);
QPen pen(brush, 1.0);
painter.setPen(pen);
painter.setBrush(brush);
painter.drawPie(rect, angle * 16, 16);
}
}
|
Convert this Java snippet to C++ and keep its semantics consistent. | import java.awt.*;
import javax.swing.*;
public class ColorWheel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ColorWheelFrame frame = new ColorWheelFrame();
frame.setVisible(true);
}
});
}
private static class ColorWheelFrame extends JFrame {
private ColorWheelFrame() {
super("Color Wheel");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new ColorWheelPanel());
pack();
}
}
private static class ColorWheelPanel extends JComponent {
private ColorWheelPanel() {
setPreferredSize(new Dimension(400, 400));
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
int margin = 10;
int radius = (Math.min(w, h) - 2 * margin)/2;
int cx = w/2;
int cy = h/2;
float[] dist = {0.F, 1.0F};
g2.setColor(Color.BLACK);
g2.fillRect(0, 0, w, h);
for (int angle = 0; angle < 360; ++angle) {
Color color = hsvToRgb(angle, 1.0, 1.0);
Color[] colors = {Color.WHITE, color};
RadialGradientPaint paint = new RadialGradientPaint(cx, cy,
radius, dist, colors);
g2.setPaint(paint);
g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,
angle, 1);
}
}
}
private static Color hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - Math.abs(hp % 2.0 - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <= 1) {
r = c;
g = x;
} else if (hp <= 2) {
r = x;
g = c;
} else if (hp <= 3) {
g = c;
b = x;
} else if (hp <= 4) {
g = x;
b = c;
} else if (hp <= 5) {
r = x;
b = c;
} else {
r = c;
b = x;
}
r += m;
g += m;
b += m;
return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));
}
}
|
#include "colorwheelwidget.h"
#include <QPainter>
#include <QPaintEvent>
#include <cmath>
namespace {
QColor hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <= 1) {
r = c;
g = x;
} else if (hp <= 2) {
r = x;
g = c;
} else if (hp <= 3) {
g = c;
b = x;
} else if (hp <= 4) {
g = x;
b = c;
} else if (hp <= 5) {
r = x;
b = c;
} else {
r = c;
b = x;
}
r += m;
g += m;
b += m;
return QColor(r * 255, g * 255, b * 255);
}
}
ColorWheelWidget::ColorWheelWidget(QWidget *parent)
: QWidget(parent) {
setWindowTitle(tr("Color Wheel"));
resize(400, 400);
}
void ColorWheelWidget::paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
const QColor backgroundColor(0, 0, 0);
const QColor white(255, 255, 255);
painter.fillRect(event->rect(), backgroundColor);
const int margin = 10;
const double diameter = std::min(width(), height()) - 2*margin;
QPointF center(width()/2.0, height()/2.0);
QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,
diameter, diameter);
for (int angle = 0; angle < 360; ++angle) {
QColor color(hsvToRgb(angle, 1.0, 1.0));
QRadialGradient gradient(center, diameter/2.0);
gradient.setColorAt(0, white);
gradient.setColorAt(1, color);
QBrush brush(gradient);
QPen pen(brush, 1.0);
painter.setPen(pen);
painter.setBrush(brush);
painter.drawPie(rect, angle * 16, 16);
}
}
|
Write a version of this Java function in C++ with identical behavior. | import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import static java.awt.image.BufferedImage.*;
import static java.lang.Math.*;
import javax.swing.*;
public class PlasmaEffect extends JPanel {
float[][] plasma;
float hueShift = 0;
BufferedImage img;
public PlasmaEffect() {
Dimension dim = new Dimension(640, 640);
setPreferredSize(dim);
setBackground(Color.white);
img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);
plasma = createPlasma(dim.height, dim.width);
new Timer(42, (ActionEvent e) -> {
hueShift = (hueShift + 0.02f) % 1;
repaint();
}).start();
}
float[][] createPlasma(int w, int h) {
float[][] buffer = new float[h][w];
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
double value = sin(x / 16.0);
value += sin(y / 8.0);
value += sin((x + y) / 16.0);
value += sin(sqrt(x * x + y * y) / 8.0);
value += 4;
value /= 8;
assert (value >= 0.0 && value <= 1.0) : "Hue value out of bounds";
buffer[y][x] = (float) value;
}
return buffer;
}
void drawPlasma(Graphics2D g) {
int h = plasma.length;
int w = plasma[0].length;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
float hue = hueShift + plasma[y][x] % 1;
img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));
}
g.drawImage(img, 0, 0, null);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawPlasma(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Plasma Effect");
f.setResizable(false);
f.add(new PlasmaEffect(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
| #include <windows.h>
#include <math.h>
#include <string>
const int BMP_SIZE = 240, MY_TIMER = 987654;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h ) {
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 ) {
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr ) {
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) {
clr = c; createPen();
}
void setPenWidth( int w ) {
wid = w; createPen();
}
void saveBitmap( std::string path ) {
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
DWORD* bits() { return ( DWORD* )pBits; }
private:
void createPen() {
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp; HDC hdc;
HPEN pen; HBRUSH brush;
void *pBits; int width, height, wid;
DWORD clr;
};
class plasma
{
public:
plasma() {
currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;
_bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();
plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];
plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];
int i, j, dst = 0;
double temp;
for( j = 0; j < BMP_SIZE * 2; j++ ) {
for( i = 0; i < BMP_SIZE * 2; i++ ) {
plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );
plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) +
( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );
dst++;
}
}
}
void update() {
DWORD dst;
BYTE a, c1,c2, c3;
currentTime += ( double )( rand() % 2 + 1 );
int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime / 137 ) ),
x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 75 ) ),
x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),
y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime / 123 ) ),
y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 85 ) ),
y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );
int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;
DWORD* bits = _bmp.bits();
for( int j = 0; j < BMP_SIZE; j++ ) {
dst = j * BMP_SIZE;
for( int i= 0; i < BMP_SIZE; i++ ) {
a = plasma2[src1] + plasma1[src2] + plasma2[src3];
c1 = a << 1; c2 = a << 2; c3 = a << 3;
bits[dst + i] = RGB( c1, c2, c3 );
src1++; src2++; src3++;
}
src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;
}
draw();
}
void setHWND( HWND hwnd ) { _hwnd = hwnd; }
private:
void draw() {
HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );
BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );
ReleaseDC( _hwnd, wdc );
}
myBitmap _bmp; HWND _hwnd; float _ang;
BYTE *plasma1, *plasma2;
double currentTime; int _WD, _WV;
};
class wnd
{
public:
wnd() { _inst = this; }
int wnd::Run( HINSTANCE hInst ) {
_hInst = hInst; _hwnd = InitAll();
SetTimer( _hwnd, MY_TIMER, 15, NULL );
_plasma.setHWND( _hwnd );
ShowWindow( _hwnd, SW_SHOW );
UpdateWindow( _hwnd );
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT ) {
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
return UnregisterClass( "_MY_PLASMA_", _hInst );
}
private:
void wnd::doPaint( HDC dc ) { _plasma.update(); }
void wnd::doTimer() { _plasma.update(); }
static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {
switch( msg ) {
case WM_PAINT: {
PAINTSTRUCT ps;
_inst->doPaint( BeginPaint( hWnd, &ps ) );
EndPaint( hWnd, &ps );
return 0;
}
case WM_DESTROY: PostQuitMessage( 0 ); break;
case WM_TIMER: _inst->doTimer(); break;
default: return DefWindowProc( hWnd, msg, wParam, lParam );
}
return 0;
}
HWND InitAll() {
WNDCLASSEX wcex;
ZeroMemory( &wcex, sizeof( wcex ) );
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = ( WNDPROC )WndProc;
wcex.hInstance = _hInst;
wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszClassName = "_MY_PLASMA_";
RegisterClassEx( &wcex );
RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };
AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );
int w = rc.right - rc.left, h = rc.bottom - rc.top;
return CreateWindow( "_MY_PLASMA_", ".: Plasma -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );
}
static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;
};
wnd* wnd::_inst = 0;
int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {
wnd myWnd;
return myWnd.Run( hInstance );
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Java version. | import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import static java.awt.image.BufferedImage.*;
import static java.lang.Math.*;
import javax.swing.*;
public class PlasmaEffect extends JPanel {
float[][] plasma;
float hueShift = 0;
BufferedImage img;
public PlasmaEffect() {
Dimension dim = new Dimension(640, 640);
setPreferredSize(dim);
setBackground(Color.white);
img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);
plasma = createPlasma(dim.height, dim.width);
new Timer(42, (ActionEvent e) -> {
hueShift = (hueShift + 0.02f) % 1;
repaint();
}).start();
}
float[][] createPlasma(int w, int h) {
float[][] buffer = new float[h][w];
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
double value = sin(x / 16.0);
value += sin(y / 8.0);
value += sin((x + y) / 16.0);
value += sin(sqrt(x * x + y * y) / 8.0);
value += 4;
value /= 8;
assert (value >= 0.0 && value <= 1.0) : "Hue value out of bounds";
buffer[y][x] = (float) value;
}
return buffer;
}
void drawPlasma(Graphics2D g) {
int h = plasma.length;
int w = plasma[0].length;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
float hue = hueShift + plasma[y][x] % 1;
img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));
}
g.drawImage(img, 0, 0, null);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawPlasma(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Plasma Effect");
f.setResizable(false);
f.add(new PlasmaEffect(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
| #include <windows.h>
#include <math.h>
#include <string>
const int BMP_SIZE = 240, MY_TIMER = 987654;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h ) {
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 ) {
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr ) {
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) {
clr = c; createPen();
}
void setPenWidth( int w ) {
wid = w; createPen();
}
void saveBitmap( std::string path ) {
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
DWORD* bits() { return ( DWORD* )pBits; }
private:
void createPen() {
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp; HDC hdc;
HPEN pen; HBRUSH brush;
void *pBits; int width, height, wid;
DWORD clr;
};
class plasma
{
public:
plasma() {
currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;
_bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();
plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];
plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];
int i, j, dst = 0;
double temp;
for( j = 0; j < BMP_SIZE * 2; j++ ) {
for( i = 0; i < BMP_SIZE * 2; i++ ) {
plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );
plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) +
( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );
dst++;
}
}
}
void update() {
DWORD dst;
BYTE a, c1,c2, c3;
currentTime += ( double )( rand() % 2 + 1 );
int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime / 137 ) ),
x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 75 ) ),
x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),
y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime / 123 ) ),
y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 85 ) ),
y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );
int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;
DWORD* bits = _bmp.bits();
for( int j = 0; j < BMP_SIZE; j++ ) {
dst = j * BMP_SIZE;
for( int i= 0; i < BMP_SIZE; i++ ) {
a = plasma2[src1] + plasma1[src2] + plasma2[src3];
c1 = a << 1; c2 = a << 2; c3 = a << 3;
bits[dst + i] = RGB( c1, c2, c3 );
src1++; src2++; src3++;
}
src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;
}
draw();
}
void setHWND( HWND hwnd ) { _hwnd = hwnd; }
private:
void draw() {
HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );
BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );
ReleaseDC( _hwnd, wdc );
}
myBitmap _bmp; HWND _hwnd; float _ang;
BYTE *plasma1, *plasma2;
double currentTime; int _WD, _WV;
};
class wnd
{
public:
wnd() { _inst = this; }
int wnd::Run( HINSTANCE hInst ) {
_hInst = hInst; _hwnd = InitAll();
SetTimer( _hwnd, MY_TIMER, 15, NULL );
_plasma.setHWND( _hwnd );
ShowWindow( _hwnd, SW_SHOW );
UpdateWindow( _hwnd );
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT ) {
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
return UnregisterClass( "_MY_PLASMA_", _hInst );
}
private:
void wnd::doPaint( HDC dc ) { _plasma.update(); }
void wnd::doTimer() { _plasma.update(); }
static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {
switch( msg ) {
case WM_PAINT: {
PAINTSTRUCT ps;
_inst->doPaint( BeginPaint( hWnd, &ps ) );
EndPaint( hWnd, &ps );
return 0;
}
case WM_DESTROY: PostQuitMessage( 0 ); break;
case WM_TIMER: _inst->doTimer(); break;
default: return DefWindowProc( hWnd, msg, wParam, lParam );
}
return 0;
}
HWND InitAll() {
WNDCLASSEX wcex;
ZeroMemory( &wcex, sizeof( wcex ) );
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = ( WNDPROC )WndProc;
wcex.hInstance = _hInst;
wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszClassName = "_MY_PLASMA_";
RegisterClassEx( &wcex );
RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };
AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );
int w = rc.right - rc.left, h = rc.bottom - rc.top;
return CreateWindow( "_MY_PLASMA_", ".: Plasma -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );
}
static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;
};
wnd* wnd::_inst = 0;
int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {
wnd myWnd;
return myWnd.Run( hInstance );
}
|
Write a version of this Java function in C++ with identical behavior. | public class RhondaNumbers {
public static void main(String[] args) {
final int limit = 15;
for (int base = 2; base <= 36; ++base) {
if (isPrime(base))
continue;
System.out.printf("First %d Rhonda numbers to base %d:\n", limit, base);
int numbers[] = new int[limit];
for (int n = 1, count = 0; count < limit; ++n) {
if (isRhonda(base, n))
numbers[count++] = n;
}
System.out.printf("In base 10:");
for (int i = 0; i < limit; ++i)
System.out.printf(" %d", numbers[i]);
System.out.printf("\nIn base %d:", base);
for (int i = 0; i < limit; ++i)
System.out.printf(" %s", Integer.toString(numbers[i], base));
System.out.printf("\n\n");
}
}
private static int digitProduct(int base, int n) {
int product = 1;
for (; n != 0; n /= base)
product *= n % base;
return product;
}
private static int primeFactorSum(int n) {
int sum = 0;
for (; (n & 1) == 0; n >>= 1)
sum += 2;
for (int p = 3; p * p <= n; p += 2)
for (; n % p == 0; n /= p)
sum += p;
if (n > 1)
sum += n;
return sum;
}
private static boolean isPrime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
private static boolean isRhonda(int base, int n) {
return digitProduct(base, n) == base * primeFactorSum(n);
}
}
| #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
int digit_product(int base, int n) {
int product = 1;
for (; n != 0; n /= base)
product *= n % base;
return product;
}
int prime_factor_sum(int n) {
int sum = 0;
for (; (n & 1) == 0; n >>= 1)
sum += 2;
for (int p = 3; p * p <= n; p += 2)
for (; n % p == 0; n /= p)
sum += p;
if (n > 1)
sum += n;
return sum;
}
bool is_prime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
bool is_rhonda(int base, int n) {
return digit_product(base, n) == base * prime_factor_sum(n);
}
std::string to_string(int base, int n) {
assert(base <= 36);
static constexpr char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string str;
for (; n != 0; n /= base)
str += digits[n % base];
std::reverse(str.begin(), str.end());
return str;
}
int main() {
const int limit = 15;
for (int base = 2; base <= 36; ++base) {
if (is_prime(base))
continue;
std::cout << "First " << limit << " Rhonda numbers to base " << base
<< ":\n";
int numbers[limit];
for (int n = 1, count = 0; count < limit; ++n) {
if (is_rhonda(base, n))
numbers[count++] = n;
}
std::cout << "In base 10:";
for (int i = 0; i < limit; ++i)
std::cout << ' ' << numbers[i];
std::cout << "\nIn base " << base << ':';
for (int i = 0; i < limit; ++i)
std::cout << ' ' << to_string(base, numbers[i]);
std::cout << "\n\n";
}
}
|
Port the provided Java code into C++ while preserving the original functionality. | public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
| #include <iostream>
int main() {
using namespace std;
cout << "Hello, World!" << endl;
return 0;
}
|
Convert this Java block to C++, preserving its control flow and logic. | public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
| #include <iostream>
int main() {
using namespace std;
cout << "Hello, World!" << endl;
return 0;
}
|
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically? | class Point {
protected int x, y;
public Point() { this(0); }
public Point(int x) { this(x, 0); }
public Point(int x, int y) { this.x = x; this.y = y; }
public Point(Point p) { this(p.x, p.y); }
public int getX() { return this.x; }
public int getY() { return this.y; }
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
public void print() { System.out.println("Point x: " + this.x + " y: " + this.y); }
}
class Circle extends Point {
private int r;
public Circle(Point p) { this(p, 0); }
public Circle(Point p, int r) { super(p); this.r = r; }
public Circle() { this(0); }
public Circle(int x) { this(x, 0); }
public Circle(int x, int y) { this(x, y, 0); }
public Circle(int x, int y, int r) { super(x, y); this.r = r; }
public Circle(Circle c) { this(c.x, c.y, c.r); }
public int getR() { return this.r; }
public void setR(int r) { this.r = r; }
public void print() { System.out.println("Circle x: " + this.x + " y: " + this.y + " r: " + this.r); }
}
public class test {
public static void main(String args[]) {
Point p = new Point();
Point c = new Circle();
p.print();
c.print();
}
}
| #include <cstdio>
#include <cstdlib>
class Point {
protected:
int x, y;
public:
Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}
Point(const Point &p) : x(p.x), y(p.y) {}
virtual ~Point() {}
const Point& operator=(const Point &p) {
if (this != &p) {
x = p.x;
y = p.y;
}
return *this;
}
int getX() { return x; }
int getY() { return y; }
void setX(int x0) { x = x0; }
void setY(int y0) { y = y0; }
virtual void print() { printf("Point\n"); }
};
class Circle: public Point {
private:
int r;
public:
Circle(Point p, int r0 = 0) : Point(p), r(r0) {}
Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}
virtual ~Circle() {}
const Circle& operator=(const Circle &c) {
if (this != &c) {
x = c.x;
y = c.y;
r = c.r;
}
return *this;
}
int getR() { return r; }
void setR(int r0) { r = r0; }
virtual void print() { printf("Circle\n"); }
};
int main() {
Point *p = new Point();
Point *c = new Circle();
p->print();
c->print();
delete p;
delete c;
return EXIT_SUCCESS;
}
|
Rewrite the snippet below in C++ so it works the same as the original Java code. | import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
BigInteger d = new BigInteger("3"), a;
int lmt = 25, sl, c = 0;
for (int i = 3; i < 5808; ) {
a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);
if (a.isProbablePrime(1)) {
System.out.printf("%2d %4d ", ++c, i);
String s = a.toString(); sl = s.length();
if (sl < lmt) System.out.println(a);
else System.out.println(s.substring(0, 11) + ".." + s.substring(sl - 11, sl) + " " + sl + " digits");
}
i = BigInteger.valueOf(i).nextProbablePrime().intValue();
}
}
}
| #include <gmpxx.h>
#include <primesieve.hpp>
#include <iostream>
using big_int = mpz_class;
std::string to_string(const big_int& num, size_t n) {
std::string str = num.get_str();
size_t len = str.size();
if (len > n) {
str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2);
str += " (";
str += std::to_string(len);
str += " digits)";
}
return str;
}
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;
}
int main() {
const big_int one(1);
primesieve::iterator pi;
pi.next_prime();
for (int i = 0; i < 24;) {
uint64_t p = pi.next_prime();
big_int n = ((one << p) + 1) / 3;
if (is_probably_prime(n))
std::cout << ++i << ": " << p << " - " << to_string(n, 30) << '\n';
}
}
|
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically? | import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
BigInteger d = new BigInteger("3"), a;
int lmt = 25, sl, c = 0;
for (int i = 3; i < 5808; ) {
a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);
if (a.isProbablePrime(1)) {
System.out.printf("%2d %4d ", ++c, i);
String s = a.toString(); sl = s.length();
if (sl < lmt) System.out.println(a);
else System.out.println(s.substring(0, 11) + ".." + s.substring(sl - 11, sl) + " " + sl + " digits");
}
i = BigInteger.valueOf(i).nextProbablePrime().intValue();
}
}
}
| #include <gmpxx.h>
#include <primesieve.hpp>
#include <iostream>
using big_int = mpz_class;
std::string to_string(const big_int& num, size_t n) {
std::string str = num.get_str();
size_t len = str.size();
if (len > n) {
str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2);
str += " (";
str += std::to_string(len);
str += " digits)";
}
return str;
}
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;
}
int main() {
const big_int one(1);
primesieve::iterator pi;
pi.next_prime();
for (int i = 0; i < 24;) {
uint64_t p = pi.next_prime();
big_int n = ((one << p) + 1) / 3;
if (is_probably_prime(n))
std::cout << ++i << ": " << p << " - " << to_string(n, 30) << '\n';
}
}
|
Translate the given Java code snippet into C++ without altering its behavior. | import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class ImmutableMap {
public static void main(String[] args) {
Map<String,Integer> hashMap = getImmutableMap();
try {
hashMap.put("Test", 23);
}
catch (UnsupportedOperationException e) {
System.out.println("ERROR: Unable to put new value.");
}
try {
hashMap.clear();
}
catch (UnsupportedOperationException e) {
System.out.println("ERROR: Unable to clear map.");
}
try {
hashMap.putIfAbsent("Test", 23);
}
catch (UnsupportedOperationException e) {
System.out.println("ERROR: Unable to put if absent.");
}
for ( String key : hashMap.keySet() ) {
System.out.printf("key = %s, value = %s%n", key, hashMap.get(key));
}
}
private static Map<String,Integer> getImmutableMap() {
Map<String,Integer> hashMap = new HashMap<>();
hashMap.put("Key 1", 34);
hashMap.put("Key 2", 105);
hashMap.put("Key 3", 144);
return Collections.unmodifiableMap(hashMap);
}
}
| #include <iostream>
#include <map>
#include <utility>
using namespace std;
template<typename T>
class FixedMap : private T
{
T m_defaultValues;
public:
FixedMap(T map)
: T(map), m_defaultValues(move(map)){}
using T::cbegin;
using T::cend;
using T::empty;
using T::find;
using T::size;
using T::at;
using T::begin;
using T::end;
auto& operator[](typename T::key_type&& key)
{
return this->at(forward<typename T::key_type>(key));
}
void erase(typename T::key_type&& key)
{
T::operator[](key) = m_defaultValues.at(key);
}
void clear()
{
T::operator=(m_defaultValues);
}
};
auto PrintMap = [](const auto &map)
{
for(auto &[key, value] : map)
{
cout << "{" << key << " : " << value << "} ";
}
cout << "\n\n";
};
int main(void)
{
cout << "Map intialized with values\n";
FixedMap<map<string, int>> fixedMap ({
{"a", 1},
{"b", 2}});
PrintMap(fixedMap);
cout << "Change the values of the keys\n";
fixedMap["a"] = 55;
fixedMap["b"] = 56;
PrintMap(fixedMap);
cout << "Reset the 'a' key\n";
fixedMap.erase("a");
PrintMap(fixedMap);
cout << "Change the values the again\n";
fixedMap["a"] = 88;
fixedMap["b"] = 99;
PrintMap(fixedMap);
cout << "Reset all keys\n";
fixedMap.clear();
PrintMap(fixedMap);
try
{
cout << "Try to add a new key\n";
fixedMap["newKey"] = 99;
}
catch (exception &ex)
{
cout << "error: " << ex.what();
}
}
|
Convert this Java block to C++, preserving its control flow and logic. | public class MainApp {
public static void main(String[] args) {
int countOfPrimes = 0;
final int targetCountOfPrimes = 10;
long f = 1;
while (countOfPrimes < targetCountOfPrimes) {
long factorialNum = getFactorial(f);
boolean primePlus = isPrime(factorialNum + 1);
boolean primeMinus = isPrime(factorialNum - 1);
if (primeMinus) {
countOfPrimes++;
System.out.println(countOfPrimes + ": " + factorialNum + "! - 1 = " + (factorialNum - 1));
}
if (primePlus && f > 1) {
countOfPrimes++;
System.out.println(countOfPrimes + ": " + factorialNum + "! + 1 = " + (factorialNum + 1));
}
f++;
}
}
private static long getFactorial(long f) {
long factorial = 1;
for (long i = 1; i < f; i++) {
factorial *= i;
}
return factorial;
}
private static boolean isPrime(long num) {
if (num < 2) {return false;}
for (long i = 2; i < num; i++) {
if (num % i == 0) {return false;}
}
return true;
}
}
| #include <iomanip>
#include <iostream>
#include <gmpxx.h>
using big_int = mpz_class;
std::string to_string(const big_int& num, size_t n) {
std::string str = num.get_str();
size_t len = str.size();
if (len > n) {
str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2);
str += " (";
str += std::to_string(len);
str += " digits)";
}
return str;
}
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;
}
int main() {
big_int f = 1;
for (int i = 0, n = 1; i < 31; ++n) {
f *= n;
if (is_probably_prime(f - 1)) {
++i;
std::cout << std::setw(2) << i << ": " << std::setw(3) << n
<< "! - 1 = " << to_string(f - 1, 40) << '\n';
}
if (is_probably_prime(f + 1)) {
++i;
std::cout << std::setw(2) << i << ": " << std::setw(3) << n
<< "! + 1 = " << to_string(f + 1, 40) << '\n';
}
}
}
|
Transform the following Java implementation into C++, maintaining the same output and logic. | import java.util.Stack;
public class ArithmeticEvaluation {
public interface Expression {
BigRational eval();
}
public enum Parentheses {LEFT}
public enum BinaryOperator {
ADD('+', 1),
SUB('-', 1),
MUL('*', 2),
DIV('/', 2);
public final char symbol;
public final int precedence;
BinaryOperator(char symbol, int precedence) {
this.symbol = symbol;
this.precedence = precedence;
}
public BigRational eval(BigRational leftValue, BigRational rightValue) {
switch (this) {
case ADD:
return leftValue.add(rightValue);
case SUB:
return leftValue.subtract(rightValue);
case MUL:
return leftValue.multiply(rightValue);
case DIV:
return leftValue.divide(rightValue);
}
throw new IllegalStateException();
}
public static BinaryOperator forSymbol(char symbol) {
for (BinaryOperator operator : values()) {
if (operator.symbol == symbol) {
return operator;
}
}
throw new IllegalArgumentException(String.valueOf(symbol));
}
}
public static class Number implements Expression {
private final BigRational number;
public Number(BigRational number) {
this.number = number;
}
@Override
public BigRational eval() {
return number;
}
@Override
public String toString() {
return number.toString();
}
}
public static class BinaryExpression implements Expression {
public final Expression leftOperand;
public final BinaryOperator operator;
public final Expression rightOperand;
public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {
this.leftOperand = leftOperand;
this.operator = operator;
this.rightOperand = rightOperand;
}
@Override
public BigRational eval() {
BigRational leftValue = leftOperand.eval();
BigRational rightValue = rightOperand.eval();
return operator.eval(leftValue, rightValue);
}
@Override
public String toString() {
return "(" + leftOperand + " " + operator.symbol + " " + rightOperand + ")";
}
}
private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {
Expression rightOperand = operands.pop();
Expression leftOperand = operands.pop();
operands.push(new BinaryExpression(leftOperand, operator, rightOperand));
}
public static Expression parse(String input) {
int curIndex = 0;
boolean afterOperand = false;
Stack<Expression> operands = new Stack<>();
Stack<Object> operators = new Stack<>();
while (curIndex < input.length()) {
int startIndex = curIndex;
char c = input.charAt(curIndex++);
if (Character.isWhitespace(c))
continue;
if (afterOperand) {
if (c == ')') {
Object operator;
while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))
createNewOperand((BinaryOperator) operator, operands);
continue;
}
afterOperand = false;
BinaryOperator operator = BinaryOperator.forSymbol(c);
while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))
createNewOperand((BinaryOperator) operators.pop(), operands);
operators.push(operator);
continue;
}
if (c == '(') {
operators.push(Parentheses.LEFT);
continue;
}
afterOperand = true;
while (curIndex < input.length()) {
c = input.charAt(curIndex);
if (((c < '0') || (c > '9')) && (c != '.'))
break;
curIndex++;
}
operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));
}
while (!operators.isEmpty()) {
Object operator = operators.pop();
if (operator == Parentheses.LEFT)
throw new IllegalArgumentException();
createNewOperand((BinaryOperator) operator, operands);
}
Expression expression = operands.pop();
if (!operands.isEmpty())
throw new IllegalArgumentException();
return expression;
}
public static void main(String[] args) {
String[] testExpressions = {
"2+3",
"2+3/4",
"2*3-4",
"2*(3+4)+5/6",
"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10",
"2*-3--4+-.25"};
for (String testExpression : testExpressions) {
Expression expression = parse(testExpression);
System.out.printf("Input: \"%s\", AST: \"%s\", value=%s%n", testExpression, expression, expression.eval());
}
}
}
| #include <boost/spirit.hpp>
#include <boost/spirit/tree/ast.hpp>
#include <string>
#include <cassert>
#include <iostream>
#include <istream>
#include <ostream>
using boost::spirit::rule;
using boost::spirit::parser_tag;
using boost::spirit::ch_p;
using boost::spirit::real_p;
using boost::spirit::tree_node;
using boost::spirit::node_val_data;
struct parser: public boost::spirit::grammar<parser>
{
enum rule_ids { addsub_id, multdiv_id, value_id, real_id };
struct set_value
{
set_value(parser const& p): self(p) {}
void operator()(tree_node<node_val_data<std::string::iterator,
double> >& node,
std::string::iterator begin,
std::string::iterator end) const
{
node.value.value(self.tmp);
}
parser const& self;
};
mutable double tmp;
template<typename Scanner> struct definition
{
rule<Scanner, parser_tag<addsub_id> > addsub;
rule<Scanner, parser_tag<multdiv_id> > multdiv;
rule<Scanner, parser_tag<value_id> > value;
rule<Scanner, parser_tag<real_id> > real;
definition(parser const& self)
{
using namespace boost::spirit;
addsub = multdiv
>> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv);
multdiv = value
>> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value);
value = real | inner_node_d[('(' >> addsub >> ')')];
real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]];
}
rule<Scanner, parser_tag<addsub_id> > const& start() const
{
return addsub;
}
};
};
template<typename TreeIter>
double evaluate(TreeIter const& i)
{
double op1, op2;
switch (i->value.id().to_long())
{
case parser::real_id:
return i->value.value();
case parser::value_id:
case parser::addsub_id:
case parser::multdiv_id:
op1 = evaluate(i->children.begin());
op2 = evaluate(i->children.begin()+1);
switch(*i->value.begin())
{
case '+':
return op1 + op2;
case '-':
return op1 - op2;
case '*':
return op1 * op2;
case '/':
return op1 / op2;
default:
assert(!"Should not happen");
}
default:
assert(!"Should not happen");
}
return 0;
}
int main()
{
parser eval;
std::string line;
while (std::cout << "Expression: "
&& std::getline(std::cin, line)
&& !line.empty())
{
typedef boost::spirit::node_val_data_factory<double> factory_t;
boost::spirit::tree_parse_info<std::string::iterator, factory_t> info =
boost::spirit::ast_parse<factory_t>(line.begin(), line.end(),
eval, boost::spirit::space_p);
if (info.full)
{
std::cout << "Result: " << evaluate(info.trees.begin()) << std::endl;
}
else
{
std::cout << "Error in expression." << std::endl;
}
}
};
|
Please provide an equivalent version of this Java code in C++. | import java.util.Stack;
public class ArithmeticEvaluation {
public interface Expression {
BigRational eval();
}
public enum Parentheses {LEFT}
public enum BinaryOperator {
ADD('+', 1),
SUB('-', 1),
MUL('*', 2),
DIV('/', 2);
public final char symbol;
public final int precedence;
BinaryOperator(char symbol, int precedence) {
this.symbol = symbol;
this.precedence = precedence;
}
public BigRational eval(BigRational leftValue, BigRational rightValue) {
switch (this) {
case ADD:
return leftValue.add(rightValue);
case SUB:
return leftValue.subtract(rightValue);
case MUL:
return leftValue.multiply(rightValue);
case DIV:
return leftValue.divide(rightValue);
}
throw new IllegalStateException();
}
public static BinaryOperator forSymbol(char symbol) {
for (BinaryOperator operator : values()) {
if (operator.symbol == symbol) {
return operator;
}
}
throw new IllegalArgumentException(String.valueOf(symbol));
}
}
public static class Number implements Expression {
private final BigRational number;
public Number(BigRational number) {
this.number = number;
}
@Override
public BigRational eval() {
return number;
}
@Override
public String toString() {
return number.toString();
}
}
public static class BinaryExpression implements Expression {
public final Expression leftOperand;
public final BinaryOperator operator;
public final Expression rightOperand;
public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {
this.leftOperand = leftOperand;
this.operator = operator;
this.rightOperand = rightOperand;
}
@Override
public BigRational eval() {
BigRational leftValue = leftOperand.eval();
BigRational rightValue = rightOperand.eval();
return operator.eval(leftValue, rightValue);
}
@Override
public String toString() {
return "(" + leftOperand + " " + operator.symbol + " " + rightOperand + ")";
}
}
private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {
Expression rightOperand = operands.pop();
Expression leftOperand = operands.pop();
operands.push(new BinaryExpression(leftOperand, operator, rightOperand));
}
public static Expression parse(String input) {
int curIndex = 0;
boolean afterOperand = false;
Stack<Expression> operands = new Stack<>();
Stack<Object> operators = new Stack<>();
while (curIndex < input.length()) {
int startIndex = curIndex;
char c = input.charAt(curIndex++);
if (Character.isWhitespace(c))
continue;
if (afterOperand) {
if (c == ')') {
Object operator;
while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))
createNewOperand((BinaryOperator) operator, operands);
continue;
}
afterOperand = false;
BinaryOperator operator = BinaryOperator.forSymbol(c);
while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))
createNewOperand((BinaryOperator) operators.pop(), operands);
operators.push(operator);
continue;
}
if (c == '(') {
operators.push(Parentheses.LEFT);
continue;
}
afterOperand = true;
while (curIndex < input.length()) {
c = input.charAt(curIndex);
if (((c < '0') || (c > '9')) && (c != '.'))
break;
curIndex++;
}
operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));
}
while (!operators.isEmpty()) {
Object operator = operators.pop();
if (operator == Parentheses.LEFT)
throw new IllegalArgumentException();
createNewOperand((BinaryOperator) operator, operands);
}
Expression expression = operands.pop();
if (!operands.isEmpty())
throw new IllegalArgumentException();
return expression;
}
public static void main(String[] args) {
String[] testExpressions = {
"2+3",
"2+3/4",
"2*3-4",
"2*(3+4)+5/6",
"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10",
"2*-3--4+-.25"};
for (String testExpression : testExpressions) {
Expression expression = parse(testExpression);
System.out.printf("Input: \"%s\", AST: \"%s\", value=%s%n", testExpression, expression, expression.eval());
}
}
}
| #include <boost/spirit.hpp>
#include <boost/spirit/tree/ast.hpp>
#include <string>
#include <cassert>
#include <iostream>
#include <istream>
#include <ostream>
using boost::spirit::rule;
using boost::spirit::parser_tag;
using boost::spirit::ch_p;
using boost::spirit::real_p;
using boost::spirit::tree_node;
using boost::spirit::node_val_data;
struct parser: public boost::spirit::grammar<parser>
{
enum rule_ids { addsub_id, multdiv_id, value_id, real_id };
struct set_value
{
set_value(parser const& p): self(p) {}
void operator()(tree_node<node_val_data<std::string::iterator,
double> >& node,
std::string::iterator begin,
std::string::iterator end) const
{
node.value.value(self.tmp);
}
parser const& self;
};
mutable double tmp;
template<typename Scanner> struct definition
{
rule<Scanner, parser_tag<addsub_id> > addsub;
rule<Scanner, parser_tag<multdiv_id> > multdiv;
rule<Scanner, parser_tag<value_id> > value;
rule<Scanner, parser_tag<real_id> > real;
definition(parser const& self)
{
using namespace boost::spirit;
addsub = multdiv
>> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv);
multdiv = value
>> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value);
value = real | inner_node_d[('(' >> addsub >> ')')];
real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]];
}
rule<Scanner, parser_tag<addsub_id> > const& start() const
{
return addsub;
}
};
};
template<typename TreeIter>
double evaluate(TreeIter const& i)
{
double op1, op2;
switch (i->value.id().to_long())
{
case parser::real_id:
return i->value.value();
case parser::value_id:
case parser::addsub_id:
case parser::multdiv_id:
op1 = evaluate(i->children.begin());
op2 = evaluate(i->children.begin()+1);
switch(*i->value.begin())
{
case '+':
return op1 + op2;
case '-':
return op1 - op2;
case '*':
return op1 * op2;
case '/':
return op1 / op2;
default:
assert(!"Should not happen");
}
default:
assert(!"Should not happen");
}
return 0;
}
int main()
{
parser eval;
std::string line;
while (std::cout << "Expression: "
&& std::getline(std::cin, line)
&& !line.empty())
{
typedef boost::spirit::node_val_data_factory<double> factory_t;
boost::spirit::tree_parse_info<std::string::iterator, factory_t> info =
boost::spirit::ast_parse<factory_t>(line.begin(), line.end(),
eval, boost::spirit::space_p);
if (info.full)
{
std::cout << "Result: " << evaluate(info.trees.begin()) << std::endl;
}
else
{
std::cout << "Error in expression." << std::endl;
}
}
};
|
Please provide an equivalent version of this Java code in C++. | import java.util.Stack;
public class ArithmeticEvaluation {
public interface Expression {
BigRational eval();
}
public enum Parentheses {LEFT}
public enum BinaryOperator {
ADD('+', 1),
SUB('-', 1),
MUL('*', 2),
DIV('/', 2);
public final char symbol;
public final int precedence;
BinaryOperator(char symbol, int precedence) {
this.symbol = symbol;
this.precedence = precedence;
}
public BigRational eval(BigRational leftValue, BigRational rightValue) {
switch (this) {
case ADD:
return leftValue.add(rightValue);
case SUB:
return leftValue.subtract(rightValue);
case MUL:
return leftValue.multiply(rightValue);
case DIV:
return leftValue.divide(rightValue);
}
throw new IllegalStateException();
}
public static BinaryOperator forSymbol(char symbol) {
for (BinaryOperator operator : values()) {
if (operator.symbol == symbol) {
return operator;
}
}
throw new IllegalArgumentException(String.valueOf(symbol));
}
}
public static class Number implements Expression {
private final BigRational number;
public Number(BigRational number) {
this.number = number;
}
@Override
public BigRational eval() {
return number;
}
@Override
public String toString() {
return number.toString();
}
}
public static class BinaryExpression implements Expression {
public final Expression leftOperand;
public final BinaryOperator operator;
public final Expression rightOperand;
public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {
this.leftOperand = leftOperand;
this.operator = operator;
this.rightOperand = rightOperand;
}
@Override
public BigRational eval() {
BigRational leftValue = leftOperand.eval();
BigRational rightValue = rightOperand.eval();
return operator.eval(leftValue, rightValue);
}
@Override
public String toString() {
return "(" + leftOperand + " " + operator.symbol + " " + rightOperand + ")";
}
}
private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {
Expression rightOperand = operands.pop();
Expression leftOperand = operands.pop();
operands.push(new BinaryExpression(leftOperand, operator, rightOperand));
}
public static Expression parse(String input) {
int curIndex = 0;
boolean afterOperand = false;
Stack<Expression> operands = new Stack<>();
Stack<Object> operators = new Stack<>();
while (curIndex < input.length()) {
int startIndex = curIndex;
char c = input.charAt(curIndex++);
if (Character.isWhitespace(c))
continue;
if (afterOperand) {
if (c == ')') {
Object operator;
while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))
createNewOperand((BinaryOperator) operator, operands);
continue;
}
afterOperand = false;
BinaryOperator operator = BinaryOperator.forSymbol(c);
while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))
createNewOperand((BinaryOperator) operators.pop(), operands);
operators.push(operator);
continue;
}
if (c == '(') {
operators.push(Parentheses.LEFT);
continue;
}
afterOperand = true;
while (curIndex < input.length()) {
c = input.charAt(curIndex);
if (((c < '0') || (c > '9')) && (c != '.'))
break;
curIndex++;
}
operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));
}
while (!operators.isEmpty()) {
Object operator = operators.pop();
if (operator == Parentheses.LEFT)
throw new IllegalArgumentException();
createNewOperand((BinaryOperator) operator, operands);
}
Expression expression = operands.pop();
if (!operands.isEmpty())
throw new IllegalArgumentException();
return expression;
}
public static void main(String[] args) {
String[] testExpressions = {
"2+3",
"2+3/4",
"2*3-4",
"2*(3+4)+5/6",
"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10",
"2*-3--4+-.25"};
for (String testExpression : testExpressions) {
Expression expression = parse(testExpression);
System.out.printf("Input: \"%s\", AST: \"%s\", value=%s%n", testExpression, expression, expression.eval());
}
}
}
| #include <boost/spirit.hpp>
#include <boost/spirit/tree/ast.hpp>
#include <string>
#include <cassert>
#include <iostream>
#include <istream>
#include <ostream>
using boost::spirit::rule;
using boost::spirit::parser_tag;
using boost::spirit::ch_p;
using boost::spirit::real_p;
using boost::spirit::tree_node;
using boost::spirit::node_val_data;
struct parser: public boost::spirit::grammar<parser>
{
enum rule_ids { addsub_id, multdiv_id, value_id, real_id };
struct set_value
{
set_value(parser const& p): self(p) {}
void operator()(tree_node<node_val_data<std::string::iterator,
double> >& node,
std::string::iterator begin,
std::string::iterator end) const
{
node.value.value(self.tmp);
}
parser const& self;
};
mutable double tmp;
template<typename Scanner> struct definition
{
rule<Scanner, parser_tag<addsub_id> > addsub;
rule<Scanner, parser_tag<multdiv_id> > multdiv;
rule<Scanner, parser_tag<value_id> > value;
rule<Scanner, parser_tag<real_id> > real;
definition(parser const& self)
{
using namespace boost::spirit;
addsub = multdiv
>> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv);
multdiv = value
>> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value);
value = real | inner_node_d[('(' >> addsub >> ')')];
real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]];
}
rule<Scanner, parser_tag<addsub_id> > const& start() const
{
return addsub;
}
};
};
template<typename TreeIter>
double evaluate(TreeIter const& i)
{
double op1, op2;
switch (i->value.id().to_long())
{
case parser::real_id:
return i->value.value();
case parser::value_id:
case parser::addsub_id:
case parser::multdiv_id:
op1 = evaluate(i->children.begin());
op2 = evaluate(i->children.begin()+1);
switch(*i->value.begin())
{
case '+':
return op1 + op2;
case '-':
return op1 - op2;
case '*':
return op1 * op2;
case '/':
return op1 / op2;
default:
assert(!"Should not happen");
}
default:
assert(!"Should not happen");
}
return 0;
}
int main()
{
parser eval;
std::string line;
while (std::cout << "Expression: "
&& std::getline(std::cin, line)
&& !line.empty())
{
typedef boost::spirit::node_val_data_factory<double> factory_t;
boost::spirit::tree_parse_info<std::string::iterator, factory_t> info =
boost::spirit::ast_parse<factory_t>(line.begin(), line.end(),
eval, boost::spirit::space_p);
if (info.full)
{
std::cout << "Result: " << evaluate(info.trees.begin()) << std::endl;
}
else
{
std::cout << "Error in expression." << std::endl;
}
}
};
|
Write a version of this Java function in C++ with identical behavior. | import java.util.Arrays;
public class SpecialVariables {
public static void main(String[] args) {
System.out.println(Arrays.toString(args));
System.out.println(SpecialVariables.class);
System.out.println(System.getenv());
System.out.println(System.getProperties());
System.out.println(Runtime.getRuntime().availableProcessors());
}
}
| #include <iostream>
struct SpecialVariables
{
int i = 0;
SpecialVariables& operator++()
{
this->i++;
return *this;
}
};
int main()
{
SpecialVariables sv;
auto sv2 = ++sv;
std::cout << " sv :" << sv.i << "\n sv2:" << sv2.i << "\n";
}
|
Write the same code in C++ as shown below in Java. | import java.util.Arrays;
public class SpecialVariables {
public static void main(String[] args) {
System.out.println(Arrays.toString(args));
System.out.println(SpecialVariables.class);
System.out.println(System.getenv());
System.out.println(System.getProperties());
System.out.println(Runtime.getRuntime().availableProcessors());
}
}
| #include <iostream>
struct SpecialVariables
{
int i = 0;
SpecialVariables& operator++()
{
this->i++;
return *this;
}
};
int main()
{
SpecialVariables sv;
auto sv2 = ++sv;
std::cout << " sv :" << sv.i << "\n sv2:" << sv2.i << "\n";
}
|
Produce a language-to-language conversion: from Java to C++, same semantics. | import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
public class Copypasta
{
public static void fatal_error(String errtext)
{
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
StackTraceElement main = stack[stack.length - 1];
String mainClass = main.getClassName();
System.out.println("%" + errtext);
System.out.println("usage: " + mainClass + " [filename.cp]");
System.exit(1);
}
public static void main(String[] args)
{
String fname = null;
String source = null;
try
{
fname = args[0];
source = new String(Files.readAllBytes(new File(fname).toPath()));
}
catch(Exception e)
{
fatal_error("error while trying to read from specified file");
}
ArrayList<String> lines = new ArrayList<String>(Arrays.asList(source.split("\n")));
String clipboard = "";
int loc = 0;
while(loc < lines.size())
{
String command = lines.get(loc).trim();
try
{
if(command.equals("Copy"))
clipboard += lines.get(loc + 1);
else if(command.equals("CopyFile"))
{
if(lines.get(loc + 1).equals("TheF*ckingCode"))
clipboard += source;
else
{
String filetext = new String(Files.readAllBytes(new File(lines.get(loc + 1)).toPath()));
clipboard += filetext;
}
}
else if(command.equals("Duplicate"))
{
String origClipboard = clipboard;
int amount = Integer.parseInt(lines.get(loc + 1)) - 1;
for(int i = 0; i < amount; i++)
clipboard += origClipboard;
}
else if(command.equals("Pasta!"))
{
System.out.println(clipboard);
System.exit(0);
}
else
fatal_error("unknown command '" + command + "' encountered on line " + new Integer(loc + 1).toString());
}
catch(Exception e)
{
fatal_error("error while executing command '" + command + "' on line " + new Integer(loc + 1).toString());
}
loc += 2;
}
}
}
| #include <fstream>
#include <iostream>
#include <sstream>
#include <streambuf>
#include <string>
#include <stdlib.h>
using namespace std;
void fatal_error(string errtext, char *argv[])
{
cout << "%" << errtext << endl;
cout << "usage: " << argv[0] << " [filename.cp]" << endl;
exit(1);
}
string& ltrim(string& str, const string& chars = "\t\n\v\f\r ")
{
str.erase(0, str.find_first_not_of(chars));
return str;
}
string& rtrim(string& str, const string& chars = "\t\n\v\f\r ")
{
str.erase(str.find_last_not_of(chars) + 1);
return str;
}
string& trim(string& str, const string& chars = "\t\n\v\f\r ")
{
return ltrim(rtrim(str, chars), chars);
}
int main(int argc, char *argv[])
{
string fname = "";
string source = "";
try
{
fname = argv[1];
ifstream t(fname);
t.seekg(0, ios::end);
source.reserve(t.tellg());
t.seekg(0, ios::beg);
source.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());
}
catch(const exception& e)
{
fatal_error("error while trying to read from specified file", argv);
}
string clipboard = "";
int loc = 0;
string remaining = source;
string line = "";
string command = "";
stringstream ss;
while(remaining.find("\n") != string::npos)
{
line = remaining.substr(0, remaining.find("\n"));
command = trim(line);
remaining = remaining.substr(remaining.find("\n") + 1);
try
{
if(line == "Copy")
{
line = remaining.substr(0, remaining.find("\n"));
remaining = remaining.substr(remaining.find("\n") + 1);
clipboard += line;
}
else if(line == "CopyFile")
{
line = remaining.substr(0, remaining.find("\n"));
remaining = remaining.substr(remaining.find("\n") + 1);
if(line == "TheF*ckingCode")
clipboard += source;
else
{
string filetext = "";
ifstream t(line);
t.seekg(0, ios::end);
filetext.reserve(t.tellg());
t.seekg(0, ios::beg);
filetext.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());
clipboard += filetext;
}
}
else if(line == "Duplicate")
{
line = remaining.substr(0, remaining.find("\n"));
remaining = remaining.substr(remaining.find("\n") + 1);
int amount = stoi(line);
string origClipboard = clipboard;
for(int i = 0; i < amount - 1; i++) {
clipboard += origClipboard;
}
}
else if(line == "Pasta!")
{
cout << clipboard << endl;
return 0;
}
else
{
ss << (loc + 1);
fatal_error("unknown command '" + command + "' encounter on line " + ss.str(), argv);
}
}
catch(const exception& e)
{
ss << (loc + 1);
fatal_error("error while executing command '" + command + "' on line " + ss.str(), argv);
}
loc += 2;
}
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Java. | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.IntConsumer;
import java.util.stream.Collectors;
public class Kosaraju {
static class Recursive<I> {
I func;
}
private static List<Integer> kosaraju(List<List<Integer>> g) {
int size = g.size();
boolean[] vis = new boolean[size];
int[] l = new int[size];
AtomicInteger x = new AtomicInteger(size);
List<List<Integer>> t = new ArrayList<>();
for (int i = 0; i < size; ++i) {
t.add(new ArrayList<>());
}
Recursive<IntConsumer> visit = new Recursive<>();
visit.func = (int u) -> {
if (!vis[u]) {
vis[u] = true;
for (Integer v : g.get(u)) {
visit.func.accept(v);
t.get(v).add(u);
}
int xval = x.decrementAndGet();
l[xval] = u;
}
};
for (int i = 0; i < size; ++i) {
visit.func.accept(i);
}
int[] c = new int[size];
Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>();
assign.func = (Integer u, Integer root) -> {
if (vis[u]) {
vis[u] = false;
c[u] = root;
for (Integer v : t.get(u)) {
assign.func.accept(v, root);
}
}
};
for (int u : l) {
assign.func.accept(u, u);
}
return Arrays.stream(c).boxed().collect(Collectors.toList());
}
public static void main(String[] args) {
List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < 8; ++i) {
g.add(new ArrayList<>());
}
g.get(0).add(1);
g.get(1).add(2);
g.get(2).add(0);
g.get(3).add(1);
g.get(3).add(2);
g.get(3).add(4);
g.get(4).add(3);
g.get(4).add(5);
g.get(5).add(2);
g.get(5).add(6);
g.get(6).add(5);
g.get(7).add(4);
g.get(7).add(6);
g.get(7).add(7);
List<Integer> output = kosaraju(g);
System.out.println(output);
}
}
| #include <functional>
#include <iostream>
#include <ostream>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto it = v.cbegin();
auto end = v.cend();
os << "[";
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << "]";
}
std::vector<int> kosaraju(std::vector<std::vector<int>>& g) {
auto size = g.size();
std::vector<bool> vis(size);
std::vector<int> l(size);
auto x = size;
std::vector<std::vector<int>> t(size);
std::function<void(int)> visit;
visit = [&](int u) {
if (!vis[u]) {
vis[u] = true;
for (auto v : g[u]) {
visit(v);
t[v].push_back(u);
}
l[--x] = u;
}
};
for (int i = 0; i < g.size(); ++i) {
visit(i);
}
std::vector<int> c(size);
std::function<void(int, int)> assign;
assign = [&](int u, int root) {
if (vis[u]) {
vis[u] = false;
c[u] = root;
for (auto v : t[u]) {
assign(v, root);
}
}
};
for (auto u : l) {
assign(u, u);
}
return c;
}
std::vector<std::vector<int>> g = {
{1},
{2},
{0},
{1, 2, 4},
{3, 5},
{2, 6},
{5},
{4, 6, 7},
};
int main() {
using namespace std;
cout << kosaraju(g) << endl;
return 0;
}
|
Change the following Java code into C++ without altering its purpose. | & | ^ ~
>> <<
>>>
+ - * / = %
| std::cout << "Tür\n";
std::cout << "T\u00FC\n";
|
Port the provided Java code into C++ while preserving the original functionality. | & | ^ ~
>> <<
>>>
+ - * / = %
| std::cout << "Tür\n";
std::cout << "T\u00FC\n";
|
Convert this Go snippet to C# and keep its semantics consistent. | package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
fmt.Printf("%d", i)
if i%5 == 0 {
fmt.Printf("\n")
continue
}
fmt.Printf(", ")
}
}
| using System;
class Program {
static void Main(string[] args) {
for (int i = 1; i <= 10; i++) {
Console.Write(i);
if (i % 5 == 0) {
Console.WriteLine();
continue;
}
Console.Write(", ");
}
}
}
|
Translate this program into C# but keep the logic exactly as in Go. | package main
import (
"fmt"
)
const numbers = 3
func main() {
max := 20
words := map[int]string{
3: "Fizz",
5: "Buzz",
7: "Baxx",
}
keys := []int{3, 5, 7}
divisible := false
for i := 1; i <= max; i++ {
for _, n := range keys {
if i % n == 0 {
fmt.Print(words[n])
divisible = true
}
}
if !divisible {
fmt.Print(i)
}
fmt.Println()
divisible = false
}
}
| using System;
public class GeneralFizzBuzz
{
public static void Main()
{
int i;
int j;
int k;
int limit;
string iString;
string jString;
string kString;
Console.WriteLine("First integer:");
i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("First string:");
iString = Console.ReadLine();
Console.WriteLine("Second integer:");
j = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Second string:");
jString = Console.ReadLine();
Console.WriteLine("Third integer:");
k = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Third string:");
kString = Console.ReadLine();
Console.WriteLine("Limit (inclusive):");
limit = Convert.ToInt32(Console.ReadLine());
for(int n = 1; n<= limit; n++)
{
bool flag = true;
if(n%i == 0)
{
Console.Write(iString);
flag = false;
}
if(n%j == 0)
{
Console.Write(jString);
flag = false;
}
if(n%k == 0)
{
Console.Write(kString);
flag = false;
}
if(flag)
Console.Write(n);
Console.WriteLine();
}
}
}
|
Port the provided Go code into C# while preserving the original functionality. | package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
| using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Rosetta.CheckPointSync;
public class Program
{
public async Task Main()
{
RobotBuilder robotBuilder = new RobotBuilder();
Task work = robotBuilder.BuildRobots(
"Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin",
"Bender", "Number Six", "C3-PO", "Dolores");
await work;
}
public class RobotBuilder
{
static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" };
static readonly Random rng = new Random();
static readonly object key = new object();
public Task BuildRobots(params string[] robots)
{
int r = 0;
Barrier checkpoint = new Barrier(parts.Length, b => {
Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!");
Console.WriteLine();
r++;
});
var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();
return Task.WhenAll(tasks);
}
private static int GetTime()
{
lock (key) {
return rng.Next(100, 1000);
}
}
private async Task BuildPart(Barrier barrier, string part, string[] robots)
{
foreach (var robot in robots) {
int time = GetTime();
Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms.");
await Task.Delay(time);
Console.WriteLine($"{part} for {robot} finished.");
barrier.SignalAndWait();
}
}
}
}
|
Convert the following code from Go to C#, ensuring the logic remains intact. | package main
import (
"fmt"
"encoding/binary"
)
func main() {
buf := make([]byte, binary.MaxVarintLen64)
for _, x := range []int64{0x200000, 0x1fffff} {
v := buf[:binary.PutVarint(buf, x)]
fmt.Printf("%d encodes into %d bytes: %x\n", x, len(v), v)
x, _ = binary.Varint(v)
fmt.Println(x, "decoded")
}
}
| namespace Vlq
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class VarLenQuantity
{
public static ulong ToVlq(ulong integer)
{
var array = new byte[8];
var buffer = ToVlqCollection(integer)
.SkipWhile(b => b == 0)
.Reverse()
.ToArray();
Array.Copy(buffer, array, buffer.Length);
return BitConverter.ToUInt64(array, 0);
}
public static ulong FromVlq(ulong integer)
{
var collection = BitConverter.GetBytes(integer).Reverse();
return FromVlqCollection(collection);
}
public static IEnumerable<byte> ToVlqCollection(ulong integer)
{
if (integer > Math.Pow(2, 56))
throw new OverflowException("Integer exceeds max value.");
var index = 7;
var significantBitReached = false;
var mask = 0x7fUL << (index * 7);
while (index >= 0)
{
var buffer = (mask & integer);
if (buffer > 0 || significantBitReached)
{
significantBitReached = true;
buffer >>= index * 7;
if (index > 0)
buffer |= 0x80;
yield return (byte)buffer;
}
mask >>= 7;
index--;
}
}
public static ulong FromVlqCollection(IEnumerable<byte> vlq)
{
ulong integer = 0;
var significantBitReached = false;
using (var enumerator = vlq.GetEnumerator())
{
int index = 0;
while (enumerator.MoveNext())
{
var buffer = enumerator.Current;
if (buffer > 0 || significantBitReached)
{
significantBitReached = true;
integer <<= 7;
integer |= (buffer & 0x7fUL);
}
if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))
break;
}
}
return integer;
}
public static void Main()
{
var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };
foreach (var original in integers)
{
Console.WriteLine("Original: 0x{0:X}", original);
var seq = ToVlqCollection(original);
Console.WriteLine("Sequence: 0x{0}", seq.Select(b => b.ToString("X2")).Aggregate(string.Concat));
var decoded = FromVlqCollection(seq);
Console.WriteLine("Decoded: 0x{0:X}", decoded);
var encoded = ToVlq(original);
Console.WriteLine("Encoded: 0x{0:X}", encoded);
decoded = FromVlq(encoded);
Console.WriteLine("Decoded: 0x{0:X}", decoded);
Console.WriteLine();
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
|
Please provide an equivalent version of this Go code in C#. | package main
import (
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
func main() {
show("alphaBETA")
show("alpha BETA")
show("DŽLjnj")
show("o'hare O'HARE o’hare don't")
}
func show(s string) {
fmt.Println("\nstring: ",
s, " len:", utf8.RuneCountInString(s), "runes")
fmt.Println("All upper case: ", strings.ToUpper(s))
fmt.Println("All lower case: ", strings.ToLower(s))
fmt.Println("All title case: ", strings.ToTitle(s))
fmt.Println("Title words: ", strings.Title(s))
fmt.Println("Swapping case: ",
strings.Map(unicode.SimpleFold, s))
}
| using System;
namespace StringCase
{
class Program
{
public static void Main()
{
String input = scope .("alphaBETA");
input.ToUpper();
Console.WriteLine(input);
input.ToLower();
Console.WriteLine(input);
}
}
}
|
Generate a C# translation of this Go snippet without changing its computational steps. | package main
import (
"crypto/md5"
"fmt"
)
func main() {
for _, p := range [][2]string{
{"d41d8cd98f00b204e9800998ecf8427e", ""},
{"0cc175b9c0f1b6a831c399e269772661", "a"},
{"900150983cd24fb0d6963f7d28e17f72", "abc"},
{"f96b697d7cb7938d525a2f31aaf161d0", "message digest"},
{"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"},
{"d174ab98d277d9f5a5611c2c9f419d9f",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"},
{"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890"},
{"e38ca1d920c4b8b8d3946b2c72f01680",
"The quick brown fox jumped over the lazy dog's back"},
} {
validate(p[0], p[1])
}
}
var h = md5.New()
func validate(check, s string) {
h.Reset()
h.Write([]byte(s))
sum := fmt.Sprintf("%x", h.Sum(nil))
if sum != check {
fmt.Println("MD5 fail")
fmt.Println(" for string,", s)
fmt.Println(" expected: ", check)
fmt.Println(" got: ", sum)
}
}
| using System.Text;
using System.Security.Cryptography;
byte[] data = Encoding.ASCII.GetBytes("The quick brown fox jumped over the lazy dog's back");
byte[] hash = MD5.Create().ComputeHash(data);
Console.WriteLine(BitConverter.ToString(hash).Replace("-", "").ToLower());
|
Keep all operations the same but rewrite the snippet in C#. | package main
import (
"fmt"
"time"
)
const taskDate = "March 7 2009 7:30pm EST"
const taskFormat = "January 2 2006 3:04pm MST"
func main() {
if etz, err := time.LoadLocation("US/Eastern"); err == nil {
time.Local = etz
}
fmt.Println("Input: ", taskDate)
t, err := time.Parse(taskFormat, taskDate)
if err != nil {
fmt.Println(err)
return
}
t = t.Add(12 * time.Hour)
fmt.Println("+12 hrs: ", t)
if _, offset := t.Zone(); offset == 0 {
fmt.Println("No time zone info.")
return
}
atz, err := time.LoadLocation("US/Arizona")
if err == nil {
fmt.Println("+12 hrs in Arizona:", t.In(atz))
}
}
| class Program
{
static void Main(string[] args)
{
CultureInfo ci=CultureInfo.CreateSpecificCulture("en-US");
string dateString = "March 7 2009 7:30pm EST";
string format = "MMMM d yyyy h:mmtt z";
DateTime myDateTime = DateTime.ParseExact(dateString.Replace("EST","+6"),format,ci) ;
DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;
Console.WriteLine(newDateTime.ToString(format).Replace("-5","EST"));
Console.ReadLine();
}
}
|
Change the following Go code into C# without altering its purpose. | package main
import (
"fmt"
"log"
"os"
"strconv"
"time"
)
func main() {
out := make(chan uint64)
for _, a := range os.Args[1:] {
i, err := strconv.ParseUint(a, 10, 64)
if err != nil {
log.Fatal(err)
}
go func(n uint64) {
time.Sleep(time.Duration(n) * time.Millisecond)
out <- n
}(i)
}
for _ = range os.Args[1:] {
fmt.Println(<-out)
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
class Program
{
static void ThreadStart(object item)
{
Thread.Sleep(1000 * (int)item);
Console.WriteLine(item);
}
static void SleepSort(IEnumerable<int> items)
{
foreach (var item in items)
{
new Thread(ThreadStart).Start(item);
}
}
static void Main(string[] arguments)
{
SleepSort(arguments.Select(int.Parse));
}
}
|
Change the following Go code into C# without altering its purpose. | package main
import (
"fmt"
"log"
"os"
"strconv"
"time"
)
func main() {
out := make(chan uint64)
for _, a := range os.Args[1:] {
i, err := strconv.ParseUint(a, 10, 64)
if err != nil {
log.Fatal(err)
}
go func(n uint64) {
time.Sleep(time.Duration(n) * time.Millisecond)
out <- n
}(i)
}
for _ = range os.Args[1:] {
fmt.Println(<-out)
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
class Program
{
static void ThreadStart(object item)
{
Thread.Sleep(1000 * (int)item);
Console.WriteLine(item);
}
static void SleepSort(IEnumerable<int> items)
{
foreach (var item in items)
{
new Thread(ThreadStart).Start(item);
}
}
static void Main(string[] arguments)
{
SleepSort(arguments.Select(int.Parse));
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
values := make([][]int, 10)
for i := range values {
values[i] = make([]int, 10)
for j := range values[i] {
values[i][j] = rand.Intn(20) + 1
}
}
outerLoop:
for i, row := range values {
fmt.Printf("%3d)", i)
for _, value := range row {
fmt.Printf(" %3d", value)
if value == 20 {
break outerLoop
}
}
fmt.Printf("\n")
}
fmt.Printf("\n")
}
| using System;
class Program {
static void Main(string[] args) {
int[,] a = new int[10, 10];
Random r = new Random();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
a[i, j] = r.Next(0, 21) + 1;
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
Console.Write(" {0}", a[i, j]);
if (a[i, j] == 20) {
goto Done;
}
}
Console.WriteLine();
}
Done:
Console.WriteLine();
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | package main
import "fmt"
func uniq(list []int) []int {
unique_set := make(map[int]bool, len(list))
for _, x := range list {
unique_set[x] = true
}
result := make([]int, 0, len(unique_set))
for x := range unique_set {
result = append(result, x)
}
return result
}
func main() {
fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4}))
}
| int[] nums = { 1, 1, 2, 3, 4, 4 };
List<int> unique = new List<int>();
foreach (int n in nums)
if (!unique.Contains(n))
unique.Add(n);
|
Can you help me rewrite this code in C# instead of Go, keeping it the same logically? | package main
import (
"fmt"
"strconv"
)
func lss(s string) (r string) {
c := s[0]
nc := 1
for i := 1; i < len(s); i++ {
d := s[i]
if d == c {
nc++
continue
}
r += strconv.Itoa(nc) + string(c)
c = d
nc = 1
}
return r + strconv.Itoa(nc) + string(c)
}
func main() {
s := "1"
fmt.Println(s)
for i := 0; i < 8; i++ {
s = lss(s)
fmt.Println(s)
}
}
| using System;
using System.Text;
using System.Linq;
class Program
{
static string lookandsay(string number)
{
StringBuilder result = new StringBuilder();
char repeat = number[0];
number = number.Substring(1, number.Length-1)+" ";
int times = 1;
foreach (char actual in number)
{
if (actual != repeat)
{
result.Append(Convert.ToString(times)+repeat);
times = 1;
repeat = actual;
}
else
{
times += 1;
}
}
return result.ToString();
}
static void Main(string[] args)
{
string num = "1";
foreach (int i in Enumerable.Range(1, 10)) {
Console.WriteLine(num);
num = lookandsay(num);
}
}
}
|
Ensure the translated C# code behaves exactly like the original Go snippet. | var intStack []int
|
System.Collections.Stack stack = new System.Collections.Stack();
stack.Push( obj );
bool isEmpty = stack.Count == 0;
object top = stack.Peek();
top = stack.Pop();
System.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();
stack.Push(new Foo());
bool isEmpty = stack.Count == 0;
Foo top = stack.Peek();
top = stack.Pop();
|
Translate the given Go code snippet into C# without altering its behavior. | package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
t >>= 1
}
if t > 0 {
n = t
} else {
k = -t
}
t = n - k
}
return n * s
}
func totient(n int) int {
tot := 0
for k := 1; k <= n; k++ {
if gcd(n, k) == 1 {
tot++
}
}
return tot
}
func main() {
fmt.Println(" n phi prime")
fmt.Println("---------------")
count := 0
for n := 1; n <= 25; n++ {
tot := totient(n)
isPrime := n-1 == tot
if isPrime {
count++
}
fmt.Printf("%2d %2d %t\n", n, tot, isPrime)
}
fmt.Println("\nNumber of primes up to 25 =", count)
for n := 26; n <= 100000; n++ {
tot := totient(n)
if tot == n-1 {
count++
}
if n == 100 || n == 1000 || n%10000 == 0 {
fmt.Printf("\nNumber of primes up to %-6d = %d\n", n, count)
}
}
}
| using static System.Console;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
for (int i = 1; i <= 25; i++) {
int t = Totient(i);
WriteLine(i + "\t" + t + (t == i - 1 ? "\tprime" : ""));
}
WriteLine();
for (int i = 100; i <= 100_000; i *= 10) {
WriteLine($"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}");
}
}
static int Totient(int n) {
if (n < 3) return 1;
if (n == 3) return 2;
int totient = n;
if ((n & 1) == 0) {
totient >>= 1;
while (((n >>= 1) & 1) == 0) ;
}
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
totient -= totient / i;
while ((n /= i) % i == 0) ;
}
}
if (n > 1) totient -= totient / n;
return totient;
}
}
|
Write the same algorithm in C# as shown in this Go implementation. | if booleanExpression {
statements
}
| if (condition)
{
}
if (condition)
{
}
else if (condition2)
{
}
else
{
}
|
Generate a C# translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"sort"
"strings"
)
type sortable []string
func (s sortable) Len() int { return len(s) }
func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s sortable) Less(i, j int) bool {
a, b := s[i], s[j]
if len(a) != len(b) {
return len(a) > len(b)
}
return strings.ToLower(a) < strings.ToLower(b)
}
func main() {
var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog")
fmt.Println(s, "(original)")
sort.Sort(s)
fmt.Println(s, "(sorted)")
}
| using System;
using System.Collections.Generic;
namespace RosettaCode {
class SortCustomComparator {
public void CustomSort() {
String[] items = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
List<String> list = new List<string>(items);
DisplayList("Unsorted", list);
list.Sort(CustomCompare);
DisplayList("Descending Length", list);
list.Sort();
DisplayList("Ascending order", list);
}
public int CustomCompare(String x, String y) {
int result = -x.Length.CompareTo(y.Length);
if (result == 0) {
result = x.ToLower().CompareTo(y.ToLower());
}
return result;
}
public void DisplayList(String header, List<String> theList) {
Console.WriteLine(header);
Console.WriteLine("".PadLeft(header.Length, '*'));
foreach (String str in theList) {
Console.WriteLine(str);
}
Console.WriteLine();
}
}
}
|
Translate the given Go code snippet into C# without altering its behavior. | package main
import (
"log"
"time"
"github.com/gdamore/tcell"
)
const (
msg = "Hello World! "
x0, y0 = 8, 3
shiftsPerSecond = 4
clicksToExit = 5
)
func main() {
s, err := tcell.NewScreen()
if err != nil {
log.Fatal(err)
}
if err = s.Init(); err != nil {
log.Fatal(err)
}
s.Clear()
s.EnableMouse()
tick := time.Tick(time.Second / shiftsPerSecond)
click := make(chan bool)
go func() {
for {
em, ok := s.PollEvent().(*tcell.EventMouse)
if !ok || em.Buttons()&0xFF == tcell.ButtonNone {
continue
}
mx, my := em.Position()
if my == y0 && mx >= x0 && mx < x0+len(msg) {
click <- true
}
}
}()
for inc, shift, clicks := 1, 0, 0; ; {
select {
case <-tick:
shift = (shift + inc) % len(msg)
for i, r := range msg {
s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0)
}
s.Show()
case <-click:
clicks++
if clicks == clicksToExit {
s.Fini()
return
}
inc = len(msg) - inc
}
}
}
| using System;
using System.Drawing;
using System.Windows.Forms;
namespace BasicAnimation
{
class BasicAnimationForm : Form
{
bool isReverseDirection;
Label textLabel;
Timer timer;
internal BasicAnimationForm()
{
this.Size = new Size(150, 75);
this.Text = "Basic Animation";
textLabel = new Label();
textLabel.Text = "Hello World! ";
textLabel.Location = new Point(3,3);
textLabel.AutoSize = true;
textLabel.Click += new EventHandler(textLabel_OnClick);
this.Controls.Add(textLabel);
timer = new Timer();
timer.Interval = 500;
timer.Tick += new EventHandler(timer_OnTick);
timer.Enabled = true;
isReverseDirection = false;
}
private void timer_OnTick(object sender, EventArgs e)
{
string oldText = textLabel.Text, newText;
if(isReverseDirection)
newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);
else
newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);
textLabel.Text = newText;
}
private void textLabel_OnClick(object sender, EventArgs e)
{
isReverseDirection = !isReverseDirection;
}
}
class Program
{
static void Main()
{
Application.Run(new BasicAnimationForm());
}
}
}
|
Convert this Go block to C#, preserving its control flow and logic. | package main
import (
"bytes"
"encoding/binary"
"fmt"
)
type word int32
const wordLen = 4
const highBit = -1 << 31
var data = []word{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
buf := bytes.NewBuffer(nil)
ds := make([][]byte, len(data))
for i, x := range data {
binary.Write(buf, binary.LittleEndian, x^highBit)
b := make([]byte, wordLen)
buf.Read(b)
ds[i] = b
}
bins := make([][][]byte, 256)
for i := 0; i < wordLen; i++ {
for _, b := range ds {
bins[b[i]] = append(bins[b[i]], b)
}
j := 0
for k, bs := range bins {
copy(ds[j:], bs)
j += len(bs)
bins[k] = bs[:0]
}
}
fmt.Println("original:", data)
var w word
for i, b := range ds {
buf.Write(b)
binary.Read(buf, binary.LittleEndian, &w)
data[i] = w^highBit
}
fmt.Println("sorted: ", data)
}
| using System;
namespace RadixSort
{
class Program
{
static void Sort(int[] old)
{
int i, j;
int[] tmp = new int[old.Length];
for (int shift = 31; shift > -1; --shift)
{
j = 0;
for (i = 0; i < old.Length; ++i)
{
bool move = (old[i] << shift) >= 0;
if (shift == 0 ? !move : move)
old[i-j] = old[i];
else
tmp[j++] = old[i];
}
Array.Copy(tmp, 0, old, old.Length-j, j);
}
}
static void Main(string[] args)
{
int[] old = new int[] { 2, 5, 1, -3, 4 };
Console.WriteLine(string.Join(", ", old));
Sort(old);
Console.WriteLine(string.Join(", ", old));
Console.Read();
}
}
}
|
Produce a language-to-language conversion: from Go to C#, same semantics. | package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Rewrite the snippet below in C# so it works the same as the original Go code. | package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Convert this Go snippet to C# and keep its semantics consistent. | package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
selectionSort(a)
fmt.Println("after: ", a)
}
func selectionSort(a []int) {
last := len(a) - 1
for i := 0; i < last; i++ {
aMin := a[i]
iMin := i
for j := i + 1; j < len(a); j++ {
if a[j] < aMin {
aMin = a[j]
iMin = j
}
}
a[i], a[iMin] = aMin, a[i]
}
}
| class SelectionSort<T> where T : IComparable {
public T[] Sort(T[] list) {
int k;
T temp;
for (int i = 0; i < list.Length; i++) {
k = i;
for (int j=i + 1; j < list.Length; j++) {
if (list[j].CompareTo(list[k]) < 0) {
k = j;
}
}
temp = list[i];
list[i] = list[k];
list[k] = temp;
}
return list;
}
}
|
Please provide an equivalent version of this Go code in C#. | package main
import "fmt"
func main() {
for _, i := range []int{1, 2, 3, 4, 5} {
fmt.Println(i * i)
}
}
| int[] intArray = { 1, 2, 3, 4, 5 };
int[] squares1 = intArray.Select(x => x * x).ToArray();
int[] squares2 = (from x in intArray
select x * x).ToArray();
foreach (var i in intArray)
Console.WriteLine(i * i);
|
Generate a C# translation of this Go snippet without changing its computational steps. | package main
import (
"log"
"math/rand"
"sync"
"time"
)
var (
instance string
once sync.Once
)
func claim(color string, w *sync.WaitGroup) {
time.Sleep(time.Duration(rand.Intn(1e8)))
log.Println("trying to claim", color)
once.Do(func() { instance = color })
log.Printf("tried %s. instance: %s", color, instance)
w.Done()
}
func main() {
rand.Seed(time.Now().Unix())
var w sync.WaitGroup
w.Add(2)
go claim("red", &w)
go claim("blue", &w)
w.Wait()
log.Println("after trying both, instance =", instance)
}
| public sealed class Singleton1
{
private static Singleton1 instance;
private static readonly object lockObj = new object();
public static Singleton1 Instance {
get {
lock(lockObj) {
if (instance == null) {
instance = new Singleton1();
}
}
return instance;
}
}
}
|
Please provide an equivalent version of this Go code in C#. | package main
import (
"fmt"
"math"
)
type interval struct {
lower, upper float64
}
func stepAway(x float64) interval {
return interval {
math.Nextafter(x, math.Inf(-1)),
math.Nextafter(x, math.Inf(1))}
}
func safeAdd(a, b float64) interval {
return stepAway(a + b)
}
func main() {
a, b := 1.2, .03
fmt.Println(a, b, safeAdd(a, b))
}
| using System;
namespace SafeAddition {
class Program {
static float NextUp(float d) {
if (d == 0.0) return float.Epsilon;
if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;
byte[] bytes = BitConverter.GetBytes(d);
int dl = BitConverter.ToInt32(bytes, 0);
dl++;
bytes = BitConverter.GetBytes(dl);
return BitConverter.ToSingle(bytes, 0);
}
static float NextDown(float d) {
if (d == 0.0) return -float.Epsilon;
if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;
byte[] bytes = BitConverter.GetBytes(d);
int dl = BitConverter.ToInt32(bytes, 0);
dl--;
bytes = BitConverter.GetBytes(dl);
return BitConverter.ToSingle(bytes, 0);
}
static Tuple<float, float> SafeAdd(float a, float b) {
return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));
}
static void Main(string[] args) {
float a = 1.20f;
float b = 0.03f;
Console.WriteLine("({0} + {1}) is in the range {2}", a, b, SafeAdd(a, b));
}
}
}
|
Write the same algorithm in C# as shown in this Go implementation. | package main
import (
"fmt"
"math"
)
type interval struct {
lower, upper float64
}
func stepAway(x float64) interval {
return interval {
math.Nextafter(x, math.Inf(-1)),
math.Nextafter(x, math.Inf(1))}
}
func safeAdd(a, b float64) interval {
return stepAway(a + b)
}
func main() {
a, b := 1.2, .03
fmt.Println(a, b, safeAdd(a, b))
}
| using System;
namespace SafeAddition {
class Program {
static float NextUp(float d) {
if (d == 0.0) return float.Epsilon;
if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;
byte[] bytes = BitConverter.GetBytes(d);
int dl = BitConverter.ToInt32(bytes, 0);
dl++;
bytes = BitConverter.GetBytes(dl);
return BitConverter.ToSingle(bytes, 0);
}
static float NextDown(float d) {
if (d == 0.0) return -float.Epsilon;
if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;
byte[] bytes = BitConverter.GetBytes(d);
int dl = BitConverter.ToInt32(bytes, 0);
dl--;
bytes = BitConverter.GetBytes(dl);
return BitConverter.ToSingle(bytes, 0);
}
static Tuple<float, float> SafeAdd(float a, float b) {
return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));
}
static void Main(string[] args) {
float a = 1.20f;
float b = 0.03f;
Console.WriteLine("({0} + {1}) is in the range {2}", a, b, SafeAdd(a, b));
}
}
}
|
Write the same code in C# as shown below in Go. | for i := 10; i >= 0; i-- {
fmt.Println(i)
}
| for (int i = 10; i >= 0; i--)
{
Console.WriteLine(i);
}
|
Port the following code from Go to C# with equivalent syntax and logic. | import "io/ioutil"
func main() {
ioutil.WriteFile("path/to/your.file", []byte("data"), 0644)
}
| System.IO.File.WriteAllText("filename.txt", "This file contains a string.");
|
Port the provided Go code into C# while preserving the original functionality. | package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
for j := 1; j <= i; j++ {
fmt.Printf("*")
}
fmt.Printf("\n")
}
}
| using System;
class Program {
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}
|
Preserve the algorithm and functionality while converting the code from Go to C#. | package main
import "fmt"
const (
m = iota
c
cm
cmc
)
func ncs(s []int) [][]int {
if len(s) < 3 {
return nil
}
return append(n2(nil, s[1:], m), n2([]int{s[0]}, s[1:], c)...)
}
var skip = []int{m, cm, cm, cmc}
var incl = []int{c, c, cmc, cmc}
func n2(ss, tail []int, seq int) [][]int {
if len(tail) == 0 {
if seq != cmc {
return nil
}
return [][]int{ss}
}
return append(n2(append([]int{}, ss...), tail[1:], skip[seq]),
n2(append(ss, tail[0]), tail[1:], incl[seq])...)
}
func main() {
ss := ncs([]int{1, 2, 3, 4})
fmt.Println(len(ss), "non-continuous subsequences:")
for _, s := range ss {
fmt.Println(" ", s)
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main() {
var sequence = new[] { "A", "B", "C", "D" };
foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {
Console.WriteLine(string.Join(" ", subset.Select(i => sequence[i])));
}
}
static IEnumerable<List<int>> Subsets(int length) {
int[] values = Enumerable.Range(0, length).ToArray();
var stack = new Stack<int>(length);
for (int i = 0; stack.Count > 0 || i < length; ) {
if (i < length) {
stack.Push(i++);
yield return (from index in stack.Reverse() select values[index]).ToList();
} else {
i = stack.Pop() + 1;
if (stack.Count > 0) i = stack.Pop() + 1;
}
}
}
static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;
}
|
Translate the given Go code snippet into C# without altering its behavior. | package main
import "fmt"
func sieve(limit uint64) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := uint64(3)
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
c := sieve(1e10 - 1)
limit := 10
start := 3
twins := 0
for i := 1; i < 11; i++ {
for i := start; i < limit; i += 2 {
if !c[i] && !c[i-2] {
twins++
}
}
fmt.Printf("Under %14s there are %10s pairs of twin primes.\n", commatize(limit), commatize(twins))
start = limit + 1
limit *= 10
}
}
| using System;
class Program {
static uint[] res = new uint[10];
static uint ri = 1, p = 10, count = 0;
static void TabulateTwinPrimes(uint bound) {
if (bound < 5) return; count++;
uint cl = (bound - 1) >> 1, i = 1, j,
limit = (uint)(Math.Sqrt(bound) - 1) >> 1;
var comp = new bool[cl]; bool lp;
for (j = 3; j < cl; j += 3) comp[j] = true;
while (i < limit) {
if (lp = !comp[i]) {
uint pr = (i << 1) + 3;
for (j = (pr * pr - 2) >> 1; j < cl; j += pr)
comp[j] = true;
}
if (!comp[++i]) {
uint pr = (i << 1) + 3;
if (lp) {
if (pr > p) {
res[ri++] = count;
p *= 10;
}
count++;
i++;
}
for (j = (pr * pr - 2) >> 1; j < cl; j += pr)
comp[j] = true;
}
}
cl--;
while (i < cl) {
lp = !comp[i++];
if (!comp[i] && lp) {
if ((i++ << 1) + 3 > p) {
res[ri++] = count;
p *= 10;
}
count++;
}
}
res[ri] = count;
}
static void Main(string[] args) {
var sw = System.Diagnostics.Stopwatch.StartNew();
string fmt = "{0,9:n0} twin primes below {1,-13:n0}";
TabulateTwinPrimes(1_000_000_000);
sw.Stop();
p = 1;
for (var j = 1; j <= ri; j++)
Console.WriteLine(fmt, res[j], p *= 10);
Console.Write("{0} sec", sw.Elapsed.TotalSeconds);
}
}
|
Port the following code from Go to C# with equivalent syntax and logic. | package main
import (
"fmt"
"math"
"math/cmplx"
)
func main() {
for n := 2; n <= 5; n++ {
fmt.Printf("%d roots of 1:\n", n)
for _, r := range roots(n) {
fmt.Printf(" %18.15f\n", r)
}
}
}
func roots(n int) []complex128 {
r := make([]complex128, n)
for i := 0; i < n; i++ {
r[i] = cmplx.Rect(1, 2*math.Pi*float64(i)/float64(n))
}
return r
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
class Program
{
static IEnumerable<Complex> RootsOfUnity(int degree)
{
return Enumerable
.Range(0, degree)
.Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));
}
static void Main()
{
var degree = 3;
foreach (var root in RootsOfUnity(degree))
{
Console.WriteLine(root);
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. |
package main
import "fmt"
func d(b byte) byte {
if b < '0' || b > '9' {
panic("digit 0-9 expected")
}
return b - '0'
}
func add(x, y string) string {
if len(y) > len(x) {
x, y = y, x
}
b := make([]byte, len(x)+1)
var c byte
for i := 1; i <= len(x); i++ {
if i <= len(y) {
c += d(y[len(y)-i])
}
s := d(x[len(x)-i]) + c
c = s / 10
b[len(b)-i] = (s % 10) + '0'
}
if c == 0 {
return string(b[1:])
}
b[0] = c + '0'
return string(b)
}
func mulDigit(x string, y byte) string {
if y == '0' {
return "0"
}
y = d(y)
b := make([]byte, len(x)+1)
var c byte
for i := 1; i <= len(x); i++ {
s := d(x[len(x)-i])*y + c
c = s / 10
b[len(b)-i] = (s % 10) + '0'
}
if c == 0 {
return string(b[1:])
}
b[0] = c + '0'
return string(b)
}
func mul(x, y string) string {
result := mulDigit(x, y[len(y)-1])
for i, zeros := 2, ""; i <= len(y); i++ {
zeros += "0"
result = add(result, mulDigit(x, y[len(y)-i])+zeros)
}
return result
}
const n = "18446744073709551616"
func main() {
fmt.Println(mul(n, n))
}
| using System;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static decimal mx = 1E28M, hm = 1E14M, a;
struct bi { public decimal hi, lo; }
static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }
static string toStr(bi a, bool comma = false) {
string r = a.hi == 0 ? string.Format("{0:0}", a.lo) :
string.Format("{0:0}{1:" + new string('0', 28) + "}", a.hi, a.lo);
if (!comma) return r; string rc = "";
for (int i = r.Length - 3; i > 0; i -= 3) rc = "," + r.Substring(i, 3) + rc;
return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }
static decimal Pow_dec(decimal bas, uint exp) {
if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;
if ((exp & 1) == 0) return tmp; return tmp * bas; }
static void Main(string[] args) {
for (uint p = 64; p < 95; p += 30) {
bi x = set4sq(a = Pow_dec(2M, p)), y;
WriteLine("The square of (2^{0}): {1,38:n0}", p, a); BI BS = BI.Pow((BI)a, 2);
y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;
a = x.hi * x.lo * 2M;
y.hi += Math.Floor(a / hm);
y.lo += (a % hm) * hm;
while (y.lo > mx) { y.lo -= mx; y.hi++; }
WriteLine(" is {0,75} (which {1} match the BigInteger computation)\n", toStr(y, true),
BS.ToString() == toStr(y) ? "does" : "fails to"); } }
}
|
Generate a C# translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math/big"
)
var big1 = new(big.Int).SetUint64(1)
func solvePell(nn uint64) (*big.Int, *big.Int) {
n := new(big.Int).SetUint64(nn)
x := new(big.Int).Set(n)
x.Sqrt(x)
y := new(big.Int).Set(x)
z := new(big.Int).SetUint64(1)
r := new(big.Int).Lsh(x, 1)
e1 := new(big.Int).SetUint64(1)
e2 := new(big.Int)
f1 := new(big.Int)
f2 := new(big.Int).SetUint64(1)
t := new(big.Int)
u := new(big.Int)
a := new(big.Int)
b := new(big.Int)
for {
t.Mul(r, z)
y.Sub(t, y)
t.Mul(y, y)
t.Sub(n, t)
z.Quo(t, z)
t.Add(x, y)
r.Quo(t, z)
u.Set(e1)
e1.Set(e2)
t.Mul(r, e2)
e2.Add(t, u)
u.Set(f1)
f1.Set(f2)
t.Mul(r, f2)
f2.Add(t, u)
t.Mul(x, f2)
a.Add(e2, t)
b.Set(f2)
t.Mul(a, a)
u.Mul(n, b)
u.Mul(u, b)
t.Sub(t, u)
if t.Cmp(big1) == 0 {
return a, b
}
}
}
func main() {
ns := []uint64{61, 109, 181, 277}
for _, n := range ns {
x, y := solvePell(n)
fmt.Printf("x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\n", n, x, y)
}
}
| using System;
using System.Numerics;
static class Program
{
static void Fun(ref BigInteger a, ref BigInteger b, int c)
{
BigInteger t = a; a = b; b = b * c + t;
}
static void SolvePell(int n, ref BigInteger a, ref BigInteger b)
{
int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1;
BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1;
while (true)
{
y = r * z - y; z = (n - y * y) / z; r = (x + y) / z;
Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x);
if (a * a - n * b * b == 1) return;
}
}
static void Main()
{
BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 })
{
SolvePell(n, ref x, ref y);
Console.WriteLine("x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}", n, x, y);
}
}
}
|
Write the same algorithm in C# as shown in this Go implementation. | package main
import (
"bufio"
"bytes"
"fmt"
"math/rand"
"os"
"strings"
"time"
)
func main() {
fmt.Println(`Cows and Bulls
Guess four digit number of unique digits in the range 1 to 9.
A correct digit but not in the correct place is a cow.
A correct digit in the correct place is a bull.`)
pat := make([]byte, 4)
rand.Seed(time.Now().Unix())
r := rand.Perm(9)
for i := range pat {
pat[i] = '1' + byte(r[i])
}
valid := []byte("123456789")
guess:
for in := bufio.NewReader(os.Stdin); ; {
fmt.Print("Guess: ")
guess, err := in.ReadString('\n')
if err != nil {
fmt.Println("\nSo, bye.")
return
}
guess = strings.TrimSpace(guess)
if len(guess) != 4 {
fmt.Println("Please guess a four digit number.")
continue
}
var cows, bulls int
for ig, cg := range guess {
if strings.IndexRune(guess[:ig], cg) >= 0 {
fmt.Printf("Repeated digit: %c\n", cg)
continue guess
}
switch bytes.IndexByte(pat, byte(cg)) {
case -1:
if bytes.IndexByte(valid, byte(cg)) == -1 {
fmt.Printf("Invalid digit: %c\n", cg)
continue guess
}
default:
cows++
case ig:
bulls++
}
}
fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls)
if bulls == 4 {
fmt.Println("You got it.")
return
}
}
}
| using System;
namespace BullsnCows
{
class Program
{
static void Main(string[] args)
{
int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
KnuthShuffle<int>(ref nums);
int[] chosenNum = new int[4];
Array.Copy(nums, chosenNum, 4);
Console.WriteLine("Your Guess ?");
while (!game(Console.ReadLine(), chosenNum))
{
Console.WriteLine("Your next Guess ?");
}
Console.ReadKey();
}
public static void KnuthShuffle<T>(ref T[] array)
{
System.Random random = new System.Random();
for (int i = 0; i < array.Length; i++)
{
int j = random.Next(array.Length);
T temp = array[i]; array[i] = array[j]; array[j] = temp;
}
}
public static bool game(string guess, int[] num)
{
char[] guessed = guess.ToCharArray();
int bullsCount = 0, cowsCount = 0;
if (guessed.Length != 4)
{
Console.WriteLine("Not a valid guess.");
return false;
}
for (int i = 0; i < 4; i++)
{
int curguess = (int) char.GetNumericValue(guessed[i]);
if (curguess < 1 || curguess > 9)
{
Console.WriteLine("Digit must be ge greater 0 and lower 10.");
return false;
}
if (curguess == num[i])
{
bullsCount++;
}
else
{
for (int j = 0; j < 4; j++)
{
if (curguess == num[j])
cowsCount++;
}
}
}
if (bullsCount == 4)
{
Console.WriteLine("Congratulations! You have won!");
return true;
}
else
{
Console.WriteLine("Your Score is {0} bulls and {1} cows", bullsCount, cowsCount);
return false;
}
}
}
}
|
Convert the following code from Go to C#, ensuring the logic remains intact. | package main
import "fmt"
func main() {
list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
fmt.Println("unsorted:", list)
bubblesort(list)
fmt.Println("sorted! ", list)
}
func bubblesort(a []int) {
for itemCount := len(a) - 1; ; itemCount-- {
hasChanged := false
for index := 0; index < itemCount; index++ {
if a[index] > a[index+1] {
a[index], a[index+1] = a[index+1], a[index]
hasChanged = true
}
}
if hasChanged == false {
break
}
}
}
| using System;
using System.Collections.Generic;
namespace RosettaCode.BubbleSort
{
public static class BubbleSortMethods
{
public static void BubbleSort<T>(this List<T> list) where T : IComparable
{
bool madeChanges;
int itemCount = list.Count;
do
{
madeChanges = false;
itemCount--;
for (int i = 0; i < itemCount; i++)
{
if (list[i].CompareTo(list[i + 1]) > 0)
{
T temp = list[i + 1];
list[i + 1] = list[i];
list[i] = temp;
madeChanges = true;
}
}
} while (madeChanges);
}
}
class Program
{
static void Main()
{
List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };
testList.BubbleSort();
foreach (var t in testList) Console.Write(t + " ");
}
}
}
|
Write a version of this Go function in C# with identical behavior. | package main
import (
"fmt"
"io/ioutil"
)
func main() {
b, err := ioutil.ReadFile("input.txt")
if err != nil {
fmt.Println(err)
return
}
if err = ioutil.WriteFile("output.txt", b, 0666); err != nil {
fmt.Println(err)
}
}
| using System;
using System.IO;
namespace FileIO
{
class Program
{
static void Main()
{
String s = scope .();
File.ReadAllText("input.txt", s);
File.WriteAllText("output.txt", s);
}
}
}
|
Produce a functionally identical C# code for the snippet given in Go. | package main
import "fmt"
func main() {
var a, b int
fmt.Print("enter two integers: ")
fmt.Scanln(&a, &b)
fmt.Printf("%d + %d = %d\n", a, b, a+b)
fmt.Printf("%d - %d = %d\n", a, b, a-b)
fmt.Printf("%d * %d = %d\n", a, b, a*b)
fmt.Printf("%d / %d = %d\n", a, b, a/b)
fmt.Printf("%d %% %d = %d\n", a, b, a%b)
}
| using System;
class Program
{
static void Main(string[] args)
{
int a = Convert.ToInt32(args[0]);
int b = Convert.ToInt32(args[1]);
Console.WriteLine("{0} + {1} = {2}", a, b, a + b);
Console.WriteLine("{0} - {1} = {2}", a, b, a - b);
Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
Console.WriteLine("{0} / {1} = {2}", a, b, a / b);
Console.WriteLine("{0} % {1} = {2}", a, b, a % b);
Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b));
}
}
|
Keep all operations the same but rewrite the snippet in C#. | package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
)
func main() {
m := mat.NewDense(2, 3, []float64{
1, 2, 3,
4, 5, 6,
})
fmt.Println(mat.Formatted(m))
fmt.Println()
fmt.Println(mat.Formatted(m.T()))
}
| using System;
using System.Text;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
double[,] m = { {1,2,3},{4,5,6},{7,8,9} };
double[,] t = Transpose( m );
for( int i=0; i<t.GetLength(0); i++ )
{
for( int j=0; j<t.GetLength(1); j++ )
Console.Write( t[i,j] + " " );
Console.WriteLine("");
}
}
public static double[,] Transpose( double[,] m )
{
double[,] t = new double[m.GetLength(1),m.GetLength(0)];
for( int i=0; i<m.GetLength(0); i++ )
for( int j=0; j<m.GetLength(1); j++ )
t[j,i] = m[i,j];
return t;
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. | package main
import "fmt"
func a(k int, x1, x2, x3, x4, x5 func() int) int {
var b func() int
b = func() int {
k--
return a(k, b, x1, x2, x3, x4)
}
if k <= 0 {
return x4() + x5()
}
return b()
}
func main() {
x := func(i int) func() int { return func() int { return i } }
fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0)))
}
| using System;
delegate T Func<T>();
class ManOrBoy
{
static void Main()
{
Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));
}
static Func<int> C(int i)
{
return delegate { return i; };
}
static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)
{
Func<int> b = null;
b = delegate { k--; return A(k, b, x1, x2, x3, x4); };
return k <= 0 ? x4() + x5() : b();
}
}
|
Convert the following code from Go to C#, ensuring the logic remains intact. | package main
import "fmt"
func a(v bool) bool {
fmt.Print("a")
return v
}
func b(v bool) bool {
fmt.Print("b")
return v
}
func test(i, j bool) {
fmt.Printf("Testing a(%t) && b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) && b(j))
fmt.Printf("Testing a(%t) || b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) || b(j))
fmt.Println("")
}
func main() {
test(false, false)
test(false, true)
test(true, false)
test(true, true)
}
| using System;
class Program
{
static bool a(bool value)
{
Console.WriteLine("a");
return value;
}
static bool b(bool value)
{
Console.WriteLine("b");
return value;
}
static void Main()
{
foreach (var i in new[] { false, true })
{
foreach (var j in new[] { false, true })
{
Console.WriteLine("{0} and {1} = {2}", i, j, a(i) && b(j));
Console.WriteLine();
Console.WriteLine("{0} or {1} = {2}", i, j, a(i) || b(j));
Console.WriteLine();
}
}
}
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Go version. | package main
import "fmt"
func a(v bool) bool {
fmt.Print("a")
return v
}
func b(v bool) bool {
fmt.Print("b")
return v
}
func test(i, j bool) {
fmt.Printf("Testing a(%t) && b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) && b(j))
fmt.Printf("Testing a(%t) || b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) || b(j))
fmt.Println("")
}
func main() {
test(false, false)
test(false, true)
test(true, false)
test(true, true)
}
| using System;
class Program
{
static bool a(bool value)
{
Console.WriteLine("a");
return value;
}
static bool b(bool value)
{
Console.WriteLine("b");
return value;
}
static void Main()
{
foreach (var i in new[] { false, true })
{
foreach (var j in new[] { false, true })
{
Console.WriteLine("{0} and {1} = {2}", i, j, a(i) && b(j));
Console.WriteLine();
Console.WriteLine("{0} or {1} = {2}", i, j, a(i) || b(j));
Console.WriteLine();
}
}
}
}
|
Rewrite the snippet below in C# so it works the same as the original Go code. | package main
import (
"flag"
"fmt"
"runtime/debug"
)
func main() {
stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
flag.Parse()
if *stack > 0 {
debug.SetMaxStack(*stack)
}
r(1)
}
func r(l int) {
if l%1000 == 0 {
fmt.Println(l)
}
r(l + 1)
}
| using System;
class RecursionLimit
{
static void Main(string[] args)
{
Recur(0);
}
private static void Recur(int i)
{
Console.WriteLine(i);
Recur(i + 1);
}
}
|
Change the programming language of this snippet from Go to C# without modifying what it does. | package main
import (
"flag"
"fmt"
"runtime/debug"
)
func main() {
stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
flag.Parse()
if *stack > 0 {
debug.SetMaxStack(*stack)
}
r(1)
}
func r(l int) {
if l%1000 == 0 {
fmt.Println(l)
}
r(l + 1)
}
| using System;
class RecursionLimit
{
static void Main(string[] args)
{
Recur(0);
}
private static void Recur(int i)
{
Console.WriteLine(i);
Recur(i + 1);
}
}
|
Ensure the translated C# code behaves exactly like the original Go snippet. | package main
import (
"code.google.com/p/x-go-binding/ui/x11"
"fmt"
"image"
"image/color"
"image/draw"
"log"
"os"
"time"
)
var randcol = genrandcol()
func genrandcol() <-chan color.Color {
c := make(chan color.Color)
go func() {
for {
select {
case c <- image.Black:
case c <- image.White:
}
}
}()
return c
}
func gennoise(screen draw.Image) {
for y := 0; y < 240; y++ {
for x := 0; x < 320; x++ {
screen.Set(x, y, <-randcol)
}
}
}
func fps() chan<- bool {
up := make(chan bool)
go func() {
var frames int64
var lasttime time.Time
var totaltime time.Duration
for {
<-up
frames++
now := time.Now()
totaltime += now.Sub(lasttime)
if totaltime > time.Second {
fmt.Printf("FPS: %v\n", float64(frames)/totaltime.Seconds())
frames = 0
totaltime = 0
}
lasttime = now
}
}()
return up
}
func main() {
win, err := x11.NewWindow()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer win.Close()
go func() {
upfps := fps()
screen := win.Screen()
for {
gennoise(screen)
win.FlushImage()
upfps <- true
}
}()
for _ = range win.EventChan() {
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
class Program
{
static Size size = new Size(320, 240);
static Rectangle rectsize = new Rectangle(new Point(0, 0), size);
static int numpixels = size.Width * size.Height;
static int numbytes = numpixels * 3;
static PictureBox pb;
static BackgroundWorker worker;
static double time = 0;
static double frames = 0;
static Random rand = new Random();
static byte tmp;
static byte white = 255;
static byte black = 0;
static int halfmax = int.MaxValue / 2;
static IEnumerable<byte> YieldVodoo()
{
for (int i = 0; i < numpixels; i++)
{
tmp = rand.Next() < halfmax ? black : white;
yield return tmp;
yield return tmp;
yield return tmp;
}
}
static Image Randimg()
{
var bitmap = new Bitmap(size.Width, size.Height);
var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
Marshal.Copy(
YieldVodoo().ToArray<byte>(),
0,
data.Scan0,
numbytes);
bitmap.UnlockBits(data);
return bitmap;
}
[STAThread]
static void Main()
{
var form = new Form();
form.AutoSize = true;
form.Size = new Size(0, 0);
form.Text = "Test";
form.FormClosed += delegate
{
Application.Exit();
};
worker = new BackgroundWorker();
worker.DoWork += delegate
{
System.Threading.Thread.Sleep(500);
while (true)
{
var a = DateTime.Now;
pb.Image = Randimg();
var b = DateTime.Now;
time += (b - a).TotalSeconds;
frames += 1;
if (frames == 30)
{
Console.WriteLine("{0} frames in {1:0.000} seconds. ({2:0} FPS)", frames, time, frames / time);
time = 0;
frames = 0;
}
}
};
worker.RunWorkerAsync();
FlowLayoutPanel flp = new FlowLayoutPanel();
form.Controls.Add(flp);
pb = new PictureBox();
pb.Size = size;
flp.AutoSize = true;
flp.Controls.Add(pb);
form.Show();
Application.Run();
}
}
|
Rewrite the snippet below in C# so it works the same as the original Go code. | package main
import "fmt"
func computePerfect(n int64) bool {
var sum int64
for i := int64(1); i < n; i++ {
if n%i == 0 {
sum += i
}
}
return sum == n
}
func isPerfect(n int64) bool {
switch n {
case 6, 28, 496, 8128, 33550336, 8589869056,
137438691328, 2305843008139952128:
return true
}
return false
}
func main() {
for n := int64(1); ; n++ {
if isPerfect(n) != computePerfect(n) {
panic("bug")
}
if n%1e3 == 0 {
fmt.Println("tested", n)
}
}
}
| static void Main(string[] args)
{
Console.WriteLine("Perfect numbers from 1 to 33550337:");
for (int x = 0; x < 33550337; x++)
{
if (IsPerfect(x))
Console.WriteLine(x + " is perfect.");
}
Console.ReadLine();
}
static bool IsPerfect(int num)
{
int sum = 0;
for (int i = 1; i < num; i++)
{
if (num % i == 0)
sum += i;
}
return sum == num ;
}
|
Please provide an equivalent version of this Go code in C#. | package main
import (
"fmt"
"math/big"
)
func main() {
x := big.NewInt(2)
x = x.Exp(big.NewInt(3), x, nil)
x = x.Exp(big.NewInt(4), x, nil)
x = x.Exp(big.NewInt(5), x, nil)
str := x.String()
fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n",
len(str),
str[:20],
str[len(str)-20:],
)
}
| using System;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
static class Program {
static void Main() {
BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));
string result = n.ToString();
Debug.Assert(result.Length == 183231);
Debug.Assert(result.StartsWith("62060698786608744707"));
Debug.Assert(result.EndsWith("92256259918212890625"));
Console.WriteLine("n = 5^4^3^2");
Console.WriteLine("n = {0}...{1}",
result.Substring(0, 20),
result.Substring(result.Length - 20, 20)
);
Console.WriteLine("n digits = {0}", result.Length);
}
}
|
Write the same algorithm in C# as shown in this Go implementation. | package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
)
var index map[string][]int
var indexed []doc
type doc struct {
file string
title string
}
func main() {
index = make(map[string][]int)
if err := indexDir("docs"); err != nil {
fmt.Println(err)
return
}
ui()
}
func indexDir(dir string) error {
df, err := os.Open(dir)
if err != nil {
return err
}
fis, err := df.Readdir(-1)
if err != nil {
return err
}
if len(fis) == 0 {
return errors.New(fmt.Sprintf("no files in %s", dir))
}
indexed := 0
for _, fi := range fis {
if !fi.IsDir() {
if indexFile(dir + "/" + fi.Name()) {
indexed++
}
}
}
return nil
}
func indexFile(fn string) bool {
f, err := os.Open(fn)
if err != nil {
fmt.Println(err)
return false
}
x := len(indexed)
indexed = append(indexed, doc{fn, fn})
pdoc := &indexed[x]
r := bufio.NewReader(f)
lines := 0
for {
b, isPrefix, err := r.ReadLine()
switch {
case err == io.EOF:
return true
case err != nil:
fmt.Println(err)
return true
case isPrefix:
fmt.Printf("%s: unexpected long line\n", fn)
return true
case lines < 20 && bytes.HasPrefix(b, []byte("Title:")):
pdoc.title = string(b[7:])
}
wordLoop:
for _, bword := range bytes.Fields(b) {
bword := bytes.Trim(bword, ".,-~?!\"'`;:()<>[]{}\\|/=_+*&^%$#@")
if len(bword) > 0 {
word := string(bword)
dl := index[word]
for _, d := range dl {
if d == x {
continue wordLoop
}
}
index[word] = append(dl, x)
}
}
}
return true
}
func ui() {
fmt.Println(len(index), "words indexed in", len(indexed), "files")
fmt.Println("enter single words to search for")
fmt.Println("enter a blank line when done")
var word string
for {
fmt.Print("search word: ")
wc, _ := fmt.Scanln(&word)
if wc == 0 {
return
}
switch dl := index[word]; len(dl) {
case 0:
fmt.Println("no match")
case 1:
fmt.Println("one match:")
fmt.Println(" ", indexed[dl[0]].file, indexed[dl[0]].title)
default:
fmt.Println(len(dl), "matches:")
for _, d := range dl {
fmt.Println(" ", indexed[d].file, indexed[d].title)
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class InvertedIndex
{
static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)
{
return dictionary
.SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))
.GroupBy(keyValuePair => keyValuePair.Key)
.ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));
}
static void Main()
{
Console.Write("files: ");
var files = Console.ReadLine();
Console.Write("find: ");
var find = Console.ReadLine();
var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable());
Console.WriteLine("{0} found in: {1}", find, string.Join(" ", Invert(dictionary)[find]));
}
}
|
Translate the given Go code snippet into C# without altering its behavior. | package main
import (
"fmt"
"math/big"
)
var m, n, z big.Int
func init() {
m.SetString("2562047788015215500854906332309589561", 10)
n.SetString("6795454494268282920431565661684282819", 10)
}
func main() {
fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
}
| Using System;
class Program
{
static int gcd(int m, int n)
{
return n == 0 ? Math.Abs(m) : gcd(n, n % m);
}
static int lcm(int m, int n)
{
return Math.Abs(m * n) / gcd(m, n);
}
static void Main()
{
Console.WriteLine("lcm(12,18)=" + lcm(12,18));
}
}
|
Can you help me rewrite this code in C# instead of Go, keeping it the same logically? | package main
import (
"fmt"
"math/big"
)
var m, n, z big.Int
func init() {
m.SetString("2562047788015215500854906332309589561", 10)
n.SetString("6795454494268282920431565661684282819", 10)
}
func main() {
fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
}
| Using System;
class Program
{
static int gcd(int m, int n)
{
return n == 0 ? Math.Abs(m) : gcd(n, n % m);
}
static int lcm(int m, int n)
{
return Math.Abs(m * n) / gcd(m, n);
}
static void Main()
{
Console.WriteLine("lcm(12,18)=" + lcm(12,18));
}
}
|
Please provide an equivalent version of this Go code in C#. | package main
import "fmt"
import "math/rand"
import "time"
func main() {
rand.Seed(time.Now().UnixNano())
for {
a := rand.Intn(20)
fmt.Println(a)
if a == 10 {
break
}
b := rand.Intn(20)
fmt.Println(b)
}
}
| class Program
{
static void Main(string[] args)
{
Random random = new Random();
while (true)
{
int a = random.Next(20);
Console.WriteLine(a);
if (a == 10)
break;
int b = random.Next(20)
Console.WriteLine(b);
}
Console.ReadLine();
}
}
|
Convert this Go block to C#, preserving its control flow and logic. | package main
import "fmt"
func maxl(hm []int ) []int{
res := make([]int,len(hm))
max := 1
for i := 0; i < len(hm);i++{
if(hm[i] > max){
max = hm[i]
}
res[i] = max;
}
return res
}
func maxr(hm []int ) []int{
res := make([]int,len(hm))
max := 1
for i := len(hm) - 1 ; i >= 0;i--{
if(hm[i] > max){
max = hm[i]
}
res[i] = max;
}
return res
}
func min(a,b []int) []int {
res := make([]int,len(a))
for i := 0; i < len(a);i++{
if a[i] >= b[i]{
res[i] = b[i]
}else {
res[i] = a[i]
}
}
return res
}
func diff(hm, min []int) []int {
res := make([]int,len(hm))
for i := 0; i < len(hm);i++{
if min[i] > hm[i]{
res[i] = min[i] - hm[i]
}
}
return res
}
func sum(a []int) int {
res := 0
for i := 0; i < len(a);i++{
res += a[i]
}
return res
}
func waterCollected(hm []int) int {
maxr := maxr(hm)
maxl := maxl(hm)
min := min(maxr,maxl)
diff := diff(hm,min)
sum := sum(diff)
return sum
}
func main() {
fmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))
fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))
fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))
fmt.Println(waterCollected([]int{5, 5, 5, 5}))
fmt.Println(waterCollected([]int{5, 6, 7, 8}))
fmt.Println(waterCollected([]int{8, 7, 7, 6}))
fmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))
}
| class Program
{
static void Main(string[] args)
{
int[][] wta = {
new int[] {1, 5, 3, 7, 2}, new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },
new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },
new int[] { 5, 5, 5, 5 }, new int[] { 5, 6, 7, 8 },
new int[] { 8, 7, 7, 6 }, new int[] { 6, 7, 10, 7, 6 }};
string blk, lf = "\n", tb = "██", wr = "≈≈", mt = " ";
for (int i = 0; i < wta.Length; i++)
{
int bpf; blk = ""; do
{
string floor = ""; bpf = 0; for (int j = 0; j < wta[i].Length; j++)
{
if (wta[i][j] > 0)
{ floor += tb; wta[i][j] -= 1; bpf += 1; }
else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);
}
if (bpf > 0) blk = floor + lf + blk;
} while (bpf > 0);
while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);
while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);
if (args.Length > 0) System.Console.Write("\n{0}", blk);
System.Console.WriteLine("Block {0} retains {1,2} water units.",
i + 1, (blk.Length - blk.Replace(wr, "").Length) / 2);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.