Dataset Viewer
name
stringlengths 2
74
| C
stringlengths 7
6.19k
| Rust
stringlengths 19
8.53k
|
---|---|---|
100 doors | #include <stdio.h>
int main()
{
char is_open[100] = { 0 };
int pass, door;
for (pass = 0; pass < 100; ++pass)
for (door = pass; door < 100; door += pass+1)
is_open[door] = !is_open[door];
for (door = 0; door < 100; ++door)
printf("door #%d is %s.\n", door+1, (is_open[door]? "open" : "closed"));
return 0;
}
| fn main() {
let mut door_open = [false; 100];
for pass in 1..101 {
let mut door = pass;
while door <= 100 {
door_open[door - 1] = !door_open[door - 1];
door += pass;
}
}
for (i, &is_open) in door_open.iter().enumerate() {
println!(
"Door {} is {}.",
i + 1,
if is_open { "open" } else { "closed" }
);
}
}
|
100 prisoners | #include<stdbool.h>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
#define LIBERTY false
#define DEATH true
typedef struct{
int cardNum;
bool hasBeenOpened;
}drawer;
drawer *drawerSet;
void initialize(int prisoners){
int i,j,card;
bool unique;
drawerSet = ((drawer*)malloc(prisoners * sizeof(drawer))) -1;
card = rand()%prisoners + 1;
drawerSet[1] = (drawer){.cardNum = card, .hasBeenOpened = false};
for(i=1 + 1;i<prisoners + 1;i++){
unique = false;
while(unique==false){
for(j=0;j<i;j++){
if(drawerSet[j].cardNum == card){
card = rand()%prisoners + 1;
break;
}
}
if(j==i){
unique = true;
}
}
drawerSet[i] = (drawer){.cardNum = card, .hasBeenOpened = false};
}
}
void closeAllDrawers(int prisoners){
int i;
for(i=1;i<prisoners + 1;i++)
drawerSet[i].hasBeenOpened = false;
}
bool libertyOrDeathAtRandom(int prisoners,int chances){
int i,j,chosenDrawer;
for(i= 1;i<prisoners + 1;i++){
bool foundCard = false;
for(j=0;j<chances;j++){
do{
chosenDrawer = rand()%prisoners + 1;
}while(drawerSet[chosenDrawer].hasBeenOpened==true);
if(drawerSet[chosenDrawer].cardNum == i){
foundCard = true;
break;
}
drawerSet[chosenDrawer].hasBeenOpened = true;
}
closeAllDrawers(prisoners);
if(foundCard == false)
return DEATH;
}
return LIBERTY;
}
bool libertyOrDeathPlanned(int prisoners,int chances){
int i,j,chosenDrawer;
for(i=1;i<prisoners + 1;i++){
chosenDrawer = i;
bool foundCard = false;
for(j=0;j<chances;j++){
drawerSet[chosenDrawer].hasBeenOpened = true;
if(drawerSet[chosenDrawer].cardNum == i){
foundCard = true;
break;
}
if(chosenDrawer == drawerSet[chosenDrawer].cardNum){
do{
chosenDrawer = rand()%prisoners + 1;
}while(drawerSet[chosenDrawer].hasBeenOpened==true);
}
else{
chosenDrawer = drawerSet[chosenDrawer].cardNum;
}
}
closeAllDrawers(prisoners);
if(foundCard == false)
return DEATH;
}
return LIBERTY;
}
int main(int argc,char** argv)
{
int prisoners, chances;
unsigned long long int trials,i,count = 0;
char* end;
if(argc!=4)
return printf("Usage : %s <Number of prisoners> <Number of chances> <Number of trials>",argv[0]);
prisoners = atoi(argv[1]);
chances = atoi(argv[2]);
trials = strtoull(argv[3],&end,10);
srand(time(NULL));
printf("Running random trials...");
for(i=0;i<trials;i+=1L){
initialize(prisoners);
count += libertyOrDeathAtRandom(prisoners,chances)==DEATH?0:1;
}
printf("\n\nGames Played : %llu\nGames Won : %llu\nChances : %lf %% \n\n",trials,count,(100.0*count)/trials);
count = 0;
printf("Running strategic trials...");
for(i=0;i<trials;i+=1L){
initialize(prisoners);
count += libertyOrDeathPlanned(prisoners,chances)==DEATH?0:1;
}
printf("\n\nGames Played : %llu\nGames Won : %llu\nChances : %lf %% \n\n",trials,count,(100.0*count)/trials);
return 0;
}
| extern crate rand;
use rand::prelude::*;
fn check_random_boxes(prisoner: u8, boxes: &[u8]) -> bool {
let checks = {
let mut b: Vec<u8> = (1u8..=100u8).collect();
b.shuffle(&mut rand::thread_rng());
b
};
checks.into_iter().take(50).any(|check| boxes[check as usize - 1] == prisoner)
}
fn check_ordered_boxes(prisoner: u8, boxes: &[u8]) -> bool {
let mut next_check = prisoner;
(0..50).any(|_| {
next_check = boxes[next_check as usize - 1];
next_check == prisoner
})
}
fn main() {
let mut boxes: Vec<u8> = (1u8..=100u8).collect();
let trials = 100000;
let ordered_successes = (0..trials).filter(|_| {
boxes.shuffle(&mut rand::thread_rng());
(1u8..=100u8).all(|prisoner| check_ordered_boxes(prisoner, &boxes))
}).count();
let random_successes = (0..trials).filter(|_| {
boxes.shuffle(&mut rand::thread_rng());
(1u8..=100u8).all(|prisoner| check_random_boxes(prisoner, &boxes))
}).count();
println!("{} / {} ({:.02}%) successes in ordered", ordered_successes, trials, ordered_successes as f64 * 100.0 / trials as f64);
println!("{} / {} ({:.02}%) successes in random", random_successes, trials, random_successes as f64 * 100.0 / trials as f64);
}
|
15 puzzle game |
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 4
#define M 4
enum Move{UP,DOWN,LEFT,RIGHT};int hR;int hC;int cc[N][M];const int nS=100;int
update(enum Move m){const int dx[]={0,0,-1,1};const int dy[]={-1,1,0,0};int i=hR
+dy[m];int j=hC+dx[m];if(i>= 0&&i<N&&j>=0&&j<M){cc[hR][hC]=cc[i][j];cc[i][j]=0;
hR=i;hC=j;return 1;}return 0;}void setup(void){int i,j,k;for(i=0;i<N;i++)for(j=0
;j<M;j++)cc[i][j]=i*M+j+1;cc[N-1][M-1]=0;hR=N-1;hC=M-1;k=0;while(k<nS)k+=update(
(enum Move)(rand()%4));}int isEnd(void){int i,j; int k=1;for(i=0;i<N;i++)for(j=0
;j<M;j++)if((k<N*M)&&(cc[i][j]!=k++))return 0;return 1;}void show(){int i,j;
putchar('\n');for(i=0;i<N;i++)for(j=0;j<M;j++){if(cc[i][j])printf(j!=M-1?" %2d "
:" %2d \n",cc[i][j]);else printf(j!=M-1?" %2s ":" %2s \n", "");}putchar('\n');}
void disp(char* s){printf("\n%s\n", s);}enum Move get(void){int c;for(;;){printf
("%s","enter u/d/l/r : ");c=getchar();while(getchar()!='\n');switch(c){case 27:
exit(0);case'd':return UP;case'u':return DOWN;case'r':return LEFT;case'l':return
RIGHT;}}}void pause(void){getchar();}int main(void){srand((unsigned)time(NULL));
do setup();while(isEnd());show();while(!isEnd()){update(get());show();}disp(
"You win"); pause();return 0;}
| extern crate rand;
use std::collections::HashMap;
use std::fmt;
use rand::seq::SliceRandom;
use rand::Rng;
#[derive(Copy, Clone, PartialEq, Debug)]
enum Cell {
Card(usize),
Empty,
}
#[derive(Eq, PartialEq, Hash, Debug)]
enum Direction {
Up,
Down,
Left,
Right,
}
enum Action {
Move(Direction),
Quit,
}
type Board = [Cell; 16];
const EMPTY: Board = [Cell::Empty; 16];
struct P15 {
board: Board,
}
impl P15 {
fn new() -> Self {
let mut board = EMPTY;
for (i, cell) in board.iter_mut().enumerate().skip(1) {
*cell = Cell::Card(i);
}
let mut rng = rand::thread_rng();
board.shuffle(&mut rng);
if !Self::is_valid(board) {
let i = rng.gen_range(0..16);
let mut j = rng.gen_range(0..16);
while j == i {
j = rng.gen_range(0..16);
}
board.swap(i, j);
}
Self { board }
}
fn is_valid(mut board: Board) -> bool {
let mut permutations = 0;
let pos = board.iter().position(|&cell| cell == Cell::Empty).unwrap();
if pos != 15 {
board.swap(pos, 15);
permutations += 1;
}
for i in 1..16 {
let pos = board
.iter()
.position(|&cell| match cell {
Cell::Card(value) if value == i => true,
_ => false,
})
.unwrap();
if pos + 1 != i {
board.swap(pos, i - 1);
permutations += 1;
}
}
permutations % 2 == 0
}
fn get_empty_position(&self) -> usize {
self.board.iter().position(|&c| c == Cell::Empty).unwrap()
}
fn get_moves(&self) -> HashMap<Direction, Cell> {
let mut moves = HashMap::new();
let i = self.get_empty_position();
if i > 3 {
moves.insert(Direction::Up, self.board[i - 4]);
}
if i % 4 != 0 {
moves.insert(Direction::Left, self.board[i - 1]);
}
if i < 12 {
moves.insert(Direction::Down, self.board[i + 4]);
}
if i % 4 != 3 {
moves.insert(Direction::Right, self.board[i + 1]);
}
moves
}
fn play(&mut self, direction: &Direction) {
let i = self.get_empty_position();
match *direction {
Direction::Up => self.board.swap(i, i - 4),
Direction::Left => self.board.swap(i, i - 1),
Direction::Right => self.board.swap(i, i + 1),
Direction::Down => self.board.swap(i, i + 4),
};
}
fn is_complete(&self) -> bool {
self.board.iter().enumerate().all(|(i, &cell)| match cell {
Cell::Card(value) => value == i + 1,
Cell::Empty => i == 15,
})
}
}
impl fmt::Display for P15 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(writeln!(f, "+----+----+----+----+"))?;
for (i, &cell) in self.board.iter().enumerate() {
match cell {
Cell::Card(value) => (write!(f, "| {value:2} "))?,
Cell::Empty => (write!(f, "| "))?,
}
if i % 4 == 3 {
(writeln!(f, "|"))?;
(writeln!(f, "+----+----+----+----+"))?;
}
}
Ok(())
}
}
fn main() {
let mut p15 = P15::new();
for turns in 1.. {
println!("{p15}");
match ask_action(&p15.get_moves()) {
Action::Move(direction) => {
p15.play(&direction);
print!("\x1B[2J\x1B[1;1H");
}
Action::Quit => {
print!("\x1B[2J\x1B[1;1H");
println!("Bye !");
break;
}
}
if p15.is_complete() {
println!("Well done ! You won in {turns} turns");
break;
}
}
}
fn ask_action(moves: &HashMap<Direction, Cell>) -> Action {
use std::io::{self, Write};
use Action::*;
use Direction::*;
println!("Possible moves:");
if let Some(&Cell::Card(value)) = moves.get(&Up) {
println!("\tU) {value}");
}
if let Some(&Cell::Card(value)) = moves.get(&Left) {
println!("\tL) {value}");
}
if let Some(&Cell::Card(value)) = moves.get(&Right) {
println!("\tR) {value}");
}
if let Some(&Cell::Card(value)) = moves.get(&Down) {
println!("\tD) {value}");
}
println!("\tQ) Quit");
print!("Choose your move : ");
io::stdout().flush().unwrap();
let mut action = String::new();
io::stdin().read_line(&mut action).expect("read error");
match action.to_uppercase().trim() {
"U" if moves.contains_key(&Up) => Move(Up),
"L" if moves.contains_key(&Left) => Move(Left),
"R" if moves.contains_key(&Right) => Move(Right),
"D" if moves.contains_key(&Down) => Move(Down),
"Q" => Quit,
_ => {
println!("Unknown action: {action}");
ask_action(moves)
}
}
}
|
21 game |
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#if __STDC_VERSION__ >= 199901L || _MSC_VER >= 1800
#include <stdbool.h>
#else
#define bool int
#define true 1
#define false 0
#endif
#define GOAL 21
#define NUMBER_OF_PLAYERS 2
#define MIN_MOVE 1
#define MAX_MOVE 3
#define BUFFER_SIZE 256
#define _(STRING) STRING
static char DESCRIPTION[] =
"21 Game \n"
" \n"
"21 is a two player game, the game is played by choosing a number \n"
"(1, 2, or 3) to be added to the running total. The game is won by\n"
"the player whose chosen number causes the running total to reach \n"
"exactly 21. The running total starts at zero. \n\n";
static int total;
void update(char* player, int move)
{
printf("%8s: %d = %d + %d\n\n", player, total + move, total, move);
total += move;
if (total == GOAL)
printf(_("The winner is %s.\n\n"), player);
}
int ai()
{
#if GOAL < 32 && MIN_MOVE == 1 && MAX_MOVE == 3
static const int precomputed[] = { 1, 1, 3, 2, 1, 1, 3, 2, 1, 1, 3, 2, 1, 1,
3, 2, 1, 1, 3, 2, 1, 1, 3, 2, 1, 1, 3, 2, 1, 1, 3 };
update(_("ai"), precomputed[total]);
#elif MIN_MOVE == 1 && MAX_MOVE == 3
static const int precomputed[] = { 1, 1, 3, 2};
update(_("ai"), precomputed[total % (MAX_MOVE + 1)]);
#else
int i;
int move = 1;
for (i = MIN_MOVE; i <= MAX_MOVE; i++)
if ((total + i - 1) % (MAX_MOVE + 1) == 0)
move = i;
for (i = MIN_MOVE; i <= MAX_MOVE; i++)
if (total + i == GOAL)
move = i;
update(_("ai"), move);
#endif
}
void human(void)
{
char buffer[BUFFER_SIZE];
int move;
while ( printf(_("enter your move to play (or enter 0 to exit game): ")),
fgets(buffer, BUFFER_SIZE, stdin),
sscanf(buffer, "%d", &move) != 1 ||
(move && (move < MIN_MOVE || move > MAX_MOVE || total+move > GOAL)))
puts(_("\nYour answer is not a valid choice.\n"));
putchar('\n');
if (!move) exit(EXIT_SUCCESS);
update(_("human"), move);
}
int main(int argc, char* argv[])
{
srand(time(NULL));
puts(_(DESCRIPTION));
while (true)
{
puts(_("\n---- NEW GAME ----\n"));
puts(_("\nThe running total is currently zero.\n"));
total = 0;
if (rand() % NUMBER_OF_PLAYERS)
{
puts(_("The first move is AI move.\n"));
ai();
}
else
puts(_("The first move is human move.\n"));
while (total < GOAL)
{
human();
ai();
}
}
}
| use rand::Rng;
use std::io;
#[derive(Clone)]
enum PlayerType {
Human,
Computer,
}
#[derive(Clone)]
struct Player {
name: String,
wins: u32,
level: u32,
player_type: PlayerType,
}
trait Choose {
fn choose(&self, game: &Game) -> u8;
}
impl Player {
fn new(name: &str, player_type: PlayerType, level: u32) -> Player {
Player {
name: String::from(name),
wins: 0,
level,
player_type,
}
}
fn get_name(&self) -> &str {
&self.name[..]
}
fn get_level(&self) -> u32 {
self.level
}
fn add_win(&mut self) {
self.wins += 1
}
fn level_up(&mut self) {
self.level += 1
}
}
impl Choose for Player {
fn choose(&self, game: &Game) -> u8 {
match self.player_type {
PlayerType::Human => loop {
let max_choice = game.max_choice();
match max_choice {
1 => println!("Enter a number 1 to win (or quit):"),
_ => println!("Enter a number between 1 and {} (or quit):", max_choice)
}
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
if guess.trim() == "quit" {
return 0
}
let guess: u8 = match guess.trim().parse() {
Ok(num) if num >= 1 && num <= max_choice => num,
Ok(_) => continue,
Err(_) => continue,
};
return guess;
},
PlayerType::Computer => match self.level {
5 => match game.get_total() {
total if total == 20 => 1,
total if total == 19 => 2,
total if total == 18 => 3,
_ => 1,
},
4 => match game.get_total() {
total if total == 20 => 1,
total if total == 19 => 2,
total if total == 18 => 3,
_ => rand::thread_rng().gen_range(1, 3),
},
3 => match game.get_total() {
total if total == 20 => 1,
total if total == 19 => 2,
total if total == 18 => 3,
_ => rand::thread_rng().gen_range(1, 4),
},
2 => match game.get_total() {
total if total == 20 => 1,
total if total == 19 => 2,
_ => rand::thread_rng().gen_range(1, 3),
},
1 => 1,
_ => match game.get_total() {
total if total == 20 => 1,
total if total == 19 => 2,
total if total == 18 => 3,
_ => match game.get_remaining() % 4 {
0 => rand::thread_rng().gen_range(1, 4),
_ => game.get_remaining() % 4,
},
},
},
}
}
}
struct Game {
players: Vec<Player>,
turn: u8,
total: u8,
start: u8,
}
impl Game {
fn init(players: &Vec<Player>) -> Game {
Game {
players: players.to_vec(),
turn: 1,
total: 0,
start: rand::thread_rng().gen_range(0, 2),
}
}
fn play(&mut self) -> &Player {
loop {
println!(
"Total now {} (remaining: {})",
self.get_total(),
self.get_remaining()
);
{
let player = self.whose_turn();
println!("Turn: {} ({} turn)", self.get_turn(), player.get_name());
let choice = player.choose(&self);
if choice == 0 {
self.next_turn();
break;
}
println!("{} choose {}", player.get_name(), choice);
self.add_total(choice)
}
if self.get_total() >= 21 {
break;
}
println!("");
self.next_turn();
}
self.whose_turn()
}
fn add_total(&mut self, choice: u8) {
self.total += choice;
}
fn next_turn(&mut self) {
self.turn += 1;
}
fn whose_turn(&self) -> &Player {
let index: usize = ((self.turn + self.start) % 2).into();
&self.players[index]
}
fn get_total(&self) -> u8 {
self.total
}
fn get_remaining(&self) -> u8 {
21 - self.total
}
fn max_choice(&self) -> u8 {
match self.get_remaining() {
1 => 1,
2 => 2,
_ => 3
}
}
fn get_turn(&self) -> u8 {
self.turn
}
}
fn main() {
let mut game_count = 0;
let mut players = vec![
Player::new("human", PlayerType::Human, 0),
Player::new("computer", PlayerType::Computer, 1),
];
println!("21 Game");
println!("Press enter key to start");
{
let _ = io::stdin().read_line(&mut String::new());
}
loop {
game_count += 1;
let mut game = Game::init(&players);
let winner = game.play();
{
let mut index = 0;
while index < players.len() {
if players[index].get_name() == winner.get_name() {
players[index].add_win();
}
index += 1
}
}
println!("\n{} won game {}\n", winner.get_name(), game_count);
if game_count >= 10000 {
break;
}
println!("Press enter key to play again (or quit):");
let mut reply = String::new();
io::stdin()
.read_line(&mut reply)
.expect("Failed to read line");
if reply.trim() == "quit" {
break;
}
if winner.get_name() != "computer" {
println!("Computer leveling up ...");
players[1].level_up();
println!("Computer now level {}!", players[1].get_level());
println!("Beware!\n");
}
}
println!("player: {} win: {}", players[0].get_name(), players[0].wins);
println!("player: {} win: {}", players[1].get_name(), players[1].wins);
}
|
4-rings or 4-squares puzzle | #include <stdio.h>
#define TRUE 1
#define FALSE 0
int a,b,c,d,e,f,g;
int lo,hi,unique,show;
int solutions;
void
bf()
{
for (f = lo;f <= hi; f++)
if ((!unique) ||
((f != a) && (f != c) && (f != d) && (f != g) && (f != e)))
{
b = e + f - c;
if ((b >= lo) && (b <= hi) &&
((!unique) || ((b != a) && (b != c) &&
(b != d) && (b != g) && (b != e) && (b != f))))
{
solutions++;
if (show)
printf("%d %d %d %d %d %d %d\n",a,b,c,d,e,f,g);
}
}
}
void
ge()
{
for (e = lo;e <= hi; e++)
if ((!unique) || ((e != a) && (e != c) && (e != d)))
{
g = d + e;
if ((g >= lo) && (g <= hi) &&
((!unique) || ((g != a) && (g != c) &&
(g != d) && (g != e))))
bf();
}
}
void
acd()
{
for (c = lo;c <= hi; c++)
for (d = lo;d <= hi; d++)
if ((!unique) || (c != d))
{
a = c + d;
if ((a >= lo) && (a <= hi) &&
((!unique) || ((c != 0) && (d != 0))))
ge();
}
}
void
foursquares(int plo,int phi, int punique,int pshow)
{
lo = plo;
hi = phi;
unique = punique;
show = pshow;
solutions = 0;
printf("\n");
acd();
if (unique)
printf("\n%d unique solutions in %d to %d\n",solutions,lo,hi);
else
printf("\n%d non-unique solutions in %d to %d\n",solutions,lo,hi);
}
main()
{
foursquares(1,7,TRUE,TRUE);
foursquares(3,9,TRUE,TRUE);
foursquares(0,9,FALSE,FALSE);
}
| #![feature(inclusive_range_syntax)]
fn is_unique(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8, g: u8) -> bool {
a != b && a != c && a != d && a != e && a != f && a != g &&
b != c && b != d && b != e && b != f && b != g &&
c != d && c != e && c != f && c != g &&
d != e && d != f && d != g &&
e != f && e != g &&
f != g
}
fn is_solution(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8, g: u8) -> bool {
a + b == b + c + d &&
b + c + d == d + e + f &&
d + e + f == f + g
}
fn four_squares(low: u8, high: u8, unique: bool) -> Vec<Vec<u8>> {
let mut results: Vec<Vec<u8>> = Vec::new();
for a in low..=high {
for b in low..=high {
for c in low..=high {
for d in low..=high {
for e in low..=high {
for f in low..=high {
for g in low..=high {
if (!unique || is_unique(a, b, c, d, e, f, g)) &&
is_solution(a, b, c, d, e, f, g) {
results.push(vec![a, b, c, d, e, f, g]);
}
}
}
}
}
}
}
}
results
}
fn print_results(solutions: &Vec<Vec<u8>>) {
for solution in solutions {
println!("{:?}", solution)
}
}
fn print_results_summary(solutions: usize, low: u8, high: u8, unique: bool) {
let uniqueness = if unique {
"unique"
} else {
"non-unique"
};
println!("{} {} solutions in {} to {} range", solutions, uniqueness, low, high)
}
fn uniques(low: u8, high: u8) {
let solutions = four_squares(low, high, true);
print_results(&solutions);
print_results_summary(solutions.len(), low, high, true);
}
fn nonuniques(low: u8, high: u8) {
let solutions = four_squares(low, high, false);
print_results_summary(solutions.len(), low, high, false);
}
fn main() {
uniques(1, 7);
println!();
uniques(3, 9);
println!();
nonuniques(0, 9);
}
|
9 billion names of God the integer | #include <stdio.h>
#include <gmp.h>
#define N 100000
mpz_t p[N + 1];
void calc(int n)
{
mpz_init_set_ui(p[n], 0);
for (int k = 1; k <= n; k++) {
int d = n - k * (3 * k - 1) / 2;
if (d < 0) break;
if (k&1)mpz_add(p[n], p[n], p[d]);
else mpz_sub(p[n], p[n], p[d]);
d -= k;
if (d < 0) break;
if (k&1)mpz_add(p[n], p[n], p[d]);
else mpz_sub(p[n], p[n], p[d]);
}
}
int main(void)
{
int idx[] = { 23, 123, 1234, 12345, 20000, 30000, 40000, 50000, N, 0 };
int at = 0;
mpz_init_set_ui(p[0], 1);
for (int i = 1; idx[at]; i++) {
calc(i);
if (i != idx[at]) continue;
gmp_printf("%2d:\t%Zd\n", i, p[i]);
at++;
}
}
| extern crate num;
use std::cmp;
use num::bigint::BigUint;
fn cumu(n: usize, cache: &mut Vec<Vec<BigUint>>) {
for l in cache.len()..n+1 {
let mut r = vec![BigUint::from(0u32)];
for x in 1..l+1 {
let prev = r[r.len() - 1].clone();
r.push(prev + cache[l-x][cmp::min(x, l-x)].clone());
}
cache.push(r);
}
}
fn row(n: usize, cache: &mut Vec<Vec<BigUint>>) -> Vec<BigUint> {
cumu(n, cache);
let r = &cache[n];
let mut v: Vec<BigUint> = Vec::new();
for i in 0..n {
v.push(&r[i+1] - &r[i]);
}
v
}
fn main() {
let mut cache = vec![vec![BigUint::from(1u32)]];
println!("rows:");
for x in 1..26 {
let v: Vec<String> = row(x, &mut cache).iter().map(|e| e.to_string()).collect();
let s: String = v.join(" ");
println!("{}: {}", x, s);
}
println!("sums:");
for x in vec![23, 123, 1234, 12345] {
cumu(x, &mut cache);
let v = &cache[x];
let s = v[v.len() - 1].to_string();
println!("{}: {}", x, s);
}
}
|
99 bottles of beer | const bottle = " bottle"
const plural = "s"
const ofbeer = " of beer"
const wall = " on the wall"
const sep = ", "
const takedown = "Take one down and pass it around, "
const u_no = "No"
const l_no = "no"
const more = " more bottles of beer"
const store = "Go to the store and buy some more, "
const dotnl = ".\n"
const nl = "\n"
var x 1024
fun printnum
b = a
a >= 10
a /= 10
b = d
a += 48
print(chr(a))
end
a = b
a += 48
print(chr(a))
end
fun main
loop 99
c -> stack
c -> stack
a = c
printnum()
x = bottle
x += plural
x += ofbeer
x += wall
x += sep
print(x)
stack -> a
printnum()
x = bottle
x += plural
x += ofbeer
x += dotnl
x += takedown
print(x)
stack -> a
a--
a -> stack
printnum()
print(bottle)
stack -> a
a != 1
print(plural)
end
x = ofbeer
x += wall
x += dotnl
x += nl
print(x)
continue (c >= 2)
a = 1
printnum()
x = bottle
x += ofbeer
x += wall
x += sep
print(x)
a = 1
printnum()
x = bottle
x += ofbeer
x += dotnl
x += takedown
x += l_no
x += more
x += wall
x += dotnl
x += nl
x += u_no
x += more
x += wall
x += sep
x += l_no
x += more
x += dotnl
x += store
print(x)
a = 99
printnum()
x = bottle
x += plural
x += ofbeer
x += wall
x += dotnl
print(x)
end
end
| fn main() {
for n in (0..100).rev() {
match n {
0 => {
println!("No more bottles of beer on the wall, no more bottles of beer.");
println!("Go to the store and buy some more, 99 bottles of beer on the wall.");
},
1 => {
println!("1 bottle of beer on the wall, 1 bottle of beer.");
println!("Take one down and pass it around, no more bottles of beer on the wall.\n");
},
_ => {
println!("{0:?} bottles of beer on the wall, {0:?} bottles of beer.", n);
println!("Take one down and pass it around, {} bottles of beer on the wall.\n", n-1);
},
}
}
}
|
A+B |
#include <stdio.h>
int main()
{
int a, b;
scanf("%d%d", &a, &b);
printf("%d\n", a + b);
return 0;
}
| use std::io;
fn main() {
let mut line = String::new();
io::stdin().read_line(&mut line).expect("reading stdin");
let mut i: i64 = 0;
for word in line.split_whitespace() {
i += word.parse::<i64>().expect("trying to interpret your input as numbers");
}
println!("{}", i);
}
|
ABC problem | #include <stdio.h>
#include <ctype.h>
int can_make_words(char **b, char *word)
{
int i, ret = 0, c = toupper(*word);
#define SWAP(a, b) if (a != b) { char * tmp = a; a = b; b = tmp; }
if (!c) return 1;
if (!b[0]) return 0;
for (i = 0; b[i] && !ret; i++) {
if (b[i][0] != c && b[i][1] != c) continue;
SWAP(b[i], b[0]);
ret = can_make_words(b + 1, word + 1);
SWAP(b[i], b[0]);
}
return ret;
}
int main(void)
{
char* blocks[] = {
"BO", "XK", "DQ", "CP", "NA",
"GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB",
"ER", "FS", "LY", "PC", "ZM",
0 };
char *words[] = {
"", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse", 0
};
char **w;
for (w = words; *w; w++)
printf("%s\t%d\n", *w, can_make_words(blocks, *w));
return 0;
}
| use std::iter::repeat;
fn rec_can_make_word(index: usize, word: &str, blocks: &[&str], used: &mut[bool]) -> bool {
let c = word.chars().nth(index).unwrap().to_uppercase().next().unwrap();
for i in 0..blocks.len() {
if !used[i] && blocks[i].chars().any(|s| s == c) {
used[i] = true;
if index == 0 || rec_can_make_word(index - 1, word, blocks, used) {
return true;
}
used[i] = false;
}
}
false
}
fn can_make_word(word: &str, blocks: &[&str]) -> bool {
return rec_can_make_word(word.chars().count() - 1, word, blocks,
&mut repeat(false).take(blocks.len()).collect::<Vec<_>>());
}
fn main() {
let blocks = [("BO"), ("XK"), ("DQ"), ("CP"), ("NA"), ("GT"), ("RE"), ("TG"), ("QD"), ("FS"),
("JW"), ("HU"), ("VI"), ("AN"), ("OB"), ("ER"), ("FS"), ("LY"), ("PC"), ("ZM")];
let words = ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"];
for word in &words {
println!("{} -> {}", word, can_make_word(word, &blocks))
}
}
|
AKS test for primes | #include <stdio.h>
#include <stdlib.h>
long long c[100];
void coef(int n)
{
int i, j;
if (n < 0 || n > 63) abort();
for (c[i=0] = 1; i < n; c[0] = -c[0], i++)
for (c[1 + (j=i)] = 1; j > 0; j--)
c[j] = c[j-1] - c[j];
}
int is_prime(int n)
{
int i;
coef(n);
c[0] += 1, c[i=n] -= 1;
while (i-- && !(c[i] % n));
return i < 0;
}
void show(int n)
{
do printf("%+lldx^%d", c[n], n); while (n--);
}
int main(void)
{
int n;
for (n = 0; n < 10; n++) {
coef(n);
printf("(x-1)^%d = ", n);
show(n);
putchar('\n');
}
printf("\nprimes (never mind the 1):");
for (n = 1; n <= 63; n++)
if (is_prime(n))
printf(" %d", n);
putchar('\n');
return 0;
}
| fn aks_coefficients(k: usize) -> Vec<i64> {
let mut coefficients = vec![0i64; k + 1];
coefficients[0] = 1;
for i in 1..(k + 1) {
coefficients[i] = -(1..i).fold(coefficients[0], |prev, j|{
let old = coefficients[j];
coefficients[j] = old - prev;
old
});
}
coefficients
}
fn is_prime(p: usize) -> bool {
if p < 2 {
false
} else {
let c = aks_coefficients(p);
(1..p / 2 + 1).all(|i| c[i] % p as i64 == 0)
}
}
fn main() {
for i in 0..8 {
println!("{}: {:?}", i, aks_coefficients(i));
}
for i in (1..=50).filter(|&i| is_prime(i)) {
print!("{} ", i);
}
}
|
Abstract type | #ifndef INTERFACE_ABS
#define INTERFACE_ABS
typedef struct sAbstractCls *AbsCls;
typedef struct sAbstractMethods {
int (*method1)(AbsCls c, int a);
const char *(*method2)(AbsCls c, int b);
void (*method3)(AbsCls c, double d);
} *AbstractMethods, sAbsMethods;
struct sAbstractCls {
AbstractMethods klass;
void *instData;
};
#define ABSTRACT_METHODS( cName, m1, m2, m3 ) \
static sAbsMethods cName ## _Iface = { &m1, &m2, &m3 }; \
AbsCls cName ## _Instance( void *clInst) { \
AbsCls ac = malloc(sizeof(struct sAbstractCls)); \
if (ac) { \
ac->klass = &cName ## _Iface; \
ac->instData = clInst; \
}\
return ac; }
#define Abs_Method1( c, a) (c)->klass->method1(c, a)
#define Abs_Method2( c, b) (c)->klass->method2(c, b)
#define Abs_Method3( c, d) (c)->klass->method3(c, d)
#define Abs_Free(c) \
do { if (c) { free((c)->instData); free(c); } } while(0);
#endif
| trait Shape {
fn area(self) -> i32;
}
|
Abundant odd numbers | #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
| fn divisors(n: u64) -> Vec<u64> {
let mut divs = vec![1];
let mut divs2 = Vec::new();
for i in (2..).take_while(|x| x * x <= n).filter(|x| n % x == 0) {
divs.push(i);
let j = n / i;
if i != j {
divs2.push(j);
}
}
divs.extend(divs2.iter().rev());
divs
}
fn sum_string(v: Vec<u64>) -> String {
v[1..]
.iter()
.fold(format!("{}", v[0]), |s, i| format!("{} + {}", s, i))
}
fn abundant_odd(search_from: u64, count_from: u64, count_to: u64, print_one: bool) -> u64 {
let mut count = count_from;
for n in (search_from..).step_by(2) {
let divs = divisors(n);
let total: u64 = divs.iter().sum();
if total > n {
count += 1;
let s = sum_string(divs);
if !print_one {
println!("{}. {} < {} = {}", count, n, s, total);
} else if count == count_to {
println!("{} < {} = {}", n, s, total);
}
}
if count == count_to {
break;
}
}
count_to
}
fn main() {
let max = 25;
println!("The first {} abundant odd numbers are:", max);
let n = abundant_odd(1, 0, max, false);
println!("The one thousandth abundant odd number is:");
abundant_odd(n, 25, 1000, true);
println!("The first abundant odd number above one billion is:");
abundant_odd(1e9 as u64 + 1, 0, 1, true);
}
|
Abundant, deficient and perfect number classifications | #include<stdio.h>
#define de 0
#define pe 1
#define ab 2
int main(){
int sum = 0, i, j;
int try_max = 0;
int count_list[3] = {1,0,0};
for(i=2; i <= 20000; i++){
try_max = i/2;
sum = 1;
for(j=2; j<try_max; j++){
if (i % j)
continue;
try_max = i/j;
sum += j;
if (j != try_max)
sum += try_max;
}
if (sum < i){
count_list[de]++;
continue;
}
if (sum > i){
count_list[ab]++;
continue;
}
count_list[pe]++;
}
printf("\nThere are %d deficient," ,count_list[de]);
printf(" %d perfect," ,count_list[pe]);
printf(" %d abundant numbers between 1 and 20000.\n" ,count_list[ab]);
return 0;
}
| fn main() {
let (mut abundant, mut deficient, mut perfect) = (0u32, 1u32, 0u32);
for i in 1..20_001 {
if let Some(divisors) = i.proper_divisors() {
let sum: u64 = divisors.iter().sum();
if sum < i {
deficient += 1
} else if sum > i {
abundant += 1
} else {
perfect += 1
}
}
}
println!("deficient:\t{:5}\nperfect:\t{:5}\nabundant:\t{:5}",
deficient, perfect, abundant);
}
|
Accumulator factory | #include <stdio.h>
#define ACCUMULATOR(name,n) __typeof__(n) name (__typeof__(n) i) { \
static __typeof__(n) _n=n; LOGIC; }
#define LOGIC return _n+=i
ACCUMULATOR(x,1.0)
ACCUMULATOR(y,3)
ACCUMULATOR(z,'a')
#undef LOGIC
int main (void) {
printf ("%f\n", x(5));
printf ("%f\n", x(2.3));
printf ("%i\n", y(5.0));
printf ("%i\n", y(3.3));
printf ("%c\n", z(5));
return 0;
}
|
use std::ops::Add;
fn foo<Num>(n: Num) -> impl FnMut(Num) -> Num
where Num: Add<Output=Num> + Copy + 'static {
let mut acc = n;
move |i: Num| {
acc = acc + i;
acc
}
}
fn main() {
let mut x = foo(1.);
x(5.);
foo(3.);
println!("{}", x(2.3));
}
|
Ackermann function | #include <stdio.h>
int ackermann(int m, int n)
{
if (!m) return n + 1;
if (!n) return ackermann(m - 1, 1);
return ackermann(m - 1, ackermann(m, n - 1));
}
int main()
{
int m, n;
for (m = 0; m <= 4; m++)
for (n = 0; n < 6 - m; n++)
printf("A(%d, %d) = %d\n", m, n, ackermann(m, n));
return 0;
}
| fn ack(m: isize, n: isize) -> isize {
if m == 0 {
n + 1
} else if n == 0 {
ack(m - 1, 1)
} else {
ack(m - 1, ack(m, n - 1))
}
}
fn main() {
let a = ack(3, 4);
println!("{}", a);
}
|
Active object | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <sys/time.h>
#include <pthread.h>
typedef struct {
double (*func)(double);
struct timeval start;
double v, last_v, last_t;
pthread_t id;
} integ_t, *integ;
void update(integ x)
{
struct timeval tv;
double t, v, (*f)(double);
f = x->func;
gettimeofday(&tv, 0);
t = ((tv.tv_sec - x->start.tv_sec) * 1000000
+ tv.tv_usec - x->start.tv_usec) * 1e-6;
v = f ? f(t) : 0;
x->v += (x->last_v + v) * (t - x->last_t) / 2;
x->last_t = t;
}
void* tick(void *a)
{
integ x = a;
while (1) {
usleep(100000);
update(x);
}
}
void set_input(integ x, double (*func)(double))
{
update(x);
x->func = func;
x->last_t = 0;
x->last_v = func ? func(0) : 0;
}
integ new_integ(double (*func)(double))
{
integ x = malloc(sizeof(integ_t));
x->v = x->last_v = 0;
x->func = 0;
gettimeofday(&x->start, 0);
set_input(x, func);
pthread_create(&x->id, 0, tick, x);
return x;
}
double sine(double t) { return sin(4 * atan2(1, 1) * t); }
int main()
{
integ x = new_integ(sine);
sleep(2);
set_input(x, 0);
usleep(500000);
printf("%g\n", x->v);
return 0;
}
| #![feature(mpsc_select)]
extern crate num;
extern crate schedule_recv;
use num::traits::Zero;
use num::Float;
use schedule_recv::periodic_ms;
use std::f64::consts::PI;
use std::ops::Mul;
use std::sync::mpsc::{self, SendError, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
pub type Actor<S> = Sender<Box<Fn(u32) -> S + Send>>;
pub type ActorResult<S> = Result<(), SendError<Box<Fn(u32) -> S + Send>>>;
pub struct Integrator<S: 'static, T: Send> {
input: Actor<S>,
output: Arc<Mutex<T>>,
}
impl<S, T> Integrator<S, T>
where
S: Mul<f64, Output = T> + Float + Zero,
T: 'static + Clone + Send + Float,
{
pub fn new(frequency: u32) -> Integrator<S, T> {
let (tx, input) = mpsc::channel();
let s: Arc<Mutex<T>> = Arc::new(Mutex::new(Zero::zero()));
let integrator = Integrator {
input: tx,
output: Arc::clone(&s),
};
thread::spawn(move || -> () {
let periodic = periodic_ms(frequency);
let mut t = 0;
let mut k: Box<Fn(u32) -> S + Send> = Box::new(|_| Zero::zero());
let mut k_0: S = Zero::zero();
loop {
select! {
res = periodic.recv() => match res {
Ok(_) => {
t += frequency;
let k_1: S = k(t);
let mut s = s.lock().unwrap();
*s = *s + (k_1 + k_0) * (f64::from(frequency) / 2.);
k_0 = k_1;
}
Err(_) => break,
},
res = input.recv() => match res {
Ok(k_new) => k = k_new,
Err(_) => break,
}
}
}
});
integrator
}
pub fn input(&self, k: Box<Fn(u32) -> S + Send>) -> ActorResult<S> {
self.input.send(k)
}
pub fn output(&self) -> T {
*self.output.lock().unwrap()
}
}
fn integrate() -> f64 {
let object = Integrator::new(10);
object
.input(Box::new(|t: u32| {
let two_seconds_ms = 2 * 1000;
let f = 1. / f64::from(two_seconds_ms);
(2. * PI * f * f64::from(t)).sin()
}))
.expect("Failed to set input");
thread::sleep(Duration::from_secs(2));
object.input(Box::new(|_| 0.)).expect("Failed to set input");
thread::sleep(Duration::from_millis(500));
object.output()
}
fn main() {
println!("{}", integrate());
}
#[test]
#[ignore]
fn solution() {
let object = Integrator::new(10);
object
.input(Box::new(|t: u32| {
let two_seconds_ms = 2 * 1000;
let f = 1. / (two_seconds_ms / 10) as f64;
(2. * PI * f * t as f64).sin()
}))
.expect("Failed to set input");
thread::sleep(Duration::from_millis(200));
object.input(Box::new(|_| 0.)).expect("Failed to set input");
thread::sleep(Duration::from_millis(100));
assert_eq!(object.output() as u32, 0)
}
|
Almost prime | #include <stdio.h>
int kprime(int n, int k)
{
int p, f = 0;
for (p = 2; f < k && p*p <= n; p++)
while (0 == n % p)
n /= p, f++;
return f + (n > 1) == k;
}
int main(void)
{
int i, c, k;
for (k = 1; k <= 5; k++) {
printf("k = %d:", k);
for (i = 2, c = 0; c < 10; i++)
if (kprime(i, k)) {
printf(" %d", i);
c++;
}
putchar('\n');
}
return 0;
}
| fn is_kprime(n: u32, k: u32) -> bool {
let mut primes = 0;
let mut f = 2;
let mut rem = n;
while primes < k && rem > 1{
while (rem % f) == 0 && rem > 1{
rem /= f;
primes += 1;
}
f += 1;
}
rem == 1 && primes == k
}
struct KPrimeGen {
k: u32,
n: u32,
}
impl Iterator for KPrimeGen {
type Item = u32;
fn next(&mut self) -> Option<u32> {
self.n += 1;
while !is_kprime(self.n, self.k) {
self.n += 1;
}
Some(self.n)
}
}
fn kprime_generator(k: u32) -> KPrimeGen {
KPrimeGen {k: k, n: 1}
}
fn main() {
for k in 1..6 {
println!("{}: {:?}", k, kprime_generator(k).take(10).collect::<Vec<_>>());
}
}
|
Amb | typedef const char * amb_t;
amb_t amb(size_t argc, ...)
{
amb_t *choices;
va_list ap;
int i;
if(argc) {
choices = malloc(argc*sizeof(amb_t));
va_start(ap, argc);
i = 0;
do { choices[i] = va_arg(ap, amb_t); } while(++i < argc);
va_end(ap);
i = 0;
do { TRY(choices[i]); } while(++i < argc);
free(choices);
}
FAIL;
}
int joins(const char *left, const char *right) { return left[strlen(left)-1] == right[0]; }
int _main() {
const char *w1,*w2,*w3,*w4;
w1 = amb(3, "the", "that", "a");
w2 = amb(3, "frog", "elephant", "thing");
w3 = amb(3, "walked", "treaded", "grows");
w4 = amb(2, "slowly", "quickly");
if(!joins(w1, w2)) amb(0);
if(!joins(w2, w3)) amb(0);
if(!joins(w3, w4)) amb(0);
printf("%s %s %s %s\n", w1, w2, w3, w4);
return EXIT_SUCCESS;
}
| use std::ops::Add;
struct Amb<'a> {
list: Vec<Vec<&'a str>>,
}
fn main() {
let amb = Amb {
list: vec![
vec!["the", "that", "a"],
vec!["frog", "elephant", "thing"],
vec!["walked", "treaded", "grows"],
vec!["slowly", "quickly"],
],
};
match amb.do_amb(0, 0 as char) {
Some(text) => println!("{}", text),
None => println!("Nothing found"),
}
}
impl<'a> Amb<'a> {
fn do_amb(&self, level: usize, last_char: char) -> Option<String> {
if self.list.is_empty() {
panic!("No word list");
}
if self.list.len() <= level {
return Some(String::new());
}
let mut res = String::new();
let word_list = &self.list[level];
for word in word_list {
if word.chars().next().unwrap() == last_char || last_char == 0 as char {
res = res.add(word).add(" ");
let answ = self.do_amb(level + 1, word.chars().last().unwrap());
match answ {
Some(x) => {
res = res.add(&x);
return Some(res);
}
None => res.clear(),
}
}
}
None
}
}
|
Amicable pairs | #include <stdio.h>
#include <stdlib.h>
typedef unsigned int uint;
int main(int argc, char **argv)
{
uint top = atoi(argv[1]);
uint *divsum = malloc((top + 1) * sizeof(*divsum));
uint pows[32] = {1, 0};
for (uint i = 0; i <= top; i++) divsum[i] = 1;
for (uint p = 2; p+p <= top; p++) {
if (divsum[p] > 1) {
divsum[p] -= p;
continue;}
uint x;
for (x = 1; pows[x - 1] <= top/p; x++)
pows[x] = p*pows[x - 1];
uint k= p-1;
for (uint n = p+p; n <= top; n += p) {
uint s=1+pows[1];
k--;
if ( k==0) {
for (uint i = 2; i < x && !(n%pows[i]); s += pows[i++]);
k = p; }
divsum[n] *= s;
}
}
for (uint p = (top >> 1)+1; p <= top; p++) {
if (divsum[p] > 1){
divsum[p] -= p;}
}
uint cnt = 0;
for (uint a = 1; a <= top; a++) {
uint b = divsum[a];
if (b > a && b <= top && divsum[b] == a){
printf("%u %u\n", a, b);
cnt++;}
}
printf("\nTop %u count : %u\n",top,cnt);
return 0;
}
| fn sum_of_divisors(val: u32) -> u32 {
(1..val/2+1).filter(|n| val % n == 0)
.fold(0, |sum, n| sum + n)
}
fn main() {
let iter = (1..20_000).map(|i| (i, sum_of_divisors(i)))
.filter(|&(i, div_sum)| i > div_sum);
for (i, sum1) in iter {
if sum_of_divisors(sum1) == i {
println!("{} {}", i, sum1);
}
}
}
|
Anagrams | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
char *sortedWord(const char *word, char *wbuf)
{
char *p1, *p2, *endwrd;
char t;
int swaps;
strcpy(wbuf, word);
endwrd = wbuf+strlen(wbuf);
do {
swaps = 0;
p1 = wbuf; p2 = endwrd-1;
while (p1<p2) {
if (*p2 > *p1) {
t = *p2; *p2 = *p1; *p1 = t;
swaps = 1;
}
p1++; p2--;
}
p1 = wbuf; p2 = p1+1;
while(p2 < endwrd) {
if (*p2 > *p1) {
t = *p2; *p2 = *p1; *p1 = t;
swaps = 1;
}
p1++; p2++;
}
} while (swaps);
return wbuf;
}
static
short cxmap[] = {
0x06, 0x1f, 0x4d, 0x0c, 0x5c, 0x28, 0x5d, 0x0e, 0x09, 0x33, 0x31, 0x56,
0x52, 0x19, 0x29, 0x53, 0x32, 0x48, 0x35, 0x55, 0x5e, 0x14, 0x27, 0x24,
0x02, 0x3e, 0x18, 0x4a, 0x3f, 0x4c, 0x45, 0x30, 0x08, 0x2c, 0x1a, 0x03,
0x0b, 0x0d, 0x4f, 0x07, 0x20, 0x1d, 0x51, 0x3b, 0x11, 0x58, 0x00, 0x49,
0x15, 0x2d, 0x41, 0x17, 0x5f, 0x39, 0x16, 0x42, 0x37, 0x22, 0x1c, 0x0f,
0x43, 0x5b, 0x46, 0x4b, 0x0a, 0x26, 0x2e, 0x40, 0x12, 0x21, 0x3c, 0x36,
0x38, 0x1e, 0x01, 0x1b, 0x05, 0x4e, 0x44, 0x3d, 0x04, 0x10, 0x5a, 0x2a,
0x23, 0x34, 0x25, 0x2f, 0x2b, 0x50, 0x3a, 0x54, 0x47, 0x59, 0x13, 0x57,
};
#define CXMAP_SIZE (sizeof(cxmap)/sizeof(short))
int Str_Hash( const char *key, int ix_max )
{
const char *cp;
short mash;
int hash = 33501551;
for (cp = key; *cp; cp++) {
mash = cxmap[*cp % CXMAP_SIZE];
hash = (hash >>4) ^ 0x5C5CF5C ^ ((hash<<1) + (mash<<5));
hash &= 0x3FFFFFFF;
}
return hash % ix_max;
}
typedef struct sDictWord *DictWord;
struct sDictWord {
const char *word;
DictWord next;
};
typedef struct sHashEntry *HashEntry;
struct sHashEntry {
const char *key;
HashEntry next;
DictWord words;
HashEntry link;
short wordCount;
};
#define HT_SIZE 8192
HashEntry hashTable[HT_SIZE];
HashEntry mostPerms = NULL;
int buildAnagrams( FILE *fin )
{
char buffer[40];
char bufr2[40];
char *hkey;
int hix;
HashEntry he, *hep;
DictWord we;
int maxPC = 2;
int numWords = 0;
while ( fgets(buffer, 40, fin)) {
for(hkey = buffer; *hkey && (*hkey!='\n'); hkey++);
*hkey = 0;
hkey = sortedWord(buffer, bufr2);
hix = Str_Hash(hkey, HT_SIZE);
he = hashTable[hix]; hep = &hashTable[hix];
while( he && strcmp(he->key , hkey) ) {
hep = &he->next;
he = he->next;
}
if ( ! he ) {
he = malloc(sizeof(struct sHashEntry));
he->next = NULL;
he->key = strdup(hkey);
he->wordCount = 0;
he->words = NULL;
he->link = NULL;
*hep = he;
}
we = malloc(sizeof(struct sDictWord));
we->word = strdup(buffer);
we->next = he->words;
he->words = we;
he->wordCount++;
if ( maxPC < he->wordCount) {
maxPC = he->wordCount;
mostPerms = he;
he->link = NULL;
}
else if (maxPC == he->wordCount) {
he->link = mostPerms;
mostPerms = he;
}
numWords++;
}
printf("%d words in dictionary max ana=%d\n", numWords, maxPC);
return maxPC;
}
int main( )
{
HashEntry he;
DictWord we;
FILE *f1;
f1 = fopen("unixdict.txt","r");
buildAnagrams(f1);
fclose(f1);
f1 = fopen("anaout.txt","w");
for (he = mostPerms; he; he = he->link) {
fprintf(f1,"%d:", he->wordCount);
for(we = he->words; we; we = we->next) {
fprintf(f1,"%s, ", we->word);
}
fprintf(f1, "\n");
}
fclose(f1);
return 0;
}
| use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead,BufReader};
use std::borrow::ToOwned;
extern crate unicode_segmentation;
use unicode_segmentation::{UnicodeSegmentation};
fn main () {
let file = BufReader::new(File::open("unixdict.txt").unwrap());
let mut map = HashMap::new();
for line in file.lines() {
let s = line.unwrap();
let mut sorted = s.trim().graphemes(true).map(ToOwned::to_owned).collect::<Vec<_>>();
sorted.sort();
map.entry(sorted).or_insert_with(Vec::new).push(s);
}
if let Some(max_len) = map.values().map(|v| v.len()).max() {
for anagram in map.values().filter(|v| v.len() == max_len) {
for word in anagram {
print!("{} ", word);
}
println!();
}
}
}
|
Anagrams_Deranged anagrams | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
const char *freq = "zqxjkvbpygfwmucldrhsnioate";
int char_to_idx[128];
struct word {
const char *w;
struct word *next;
};
union node {
union node *down[10];
struct word *list[10];
};
int deranged(const char *s1, const char *s2)
{
int i;
for (i = 0; s1[i]; i++)
if (s1[i] == s2[i]) return 0;
return 1;
}
int count_letters(const char *s, unsigned char *c)
{
int i, len;
memset(c, 0, 26);
for (len = i = 0; s[i]; i++) {
if (s[i] < 'a' || s[i] > 'z')
return 0;
len++, c[char_to_idx[(unsigned char)s[i]]]++;
}
return len;
}
const char * insert(union node *root, const char *s, unsigned char *cnt)
{
int i;
union node *n;
struct word *v, *w = 0;
for (i = 0; i < 25; i++, root = n) {
if (!(n = root->down[cnt[i]]))
root->down[cnt[i]] = n = calloc(1, sizeof(union node));
}
w = malloc(sizeof(struct word));
w->w = s;
w->next = root->list[cnt[25]];
root->list[cnt[25]] = w;
for (v = w->next; v; v = v->next) {
if (deranged(w->w, v->w))
return v->w;
}
return 0;
}
int main(int c, char **v)
{
int i, j = 0;
char *words;
struct stat st;
int fd = open(c < 2 ? "unixdict.txt" : v[1], O_RDONLY);
if (fstat(fd, &st) < 0) return 1;
words = malloc(st.st_size);
read(fd, words, st.st_size);
close(fd);
union node root = {{0}};
unsigned char cnt[26];
int best_len = 0;
const char *b1, *b2;
for (i = 0; freq[i]; i++)
char_to_idx[(unsigned char)freq[i]] = i;
for (i = j = 0; i < st.st_size; i++) {
if (words[i] != '\n') continue;
words[i] = '\0';
if (i - j > best_len) {
count_letters(words + j, cnt);
const char *match = insert(&root, words + j, cnt);
if (match) {
best_len = i - j;
b1 = words + j;
b2 = match;
}
}
j = ++i;
}
if (best_len) printf("longest derangement: %s %s\n", b1, b2);
return 0;
}
|
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fs::File;
use std::io;
use std::io::BufReader;
use std::io::BufRead;
use std::usize::MAX;
pub fn get_words() -> Result<Vec<String>, io::Error> {
let mut words = vec!();
let f = File::open("data/unixdict.txt")?;
let reader = BufReader::new(&f);
for line in reader.lines() {
words.push(line?)
}
Ok(words)
}
pub fn longest_deranged(v: &mut Vec<String>) -> Option<(String,String)>{
v.sort_by(|s1, s2| {
let mut c = s2.len().cmp(&s1.len());
if c == Ordering::Equal {
c = s1.cmp(s2);
}
c
});
let mut signatures : HashMap<Vec<char>, Vec<&String>> = HashMap::new();
let mut previous_length = MAX;
for s in v {
if s.len()<previous_length {
signatures.clear();
previous_length = s.len();
}
let mut sorted_chars = s.chars().collect::<Vec<char>>();
sorted_chars.sort();
let anagrams = signatures.entry(sorted_chars).or_insert(vec!());
if let Some(a) = anagrams.iter().filter(|anagram| is_deranged(anagram, s)).next(){
return Some(((*a).clone(), s.clone()));
}
anagrams.push(s);
}
None
}
pub fn is_deranged(s1: &String, s2: &String) -> bool {
s1.chars().zip(s2.chars()).filter(|(a,b)| a == b).next().is_none()
}
fn main() {
let r = get_words();
match r {
Ok(mut v) => {
let od = longest_deranged(&mut v);
match od {
None => println!("No deranged anagrams found!"),
Some((s1,s2)) => println!("{} {}",s1,s2),
}
},
Err(e) => panic!("Could not read words: {}",e)
}
}
|
Angle difference between two bearings | #include<stdlib.h>
#include<stdio.h>
#include<math.h>
void processFile(char* name){
int i,records;
double diff,b1,b2;
FILE* fp = fopen(name,"r");
fscanf(fp,"%d\n",&records);
for(i=0;i<records;i++){
fscanf(fp,"%lf%lf",&b1,&b2);
diff = fmod(b2-b1,360.0);
printf("\nDifference between b2(%lf) and b1(%lf) is %lf",b2,b1,(diff<-180)?diff+360:((diff>=180)?diff-360:diff));
}
fclose(fp);
}
int main(int argC,char* argV[])
{
double diff;
if(argC < 2)
printf("Usage : %s <bearings separated by a space OR full file name which contains the bearing list>",argV[0]);
else if(argC == 2)
processFile(argV[1]);
else{
diff = fmod(atof(argV[2])-atof(argV[1]),360.0);
printf("Difference between b2(%s) and b1(%s) is %lf",argV[2],argV[1],(diff<-180)?diff+360:((diff>=180)?diff-360:diff));
}
return 0;
}
|
pub fn angle_difference(bearing1: f64, bearing2: f64) -> f64 {
let diff = (bearing2 - bearing1) % 360.0;
if diff < -180.0 {
360.0 + diff
} else if diff > 180.0 {
-360.0 + diff
} else {
diff
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_angle_difference() {
assert_eq!(25.00, angle_difference(20.00, 45.00));
assert_eq!(90.00, angle_difference(-45.00, 45.00));
assert_eq!(175.00, angle_difference(-85.00, 90.00));
assert_eq!(-175.00, angle_difference(-95.00, 90.00));
assert_eq!(170.00, angle_difference(-45.00, 125.00));
assert_eq!(-170.00, angle_difference(-45.00, 145.00));
approx_eq(-118.1184, angle_difference(29.4803, -88.6381));
approx_eq(-80.7109, angle_difference(-78.3251 , -159.036));
approx_eq(-139.5832, angle_difference(-70099.74233810938, 29840.67437876723));
approx_eq(-72.3439, angle_difference(-165313.6666297357, 33693.9894517456));
approx_eq(-161.5029, angle_difference(1174.8380510598456, -154146.66490124757));
approx_eq(37.2988, angle_difference(60175.77306795546, 42213.07192354373));
}
fn approx_eq(f1: f64, f2: f64) {
assert!((f2-f1).abs() < 0.0001, "{} != {}", f1, f2)
}
}
|
Animate a pendulum | #include <stdlib.h>
#include <math.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <sys/time.h>
#define length 5
#define g 9.8
double alpha, accl, omega = 0, E;
struct timeval tv;
double elappsed() {
struct timeval now;
gettimeofday(&now, 0);
int ret = (now.tv_sec - tv.tv_sec) * 1000000
+ now.tv_usec - tv.tv_usec;
tv = now;
return ret / 1.e6;
}
void resize(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glOrtho(0, w, h, 0, -1, 1);
}
void render()
{
double x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);
resize(640, 320);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINES);
glVertex2d(320, 0);
glVertex2d(x, y);
glEnd();
glFlush();
double us = elappsed();
alpha += (omega + us * accl / 2) * us;
omega += accl * us;
if (length * g * (1 - cos(alpha)) >= E) {
alpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);
omega = 0;
}
accl = -g / length * sin(alpha);
}
void init_gfx(int *c, char **v)
{
glutInit(c, v);
glutInitDisplayMode(GLUT_RGB);
glutInitWindowSize(640, 320);
glutIdleFunc(render);
glutCreateWindow("Pendulum");
}
int main(int c, char **v)
{
alpha = 4 * atan2(1, 1) / 2.1;
E = length * g * (1 - cos(alpha));
accl = -g / length * sin(alpha);
omega = 0;
gettimeofday(&tv, 0);
init_gfx(&c, v);
glutMainLoop();
return 0;
}
|
use piston_window::{clear, ellipse, line_from_to, PistonWindow, WindowSettings};
const PI: f64 = std::f64::consts::PI;
const WIDTH: u32 = 640;
const HEIGHT: u32 = 480;
const ANCHOR_X: f64 = WIDTH as f64 / 2. - 12.;
const ANCHOR_Y: f64 = HEIGHT as f64 / 4.;
const ANCHOR_ELLIPSE: [f64; 4] = [ANCHOR_X - 3., ANCHOR_Y - 3., 6., 6.];
const ROPE_ORIGIN: [f64; 2] = [ANCHOR_X, ANCHOR_Y];
const ROPE_LENGTH: f64 = 200.;
const ROPE_THICKNESS: f64 = 1.;
const DELTA: f64 = 0.05;
const STANDARD_GRAVITY_VALUE: f64 = -9.81;
const BLACK: [f32; 4] = [0., 0., 0., 1.];
const RED: [f32; 4] = [1., 0., 0., 1.];
const GOLD: [f32; 4] = [216. / 255., 204. / 255., 36. / 255., 1.0];
fn main() {
let mut window: PistonWindow = WindowSettings::new("Pendulum", [WIDTH, HEIGHT])
.exit_on_esc(true)
.build()
.unwrap();
let mut angle = PI / 2.;
let mut angular_vel = 0.;
while let Some(event) = window.next() {
let (angle_sin, angle_cos) = angle.sin_cos();
let ball_x = ANCHOR_X + angle_sin * ROPE_LENGTH;
let ball_y = ANCHOR_Y + angle_cos * ROPE_LENGTH;
let angle_accel = STANDARD_GRAVITY_VALUE / ROPE_LENGTH * angle_sin;
angular_vel += angle_accel * DELTA;
angle += angular_vel * DELTA;
let rope_end = [ball_x, ball_y];
let ball_ellipse = [ball_x - 7., ball_y - 7., 14., 14.];
window.draw_2d(&event, |context, graphics, _device| {
clear([1.0; 4], graphics);
line_from_to(
BLACK,
ROPE_THICKNESS,
ROPE_ORIGIN,
rope_end,
context.transform,
graphics,
);
ellipse(RED, ANCHOR_ELLIPSE, context.transform, graphics);
ellipse(GOLD, ball_ellipse, context.transform, graphics);
});
}
}
|
Animation | #include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
const gchar *hello = "Hello World! ";
gint direction = -1;
gint cx=0;
gint slen=0;
GtkLabel *label;
void change_dir(GtkLayout *o, gpointer d)
{
direction = -direction;
}
gchar *rotateby(const gchar *t, gint q, gint l)
{
gint i, cl = l, j;
gchar *r = malloc(l+1);
for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)
r[j] = t[i];
r[l] = 0;
return r;
}
gboolean scroll_it(gpointer data)
{
if ( direction > 0 )
cx = (cx + 1) % slen;
else
cx = (cx + slen - 1 ) % slen;
gchar *scrolled = rotateby(hello, cx, slen);
gtk_label_set_text(label, scrolled);
free(scrolled);
return TRUE;
}
int main(int argc, char **argv)
{
GtkWidget *win;
GtkButton *button;
PangoFontDescription *pd;
gtk_init(&argc, &argv);
win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(win), "Basic Animation");
g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL);
label = (GtkLabel *)gtk_label_new(hello);
pd = pango_font_description_new();
pango_font_description_set_family(pd, "monospace");
gtk_widget_modify_font(GTK_WIDGET(label), pd);
button = (GtkButton *)gtk_button_new();
gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));
gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));
g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL);
slen = strlen(hello);
g_timeout_add(125, scroll_it, NULL);
gtk_widget_show_all(GTK_WIDGET(win));
gtk_main();
return 0;
}
| #[cfg(feature = "gtk")]
mod graphical {
extern crate gtk;
use self::gtk::traits::*;
use self::gtk::{Inhibit, Window, WindowType};
use std::ops::Not;
use std::sync::{Arc, RwLock};
pub fn create_window() {
gtk::init().expect("Failed to initialize GTK");
let window = Window::new(WindowType::Toplevel);
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
let button = gtk::Button::new_with_label("Hello World! ");
window.add(&button);
let lock = Arc::new(RwLock::new(false));
let lock_button = lock.clone();
button.connect_clicked(move |_| {
let mut reverse = lock_button.write().unwrap();
*reverse = reverse.not();
});
let lock_thread = lock.clone();
gtk::timeout_add(100, move || {
let reverse = lock_thread.read().unwrap();
let mut text = button.get_label().unwrap();
let len = &text.len();
if *reverse {
let begin = &text.split_off(1);
text.insert_str(0, begin);
} else {
let end = &text.split_off(len - 1);
text.insert_str(0, end);
}
button.set_label(&text);
gtk::Continue(true)
});
window.show_all();
gtk::main();
}
}
#[cfg(feature = "gtk")]
fn main() {
graphical::create_window();
}
#[cfg(not(feature = "gtk"))]
fn main() {}
|
Anonymous recursion | #include <stdio.h>
long fib(long x)
{
long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };
if (x < 0) {
printf("Bad argument: fib(%ld)\n", x);
return -1;
}
return fib_i(x);
}
long fib_i(long n)
{
printf("This is not the fib you are looking for\n");
return -1;
}
int main()
{
long x;
for (x = -1; x < 4; x ++)
printf("fib %ld = %ld\n", x, fib(x));
printf("calling fib_i from outside fib:\n");
fib_i(3);
return 0;
}
| fn fib(n: i64) -> Option<i64> {
fn actual_fib(n: i64) -> i64 {
if n < 2 {
n
} else {
actual_fib(n - 1) + actual_fib(n - 2)
}
}
if n < 0 {
None
} else {
Some(actual_fib(n))
}
}
fn main() {
println!("Fib(-1) = {:?}", fib(-1));
println!("Fib(0) = {:?}", fib(0));
println!("Fib(1) = {:?}", fib(1));
println!("Fib(2) = {:?}", fib(2));
println!("Fib(3) = {:?}", fib(3));
println!("Fib(4) = {:?}", fib(4));
println!("Fib(5) = {:?}", fib(5));
println!("Fib(10) = {:?}", fib(10));
}
#[test]
fn test_fib() {
assert_eq!(fib(0).unwrap(), 0);
assert_eq!(fib(1).unwrap(), 1);
assert_eq!(fib(2).unwrap(), 1);
assert_eq!(fib(3).unwrap(), 2);
assert_eq!(fib(4).unwrap(), 3);
assert_eq!(fib(5).unwrap(), 5);
assert_eq!(fib(10).unwrap(), 55);
}
#[test]
fn test_invalid_argument() {
assert_eq!(fib(-1), None);
}
|
Anti-primes | #include <stdio.h>
int countDivisors(int n) {
int i, count;
if (n < 2) return 1;
count = 2;
for (i = 2; i <= n/2; ++i) {
if (n%i == 0) ++count;
}
return count;
}
int main() {
int n, d, maxDiv = 0, count = 0;
printf("The first 20 anti-primes are:\n");
for (n = 1; count < 20; ++n) {
d = countDivisors(n);
if (d > maxDiv) {
printf("%d ", n);
maxDiv = d;
count++;
}
}
printf("\n");
return 0;
}
| fn count_divisors(n: u64) -> usize {
if n < 2 {
return 1;
}
2 + (2..=(n / 2)).filter(|i| n % i == 0).count()
}
fn main() {
println!("The first 20 anti-primes are:");
(1..)
.scan(0, |max, n| {
let d = count_divisors(n);
Some(if d > *max {
*max = d;
Some(n)
} else {
None
})
})
.flatten()
.take(20)
.for_each(|n| print!("{} ", n));
println!();
}
|
Append a record to the end of a text file | #include <stdio.h>
#include <string.h>
typedef const char *STRING;
typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t;
typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t;
#define GECOS_FMT "%s,%s,%s,%s,%s"
#define PASSWD_FMT "%s:%s:%d:%d:"GECOS_FMT":%s:%s"
passwd_t passwd_list[]={
{"jsmith", "x", 1001, 1000,
{"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "[email protected]"},
"/home/jsmith", "/bin/bash"},
{"jdoe", "x", 1002, 1000,
{"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "[email protected]"},
"/home/jdoe", "/bin/bash"}
};
main(){
FILE *passwd_text=fopen("passwd.txt", "w");
int rec_num;
for(rec_num=0; rec_num < sizeof passwd_list/sizeof(passwd_t); rec_num++)
fprintf(passwd_text, PASSWD_FMT"\n", passwd_list[rec_num]);
fclose(passwd_text);
passwd_text=fopen("passwd.txt", "a+");
char passwd_buf[BUFSIZ];
passwd_t new_rec =
{"xyz", "x", 1003, 1000,
{"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "[email protected]"},
"/home/xyz", "/bin/bash"};
sprintf(passwd_buf, PASSWD_FMT"\n", new_rec);
write(fileno(passwd_text), passwd_buf, strlen(passwd_buf));
close(passwd_text);
passwd_text=fopen("passwd.txt", "r");
while(!feof(passwd_text))
fscanf(passwd_text, "%[^\n]\n", passwd_buf, "\n");
if(strstr(passwd_buf, "xyz"))
printf("Appended record: %s\n", passwd_buf);
}
| use std::fs::File;
use std::fs::OpenOptions;
use std::io::BufRead;
use std::io::BufReader;
use std::io::BufWriter;
use std::io::Result;
use std::io::Write;
use std::path::Path;
#[derive(Eq, PartialEq, Debug)]
pub struct PasswordRecord {
pub account: String,
pub password: String,
pub uid: u64,
pub gid: u64,
pub gecos: Vec<String>,
pub directory: String,
pub shell: String,
}
impl PasswordRecord {
pub fn new(
account: &str,
password: &str,
uid: u64,
gid: u64,
gecos: Vec<&str>,
directory: &str,
shell: &str,
) -> PasswordRecord {
PasswordRecord {
account: account.to_string(),
password: password.to_string(),
uid,
gid,
gecos: gecos.iter().map(|s| s.to_string()).collect(),
directory: directory.to_string(),
shell: shell.to_string(),
}
}
pub fn to_line(&self) -> String {
let gecos = self.gecos.join(",");
format!(
"{}:{}:{}:{}:{}:{}:{}",
self.account, self.password, self.uid, self.gid, gecos, self.directory, self.shell
)
}
pub fn from_line(line: &str) -> PasswordRecord {
let sp: Vec<&str> = line.split(":").collect();
if sp.len() < 7 {
panic!("Less than 7 fields found");
} else {
let uid = sp[2].parse().expect("Cannot parse uid");
let gid = sp[3].parse().expect("Cannot parse gid");
let gecos = sp[4].split(",").collect();
PasswordRecord::new(sp[0], sp[1], uid, gid, gecos, sp[5], sp[6])
}
}
}
pub fn read_password_file(file_name: &str) -> Result<Vec<PasswordRecord>> {
let p = Path::new(file_name);
if !p.exists() {
Ok(vec![])
} else {
let f = OpenOptions::new().read(true).open(p)?;
Ok(BufReader::new(&f)
.lines()
.map(|l| PasswordRecord::from_line(&l.unwrap()))
.collect())
}
}
pub fn overwrite_password_file(file_name: &str, recs: &Vec<PasswordRecord>) -> Result<()> {
let f = OpenOptions::new()
.create(true)
.write(true)
.open(file_name)?;
write_records(f, recs)
}
pub fn append_password_file(file_name: &str, recs: &Vec<PasswordRecord>) -> Result<()> {
let f = OpenOptions::new()
.create(true)
.append(true)
.open(file_name)?;
write_records(f, recs)
}
fn write_records(f: File, recs: &Vec<PasswordRecord>) -> Result<()> {
let mut writer = BufWriter::new(f);
for rec in recs {
write!(writer, "{}\n", rec.to_line())?;
}
Ok(())
}
fn main(){
let recs1 = vec![
PasswordRecord::new(
"jsmith",
"x",
1001,
1000,
vec![
"Joe Smith",
"Room 1007",
"(234)555-8917",
"(234)555-0077",
"[email protected]",
],
"/home/jsmith",
"/bin/bash",
),
PasswordRecord::new(
"jdoe",
"x",
1002,
1000,
vec![
"Jane Doe",
"Room 1004",
"(234)555-8914",
"(234)555-0044",
"[email protected]",
],
"/home/jdoe",
"/bin/bash",
),
];
overwrite_password_file("passwd", &recs1).expect("cannot write file");
let recs2 = read_password_file("passwd").expect("cannot read file");
println!("Original file:");
for r in recs2 {
println!("{}",r.to_line());
}
let append0 = vec![PasswordRecord::new(
"xyz",
"x",
1003,
1000,
vec![
"X Yz",
"Room 1003",
"(234)555-8913",
"(234)555-0033",
"[email protected]",
],
"/home/xyz",
"/bin/bash",
)];
append_password_file("passwd", &append0).expect("cannot append to file");
let recs2 = read_password_file("passwd").expect("cannot read file");
println!("");
println!("Appended file:");
for r in recs2 {
println!("{}",r.to_line());
}
}
|
Apply a callback to an array | #ifndef CALLBACK_H
#define CALLBACK_H
void map(int* array, int len, void(*callback)(int,int));
#endif
| fn echo(n: &i32) {
println!("{}", n);
}
fn main() {
let a: [i32; 5];
a = [1, 2, 3, 4, 5];
let _: Vec<_> = a.into_iter().map(echo).collect();
}
|
Apply a digital filter (direct form II transposed) | #include<stdlib.h>
#include<string.h>
#include<stdio.h>
#define MAX_LEN 1000
typedef struct{
float* values;
int size;
}vector;
vector extractVector(char* str){
vector coeff;
int i=0,count = 1;
char* token;
while(str[i]!=00){
if(str[i++]==' ')
count++;
}
coeff.values = (float*)malloc(count*sizeof(float));
coeff.size = count;
token = strtok(str," ");
i = 0;
while(token!=NULL){
coeff.values[i++] = atof(token);
token = strtok(NULL," ");
}
return coeff;
}
vector processSignalFile(char* fileName){
int i,j;
float sum;
char str[MAX_LEN];
vector coeff1,coeff2,signal,filteredSignal;
FILE* fp = fopen(fileName,"r");
fgets(str,MAX_LEN,fp);
coeff1 = extractVector(str);
fgets(str,MAX_LEN,fp);
coeff2 = extractVector(str);
fgets(str,MAX_LEN,fp);
signal = extractVector(str);
fclose(fp);
filteredSignal.values = (float*)calloc(signal.size,sizeof(float));
filteredSignal.size = signal.size;
for(i=0;i<signal.size;i++){
sum = 0;
for(j=0;j<coeff2.size;j++){
if(i-j>=0)
sum += coeff2.values[j]*signal.values[i-j];
}
for(j=0;j<coeff1.size;j++){
if(i-j>=0)
sum -= coeff1.values[j]*filteredSignal.values[i-j];
}
sum /= coeff1.values[0];
filteredSignal.values[i] = sum;
}
return filteredSignal;
}
void printVector(vector v, char* outputFile){
int i;
if(outputFile==NULL){
printf("[");
for(i=0;i<v.size;i++)
printf("%.12f, ",v.values[i]);
printf("\b\b]");
}
else{
FILE* fp = fopen(outputFile,"w");
for(i=0;i<v.size-1;i++)
fprintf(fp,"%.12f, ",v.values[i]);
fprintf(fp,"%.12f",v.values[i]);
fclose(fp);
}
}
int main(int argC,char* argV[])
{
char *str;
if(argC<2||argC>3)
printf("Usage : %s <name of signal data file and optional output file.>",argV[0]);
else{
if(argC!=2){
str = (char*)malloc((strlen(argV[2]) + strlen(str) + 1)*sizeof(char));
strcpy(str,"written to ");
}
printf("Filtered signal %s",(argC==2)?"is:\n":strcat(str,argV[2]));
printVector(processSignalFile(argV[1]),argV[2]);
}
return 0;
}
| use std::cmp::Ordering;
struct IIRFilter<'f>(&'f [f32], &'f [f32]);
impl<'f> IIRFilter<'f> {
pub fn with_coefficients(a: &'f [f32], b: &'f [f32]) -> IIRFilter<'f> {
IIRFilter(a, b)
}
pub fn apply<I: Iterator<Item = &'f f32> + 'f>(
&self,
samples: I,
) -> impl Iterator<Item = f32> + 'f {
let a_coeff = self.0;
let b_coeff = self.1;
let mut prev_results = Vec::<f32>::new();
let mut prev_samples = Vec::<f32>::new();
samples.enumerate()
.map(move |(i, sample)| {
prev_samples.push(*sample);
prev_results.push(0f32);
let sum_b: f32 = b_coeff.iter()
.enumerate()
.map(|(j, c)| {
if i >= j {
(*c) * prev_samples[i-j]
} else {
0f32
}
})
.sum();
let sum_a: f32 = a_coeff.iter()
.enumerate()
.map(|(j, c)| {
if i >= j {
(*c) * prev_results[i-j]
} else {
0f32
}
})
.sum();
let result = (sum_b - sum_a) / a_coeff[0];
prev_results[i] = result;
result
}
)
}
}
fn main() {
let a: &[f32] = &[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17];
let b: &[f32] = &[0.16666667, 0.5, 0.5, 0.16666667];
let samples: Vec<f32> = vec![
-0.917843918645,
0.141984778794,
1.20536903482,
0.190286794412,
-0.662370894973,
-1.00700480494,
-0.404707073677,
0.800482325044,
0.743500089861,
1.01090520172,
0.741527555207,
0.277841675195,
0.400833448236,
-0.2085993586,
-0.172842103641,
-0.134316096293,
0.0259303398477,
0.490105989562,
0.549391221511,
0.9047198589,
];
for (i, result) in IIRFilter::with_coefficients(a, b)
.apply(samples.iter())
.enumerate()
{
print!("{:.8}", result);
if (i + 1) % 5 != 0 {
print!(", ");
} else {
println!();
}
}
println!();
}
|
Approximate equality | #include <math.h>
#include <stdbool.h>
#include <stdio.h>
bool approxEquals(double value, double other, double epsilon) {
return fabs(value - other) < epsilon;
}
void test(double a, double b) {
double epsilon = 1e-18;
printf("%f, %f => %d\n", a, b, approxEquals(a, b, epsilon));
}
int main() {
test(100000000000000.01, 100000000000000.011);
test(100.01, 100.011);
test(10000000000000.001 / 10000.0, 1000000000.0000001000);
test(0.001, 0.0010000001);
test(0.000000000000000000000101, 0.0);
test(sqrt(2.0) * sqrt(2.0), 2.0);
test(-sqrt(2.0) * sqrt(2.0), -2.0);
test(3.14159265358979323846, 3.14159265358979324);
return 0;
}
|
fn isclose(a: f64, b: f64, epsilon: f64) -> bool {
(a - b).abs() <= a.abs().max(b.abs()) * epsilon
}
fn main() {
fn sqrt(x: f64) -> f64 { x.sqrt() }
macro_rules! test {
($a: expr, $b: expr) => {
let operator = if isclose($a, $b, 1.0e-9) { '≈' } else { '≉' };
println!("{:>28} {} {}", stringify!($a), operator, stringify!($b))
}
}
test!(100000000000000.01, 100000000000000.011);
test!(100.01, 100.011);
test!(10000000000000.001/10000.0, 1000000000.0000001000);
test!(0.001, 0.0010000001);
test!(0.000000000000000000000101, 0.0);
test!( sqrt(2.0) * sqrt(2.0), 2.0);
test!(-sqrt(2.0) * sqrt(2.0), -2.0);
test!(3.14159265358979323846, 3.14159265358979324);
}
|
Arbitrary-precision integers (included) | #include <gmp.h>
#include <stdio.h>
#include <string.h>
int main()
{
mpz_t a;
mpz_init_set_ui(a, 5);
mpz_pow_ui(a, a, 1 << 18);
int len = mpz_sizeinbase(a, 10);
printf("GMP says size is: %d\n", len);
char *s = mpz_get_str(0, 10, a);
printf("size really is %d\n", len = strlen(s));
printf("Digits: %.20s...%s\n", s, s + len - 20);
return 0;
}
| extern crate num;
use num::bigint::BigUint;
use num::FromPrimitive;
use num::pow::pow;
fn main() {
let big = BigUint::from_u8(5).unwrap();
let answer_as_string = format!("{}", pow(big,pow(4,pow(3,2))));
let first_twenty: String = answer_as_string.chars().take(20).collect();
let last_twenty_reversed: Vec<char> = answer_as_string.chars().rev().take(20).collect();
let last_twenty: String = last_twenty_reversed.into_iter().rev().collect();
println!("Number of digits: {}", answer_as_string.len());
println!("First and last digits: {:?}..{:?}", first_twenty, last_twenty);
}
|
Archimedean spiral | #include <jambo.h>
Main
Set break
a=1.5, b=1.5, r=0, origen x=200, origen y=105
total = 0, Let ( total := Mul(20, M_PI) )
Cls
Loop for ( t=0, var 't' Is less equal to 'total', Let (t := Add (t, 0.005)) )
#( r = a + b * t )
Set 'origen x, origen y', # ( 200 + (2*r*sin(t)) ) » 'origen x', #( 105 + (r*cos(t)) ) » 'origen y',
Gosub 'Dibuja un segmento'
Next
Pause
End
Subrutines
Define (Dibuja un segmento, x1, y1, x2, y2)
dx=0, dy=0, paso=0, i=0, DX=0, DY=0
Sub(x2, x1), Sub (y2, y1), Move to ' dx, dy '
Let( paso := Get if( Greater equal ( Abs(dx) » (DX), Abs(dy)»(DY) ), DX, DY ) )
Div(dx, paso), Div(dy, paso), Move to ( dx, dy )
Color back (13)
i = 0
Loop if ( Less equal (i, paso) )
Locate( y1, x1 ), Printnl( " " )
Add ( x1, dx), Add( y1, dy ), Move to ( x1, y1 )
++i
Back
Printnl("\OFF")
Return
| #[macro_use(px)]
extern crate bmp;
use bmp::{Image, Pixel};
use std::f64;
fn main() {
let width = 600u32;
let half_width = (width / 2) as i32;
let mut img = Image::new(width, width);
let draw_color = px!(255, 128, 128);
let a = 1.0_f64;
let b = 9.0_f64;
let max_angle = 5.0_f64 * 2.0_f64 * f64::consts::PI;
let mut theta = 0.0_f64;
while theta < max_angle {
theta = theta + 0.002_f64;
let r = a + b * theta;
let x = (r * theta.cos()) as i32 + half_width;
let y = (r * theta.sin()) as i32 + half_width;
img.set_pixel(x as u32, y as u32, draw_color);
}
let _ = img.save("archimedean_spiral.bmp").unwrap_or_else(|e| panic!("Failed to save: {}", e));
}
|
Arithmetic-geometric mean | #include<math.h>
#include<stdio.h>
#include<stdlib.h>
double agm( double a, double g ) {
double iota = 1.0E-16;
double a1, g1;
if( a*g < 0.0 ) {
printf( "arithmetic-geometric mean undefined when x*y<0\n" );
exit(1);
}
while( fabs(a-g)>iota ) {
a1 = (a + g) / 2.0;
g1 = sqrt(a * g);
a = a1;
g = g1;
}
return a;
}
int main( void ) {
double x, y;
printf( "Enter two numbers: " );
scanf( "%lf%lf", &x, &y );
printf( "The arithmetic-geometric mean is %lf\n", agm(x, y) );
return 0;
}
|
fn main () {
let mut args = std::env::args();
let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap();
let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap();
let result = agm(x,y);
println!("The arithmetic-geometric mean is {}", result);
}
fn agm (x: f32, y: f32) -> f32 {
let e: f32 = 0.000001;
let mut a = x;
let mut g = y;
let mut a1: f32;
let mut g1: f32;
if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); }
else {
loop {
a1 = (a + g) / 2.;
g1 = (a * g).sqrt();
a = a1;
g = g1;
if (a - g).abs() < e { return a; }
}
}
}
|
Arithmetic_Complex | #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
c = a + b;
printf("\na+b="); cprint(c);
c = a * b;
printf("\na*b="); cprint(c);
c = 1.0 / a;
printf("\n1/c="); cprint(c);
c = -a;
printf("\n-a="); cprint(c);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}
| extern crate num;
use num::complex::Complex;
fn main() {
let a = Complex {re:-4.0, im: 5.0};
let b = Complex::new(1.0, 1.0);
println!(" a = {}", a);
println!(" b = {}", b);
println!(" a + b = {}", a + b);
println!(" a * b = {}", a * b);
println!(" 1 / a = {}", a.inv());
println!(" -a = {}", -a);
println!("conj(a) = {}", a.conj());
}
|
Arithmetic_Integer | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int a, b;
if (argc < 3) exit(1);
b = atoi(argv[--argc]);
if (b == 0) exit(2);
a = atoi(argv[--argc]);
printf("a+b = %d\n", a+b);
printf("a-b = %d\n", a-b);
printf("a*b = %d\n", a*b);
printf("a/b = %d\n", a/b);
printf("a%%b = %d\n", a%b);
return 0;
}
| use std::env;
fn main() {
let args: Vec<_> = env::args().collect();
let a = args[1].parse::<i32>().unwrap();
let b = args[2].parse::<i32>().unwrap();
println!("sum: {}", a + b);
println!("difference: {}", a - b);
println!("product: {}", a * b);
println!("integer quotient: {}", a / b);
println!("remainder: {}", a % b);
}
|
Arithmetic_Rational | #include <stdio.h>
#include <stdlib.h>
#define FMT "%lld"
typedef long long int fr_int_t;
typedef struct { fr_int_t num, den; } frac;
fr_int_t gcd(fr_int_t m, fr_int_t n)
{
fr_int_t t;
while (n) { t = n; n = m % n; m = t; }
return m;
}
frac frac_new(fr_int_t num, fr_int_t den)
{
frac a;
if (!den) {
printf("divide by zero: "FMT"/"FMT"\n", num, den);
abort();
}
int g = gcd(num, den);
if (g) { num /= g; den /= g; }
else { num = 0; den = 1; }
if (den < 0) {
den = -den;
num = -num;
}
a.num = num; a.den = den;
return a;
}
#define BINOP(op, n, d) frac frac_##op(frac a, frac b) { return frac_new(n,d); }
BINOP(add, a.num * b.den + b.num * a.den, a.den * b.den);
BINOP(sub, a.num * b.den - b.num + a.den, a.den * b.den);
BINOP(mul, a.num * b.num, a.den * b.den);
BINOP(div, a.num * b.den, a.den * b.num);
int frac_cmp(frac a, frac b) {
int l = a.num * b.den, r = a.den * b.num;
return l < r ? -1 : l > r;
}
#define frac_cmp_int(a, b) frac_cmp(a, frac_new(b, 1))
int frtoi(frac a) { return a.den / a.num; }
double frtod(frac a) { return (double)a.den / a.num; }
int main()
{
int n, k;
frac sum, kf;
for (n = 2; n < 1<<19; n++) {
sum = frac_new(1, n);
for (k = 2; k * k < n; k++) {
if (n % k) continue;
kf = frac_new(1, k);
sum = frac_add(sum, kf);
kf = frac_new(1, n / k);
sum = frac_add(sum, kf);
}
if (frac_cmp_int(sum, 1) == 0) printf("%d\n", n);
}
return 0;
}
| use std::cmp::Ordering;
use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Neg};
fn gcd(a: i64, b: i64) -> i64 {
match b {
0 => a,
_ => gcd(b, a % b),
}
}
fn lcm(a: i64, b: i64) -> i64 {
a / gcd(a, b) * b
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord)]
pub struct Rational {
numerator: i64,
denominator: i64,
}
impl Rational {
fn new(numerator: i64, denominator: i64) -> Self {
let divisor = gcd(numerator, denominator);
Rational {
numerator: numerator / divisor,
denominator: denominator / divisor,
}
}
}
impl Add for Rational {
type Output = Self;
fn add(self, other: Self) -> Self {
let multiplier = lcm(self.denominator, other.denominator);
Rational::new(self.numerator * multiplier / self.denominator +
other.numerator * multiplier / other.denominator,
multiplier)
}
}
impl AddAssign for Rational {
fn add_assign(&mut self, other: Self) {
*self = *self + other;
}
}
impl Sub for Rational {
type Output = Self;
fn sub(self, other: Self) -> Self {
self + -other
}
}
impl SubAssign for Rational {
fn sub_assign(&mut self, other: Self) {
*self = *self - other;
}
}
impl Mul for Rational {
type Output = Self;
fn mul(self, other: Self) -> Self {
Rational::new(self.numerator * other.numerator,
self.denominator * other.denominator)
}
}
impl MulAssign for Rational {
fn mul_assign(&mut self, other: Self) {
*self = *self * other;
}
}
impl Div for Rational {
type Output = Self;
fn div(self, other: Self) -> Self {
self *
Rational {
numerator: other.denominator,
denominator: other.numerator,
}
}
}
impl DivAssign for Rational {
fn div_assign(&mut self, other: Self) {
*self = *self / other;
}
}
impl Neg for Rational {
type Output = Self;
fn neg(self) -> Self {
Rational {
numerator: -self.numerator,
denominator: self.denominator,
}
}
}
impl PartialOrd for Rational {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
(self.numerator * other.denominator).partial_cmp(&(self.denominator * other.numerator))
}
}
impl<T: Into<i64>> From<T> for Rational {
fn from(value: T) -> Self {
Rational::new(value.into(), 1)
}
}
fn main() {
let max = 1 << 19;
for candidate in 2..max {
let mut sum = Rational::new(1, candidate);
for factor in 2..(candidate as f64).sqrt().ceil() as i64 {
if candidate % factor == 0 {
sum += Rational::new(1, factor);
sum += Rational::new(1, candidate / factor);
}
}
if sum == 1.into() {
println!("{} is perfect", candidate);
}
}
}
|
Array concatenation | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \
(TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));
void *array_concat(const void *a, size_t an,
const void *b, size_t bn, size_t s)
{
char *p = malloc(s * (an + bn));
memcpy(p, a, an*s);
memcpy(p + an*s, b, bn*s);
return p;
}
const int a[] = { 1, 2, 3, 4, 5 };
const int b[] = { 6, 7, 8, 9, 0 };
int main(void)
{
unsigned int i;
int *c = ARRAY_CONCAT(int, a, 5, b, 5);
for(i = 0; i < 10; i++)
printf("%d\n", c[i]);
free(c);
return EXIT_SUCCCESS;
}
| fn main() {
let a_vec = vec![1, 2, 3, 4, 5];
let b_vec = vec![6; 5];
let c_vec = concatenate_arrays(&a_vec, &b_vec);
println!("{:?} ~ {:?} => {:?}", a_vec, b_vec, c_vec);
}
fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> {
let mut concat = x.to_vec();
concat.extend_from_slice(y);
concat
}
|
Array length | #include <stdio.h>
int main()
{
const char *fruit[2] = { "apples", "oranges" };
int length = sizeof(fruit) / sizeof(fruit[0]);
printf("%d\n", length);
return 0;
}
| fn main() {
let array = ["foo", "bar", "baz", "biff"];
println!("the array has {} elements", array.len());
}
|
Arrays | char foo()
{
char array[5] = {3,6,9,12,15};
return array[2];
}
| let a = [1, 2, 3];
let mut m = [1, 2, 3];
let zeroes = [0; 200];
|
Assertions | #include <assert.h>
int main(){
int a;
assert(a == 42);
return 0;
}
| let x = 42;
assert!(x == 42);
assert_eq!(x, 42);
|
Atomic updates | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <time.h>
#include <pthread.h>
#define N_BUCKETS 15
pthread_mutex_t bucket_mutex[N_BUCKETS];
int buckets[N_BUCKETS];
pthread_t equalizer;
pthread_t randomizer;
void transfer_value(int from, int to, int howmuch)
{
bool swapped = false;
if ( (from == to) || ( howmuch < 0 ) ||
(from < 0 ) || (to < 0) || (from >= N_BUCKETS) || (to >= N_BUCKETS) ) return;
if ( from > to ) {
int temp1 = from;
from = to;
to = temp1;
swapped = true;
howmuch = -howmuch;
}
pthread_mutex_lock(&bucket_mutex[from]);
pthread_mutex_lock(&bucket_mutex[to]);
if ( howmuch > buckets[from] && !swapped )
howmuch = buckets[from];
if ( -howmuch > buckets[to] && swapped )
howmuch = -buckets[to];
buckets[from] -= howmuch;
buckets[to] += howmuch;
pthread_mutex_unlock(&bucket_mutex[from]);
pthread_mutex_unlock(&bucket_mutex[to]);
}
void print_buckets()
{
int i;
int sum=0;
for(i=0; i < N_BUCKETS; i++) pthread_mutex_lock(&bucket_mutex[i]);
for(i=0; i < N_BUCKETS; i++) {
printf("%3d ", buckets[i]);
sum += buckets[i];
}
printf("= %d\n", sum);
for(i=0; i < N_BUCKETS; i++) pthread_mutex_unlock(&bucket_mutex[i]);
}
void *equalizer_start(void *t)
{
for(;;) {
int b1 = rand()%N_BUCKETS;
int b2 = rand()%N_BUCKETS;
int diff = buckets[b1] - buckets[b2];
if ( diff < 0 )
transfer_value(b2, b1, -diff/2);
else
transfer_value(b1, b2, diff/2);
}
return NULL;
}
void *randomizer_start(void *t)
{
for(;;) {
int b1 = rand()%N_BUCKETS;
int b2 = rand()%N_BUCKETS;
int diff = rand()%(buckets[b1]+1);
transfer_value(b1, b2, diff);
}
return NULL;
}
int main()
{
int i, total=0;
for(i=0; i < N_BUCKETS; i++) pthread_mutex_init(&bucket_mutex[i], NULL);
for(i=0; i < N_BUCKETS; i++) {
buckets[i] = rand() % 100;
total += buckets[i];
printf("%3d ", buckets[i]);
}
printf("= %d\n", total);
pthread_create(&equalizer, NULL, equalizer_start, NULL);
pthread_create(&randomizer, NULL, randomizer_start, NULL);
for(;;) {
sleep(1);
print_buckets();
}
for(i=0; i < N_BUCKETS; i++) pthread_mutex_destroy(bucket_mutex+i);
return EXIT_SUCCESS;
}
| extern crate rand;
use std::sync::{Arc, Mutex};
use std::thread;
use std::cmp;
use std::time::Duration;
use rand::Rng;
use rand::distributions::{IndependentSample, Range};
trait Buckets {
fn equalize<R:Rng>(&mut self, rng: &mut R);
fn randomize<R:Rng>(&mut self, rng: &mut R);
fn print_state(&self);
}
impl Buckets for [i32] {
fn equalize<R:Rng>(&mut self, rng: &mut R) {
let range = Range::new(0,self.len()-1);
let src = range.ind_sample(rng);
let dst = range.ind_sample(rng);
if dst != src {
let amount = cmp::min(((dst + src) / 2) as i32, self[src]);
let multiplier = if amount >= 0 { -1 } else { 1 };
self[src] += amount * multiplier;
self[dst] -= amount * multiplier;
}
}
fn randomize<R:Rng>(&mut self, rng: &mut R) {
let ind_range = Range::new(0,self.len()-1);
let src = ind_range.ind_sample(rng);
let dst = ind_range.ind_sample(rng);
if dst != src {
let amount = cmp::min(Range::new(0,20).ind_sample(rng), self[src]);
self[src] -= amount;
self[dst] += amount;
}
}
fn print_state(&self) {
println!("{:?} = {}", self, self.iter().sum::<i32>());
}
}
fn main() {
let e_buckets = Arc::new(Mutex::new([10; 10]));
let r_buckets = e_buckets.clone();
let p_buckets = e_buckets.clone();
thread::spawn(move || {
let mut rng = rand::thread_rng();
loop {
let mut buckets = e_buckets.lock().unwrap();
buckets.equalize(&mut rng);
}
});
thread::spawn(move || {
let mut rng = rand::thread_rng();
loop {
let mut buckets = r_buckets.lock().unwrap();
buckets.randomize(&mut rng);
}
});
let sleep_time = Duration::new(1,0);
loop {
{
let buckets = p_buckets.lock().unwrap();
buckets.print_state();
}
thread::sleep(sleep_time);
}
}
|
Attractive numbers | #include <stdio.h>
#define TRUE 1
#define FALSE 0
#define MAX 120
typedef int bool;
bool is_prime(int n) {
int d = 5;
if (n < 2) return FALSE;
if (!(n % 2)) return n == 2;
if (!(n % 3)) return n == 3;
while (d *d <= n) {
if (!(n % d)) return FALSE;
d += 2;
if (!(n % d)) return FALSE;
d += 4;
}
return TRUE;
}
int count_prime_factors(int n) {
int count = 0, f = 2;
if (n == 1) return 0;
if (is_prime(n)) return 1;
while (TRUE) {
if (!(n % f)) {
count++;
n /= f;
if (n == 1) return count;
if (is_prime(n)) f = n;
}
else if (f >= 3) f += 2;
else f = 3;
}
}
int main() {
int i, n, count = 0;
printf("The attractive numbers up to and including %d are:\n", MAX);
for (i = 1; i <= MAX; ++i) {
n = count_prime_factors(i);
if (is_prime(n)) {
printf("%4d", i);
if (!(++count % 20)) printf("\n");
}
}
printf("\n");
return 0;
}
| use primal::Primes;
const MAX: u64 = 120;
fn extract_prime_factor(num: u64) -> Option<(u64, u64)> {
let mut i = 0;
if primal::is_prime(num) {
None
} else {
loop {
let prime = Primes::all().nth(i).unwrap() as u64;
if num % prime == 0 {
return Some((prime, num / prime));
} else {
i += 1;
}
}
}
}
fn factorize(num: u64) -> Vec<u64> {
let mut factorized = Vec::new();
let mut rest = num;
while let Some((prime, factorizable_rest)) = extract_prime_factor(rest) {
factorized.push(prime);
rest = factorizable_rest;
}
factorized.push(rest);
factorized
}
fn main() {
let mut output: Vec<u64> = Vec::new();
for num in 4 ..= MAX {
if primal::is_prime(factorize(num).len() as u64) {
output.push(num);
}
}
println!("The attractive numbers up to and including 120 are\n{:?}", output);
}
|
Average loop length | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define MAX_N 20
#define TIMES 1000000
double factorial(int n) {
double f = 1;
int i;
for (i = 1; i <= n; i++) f *= i;
return f;
}
double expected(int n) {
double sum = 0;
int i;
for (i = 1; i <= n; i++)
sum += factorial(n) / pow(n, i) / factorial(n - i);
return sum;
}
int randint(int n) {
int r, rmax = RAND_MAX / n * n;
while ((r = rand()) >= rmax);
return r / (RAND_MAX / n);
}
int test(int n, int times) {
int i, count = 0;
for (i = 0; i < times; i++) {
int x = 1, bits = 0;
while (!(bits & x)) {
count++;
bits |= x;
x = 1 << randint(n);
}
}
return count;
}
int main(void) {
srand(time(0));
puts(" n\tavg\texp.\tdiff\n-------------------------------");
int n;
for (n = 1; n <= MAX_N; n++) {
int cnt = test(n, TIMES);
double avg = (double)cnt / TIMES;
double theory = expected(n);
double diff = (avg / theory - 1) * 100;
printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff);
}
return 0;
}
| extern crate rand;
use rand::{ThreadRng, thread_rng};
use rand::distributions::{IndependentSample, Range};
use std::collections::HashSet;
use std::env;
use std::process;
fn help() {
println!("usage: average_loop_length <max_N> <trials>");
}
fn main() {
let args: Vec<String> = env::args().collect();
let mut max_n: u32 = 20;
let mut trials: u32 = 1000;
match args.len() {
1 => {}
3 => {
max_n = args[1].parse::<u32>().unwrap();
trials = args[2].parse::<u32>().unwrap();
}
_ => {
help();
process::exit(0);
}
}
let mut rng = thread_rng();
println!(" N average analytical (error)");
println!("=== ========= ============ =========");
for n in 1..(max_n + 1) {
let the_analytical = analytical(n);
let the_empirical = empirical(n, trials, &mut rng);
println!(" {:>2} {:3.4} {:3.4} ( {:>+1.2}%)",
n,
the_empirical,
the_analytical,
100f64 * (the_empirical / the_analytical - 1f64));
}
}
fn factorial(n: u32) -> f64 {
(1..n + 1).fold(1f64, |p, n| p * n as f64)
}
fn analytical(n: u32) -> f64 {
let sum: f64 = (1..(n + 1))
.map(|i| factorial(n) / (n as f64).powi(i as i32) / factorial(n - i))
.fold(0f64, |a, v| a + v);
sum
}
fn empirical(n: u32, trials: u32, rng: &mut ThreadRng) -> f64 {
let sum: f64 = (0..trials)
.map(|_t| {
let mut item = 1u32;
let mut seen = HashSet::new();
let range = Range::new(1u32, n + 1);
for step in 0..n {
if seen.contains(&item) {
return step as f64;
}
seen.insert(item);
item = range.ind_sample(rng);
}
n as f64
})
.fold(0f64, |a, v| a + v);
sum / trials as f64
}
|
Averages_Arithmetic mean | #include <stdio.h>
double mean(double *v, int len)
{
double sum = 0;
int i;
for (i = 0; i < len; i++)
sum += v[i];
return sum / len;
}
int main(void)
{
double v[] = {1, 2, 2.718, 3, 3.142};
int i, len;
for (len = 5; len >= 0; len--) {
printf("mean[");
for (i = 0; i < len; i++)
printf(i ? ", %g" : "%g", v[i]);
printf("] = %g\n", mean(v, len));
}
return 0;
}
| fn sum(arr: &[f64]) -> f64 {
arr.iter().fold(0.0, |p,&q| p + q)
}
fn mean(arr: &[f64]) -> f64 {
sum(arr) / arr.len() as f64
}
fn main() {
let v = &[2.0, 3.0, 5.0, 7.0, 13.0, 21.0, 33.0, 54.0];
println!("mean of {:?}: {:?}", v, mean(v));
let w = &[];
println!("mean of {:?}: {:?}", w, mean(w));
}
|
Averages_Mean angle | #include<math.h>
#include<stdio.h>
double
meanAngle (double *angles, int size)
{
double y_part = 0, x_part = 0;
int i;
for (i = 0; i < size; i++)
{
x_part += cos (angles[i] * M_PI / 180);
y_part += sin (angles[i] * M_PI / 180);
}
return atan2 (y_part / size, x_part / size) * 180 / M_PI;
}
int
main ()
{
double angleSet1[] = { 350, 10 };
double angleSet2[] = { 90, 180, 270, 360};
double angleSet3[] = { 10, 20, 30};
printf ("\nMean Angle for 1st set : %lf degrees", meanAngle (angleSet1, 2));
printf ("\nMean Angle for 2nd set : %lf degrees", meanAngle (angleSet2, 4));
printf ("\nMean Angle for 3rd set : %lf degrees\n", meanAngle (angleSet3, 3));
return 0;
}
| use std::f64;
fn mean_angle(angles: &[f64]) -> f64 {
let length: f64 = angles.len() as f64;
let cos_mean: f64 = angles.iter().fold(0.0, |sum, i| sum + i.to_radians().cos()) / length;
let sin_mean: f64 = angles.iter().fold(0.0, |sum, i| sum + i.to_radians().sin()) / length;
(sin_mean).atan2(cos_mean).to_degrees()
}
fn main() {
let angles1 = [350.0_f64, 10.0];
let angles2 = [90.0_f64, 180.0, 270.0, 360.0];
let angles3 = [10.0_f64, 20.0, 30.0];
println!("Mean Angle for {:?} is {:.5} degrees",
&angles1,
mean_angle(&angles1));
println!("Mean Angle for {:?} is {:.5} degrees",
&angles2,
mean_angle(&angles2));
println!("Mean Angle for {:?} is {:.5} degrees",
&angles3,
mean_angle(&angles3));
}
macro_rules! assert_diff{
($x: expr,$y : expr, $diff :expr)=>{
if ( $x - $y ).abs() > $diff {
panic!("floating point difference is to big {}", $x - $y );
}
}
}
#[test]
fn calculate() {
let angles1 = [350.0_f64, 10.0];
let angles2 = [90.0_f64, 180.0, 270.0, 360.0];
let angles3 = [10.0_f64, 20.0, 30.0];
assert_diff!(0.0, mean_angle(&angles1), 0.001);
assert_diff!(-90.0, mean_angle(&angles2), 0.001);
assert_diff!(20.0, mean_angle(&angles3), 0.001);
}
|
Averages_Mean time of day | #include<stdlib.h>
#include<math.h>
#include<stdio.h>
typedef struct
{
int hour, minute, second;
} digitime;
double
timeToDegrees (digitime time)
{
return (360 * time.hour / 24.0 + 360 * time.minute / (24 * 60.0) +
360 * time.second / (24 * 3600.0));
}
digitime
timeFromDegrees (double angle)
{
digitime d;
double totalSeconds = 24 * 60 * 60 * angle / 360;
d.second = (int) totalSeconds % 60;
d.minute = ((int) totalSeconds % 3600 - d.second) / 60;
d.hour = (int) totalSeconds / 3600;
return d;
}
double
meanAngle (double *angles, int size)
{
double y_part = 0, x_part = 0;
int i;
for (i = 0; i < size; i++)
{
x_part += cos (angles[i] * M_PI / 180);
y_part += sin (angles[i] * M_PI / 180);
}
return atan2 (y_part / size, x_part / size) * 180 / M_PI;
}
int
main ()
{
digitime *set, meanTime;
int inputs, i;
double *angleSet, angleMean;
printf ("Enter number of inputs : ");
scanf ("%d", &inputs);
set = malloc (inputs * sizeof (digitime));
angleSet = malloc (inputs * sizeof (double));
printf ("\n\nEnter the data separated by a space between each unit : ");
for (i = 0; i < inputs; i++)
{
scanf ("%d:%d:%d", &set[i].hour, &set[i].minute, &set[i].second);
angleSet[i] = timeToDegrees (set[i]);
}
meanTime = timeFromDegrees (360 + meanAngle (angleSet, inputs));
printf ("\n\nThe mean time is : %d:%d:%d", meanTime.hour, meanTime.minute,
meanTime.second);
return 0;
}
| use std::f64::consts::PI;
#[derive(Debug, PartialEq, Eq)]
struct Time {
h: u8,
m: u8,
s: u8,
}
impl Time {
fn from_radians(mut rads: f64) -> Time {
rads %= 2.0 * PI;
if rads < 0.0 {
rads += 2.0 * PI
}
Time {
h: (rads * 12.0 / PI) as u8,
m: ((rads * 720.0 / PI) % 60.0) as u8,
s: ((rads * 43200.0 / PI) % 60.0).round() as u8,
}
}
fn from_parts(h: u8, m: u8, s: u8) -> Result<Time, ()> {
if h > 23 || m > 59 || s > 59 {
return Err(());
}
Ok(Time { h, m, s })
}
fn as_radians(&self) -> f64 {
((self.h as f64 / 12.0) + (self.m as f64 / 720.0) + (self.s as f64 / 43200.0)) * PI
}
}
fn mean_time(times: &[Time]) -> Time {
let (ss, sc) = times
.iter()
.map(Time::as_radians)
.map(|a| (a.sin(), a.cos()))
.fold((0.0, 0.0), |(ss, sc), (s, c)| (ss + s, sc + c));
Time::from_radians(ss.atan2(sc))
}
fn main() {
let times = [
Time::from_parts(23, 00, 17).unwrap(),
Time::from_parts(23, 40, 20).unwrap(),
Time::from_parts(00, 12, 45).unwrap(),
Time::from_parts(00, 17, 19).unwrap(),
];
let mean = mean_time(×);
println!("{:02}:{:02}:{:02}", mean.h, mean.m, mean.s);
}
|
Averages_Median | #include <stdio.h>
#include <stdlib.h>
typedef struct floatList {
float *list;
int size;
} *FloatList;
int floatcmp( const void *a, const void *b) {
if (*(const float *)a < *(const float *)b) return -1;
else return *(const float *)a > *(const float *)b;
}
float median( FloatList fl )
{
qsort( fl->list, fl->size, sizeof(float), floatcmp);
return 0.5 * ( fl->list[fl->size/2] + fl->list[(fl->size-1)/2]);
}
int main()
{
static float floats1[] = { 5.1, 2.6, 6.2, 8.8, 4.6, 4.1 };
static struct floatList flist1 = { floats1, sizeof(floats1)/sizeof(float) };
static float floats2[] = { 5.1, 2.6, 8.8, 4.6, 4.1 };
static struct floatList flist2 = { floats2, sizeof(floats2)/sizeof(float) };
printf("flist1 median is %7.2f\n", median(&flist1));
printf("flist2 median is %7.2f\n", median(&flist2));
return 0;
}
| fn median(mut xs: Vec<f64>) -> f64 {
xs.sort_by(|x,y| x.partial_cmp(y).unwrap() );
let n = xs.len();
if n % 2 == 0 {
(xs[n/2] + xs[n/2 - 1]) / 2.0
} else {
xs[n/2]
}
}
fn main() {
let nums = vec![2.,3.,5.,0.,9.,82.,353.,32.,12.];
println!("{:?}", median(nums))
}
|
Averages_Mode | #include <stdio.h>
#include <stdlib.h>
typedef struct { double v; int c; } vcount;
int cmp_dbl(const void *a, const void *b)
{
double x = *(const double*)a - *(const double*)b;
return x < 0 ? -1 : x > 0;
}
int vc_cmp(const void *a, const void *b)
{
return ((const vcount*)b)->c - ((const vcount*)a)->c;
}
int get_mode(double* x, int len, vcount **list)
{
int i, j;
vcount *vc;
qsort(x, len, sizeof(double), cmp_dbl);
for (i = 0, j = 1; i < len - 1; i++, j += (x[i] != x[i + 1]));
*list = vc = malloc(sizeof(vcount) * j);
vc[0].v = x[0];
vc[0].c = 1;
for (i = j = 0; i < len - 1; i++, vc[j].c++)
if (x[i] != x[i + 1]) vc[++j].v = x[i + 1];
qsort(vc, j + 1, sizeof(vcount), vc_cmp);
for (i = 0; i <= j && vc[i].c == vc[0].c; i++);
return i;
}
int main()
{
double values[] = { 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 12, 12, 17 };
# define len sizeof(values)/sizeof(double)
vcount *vc;
int i, n_modes = get_mode(values, len, &vc);
printf("got %d modes:\n", n_modes);
for (i = 0; i < n_modes; i++)
printf("\tvalue = %g, count = %d\n", vc[i].v, vc[i].c);
free(vc);
return 0;
}
| use std::collections::HashMap;
fn main() {
let mode_vec1 = mode(vec![ 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]);
let mode_vec2 = mode(vec![ 1, 1, 2, 4, 4]);
println!("Mode of vec1 is: {:?}", mode_vec1);
println!("Mode of vec2 is: {:?}", mode_vec2);
assert!( mode_vec1 == [6], "Error in mode calculation");
assert!( (mode_vec2 == [1, 4]) || (mode_vec2 == [4,1]), "Error in mode calculation" );
}
fn mode(vs: Vec<i32>) -> Vec<i32> {
let mut vec_mode = Vec::new();
let mut seen_map = HashMap::new();
let mut max_val = 0;
for i in vs{
let ctr = seen_map.entry(i).or_insert(0);
*ctr += 1;
if *ctr > max_val{
max_val = *ctr;
}
}
for (key, val) in seen_map {
if val == max_val{
vec_mode.push(key);
}
}
vec_mode
}
|
Averages_Pythagorean means | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char* argv[])
{
int i, count=0;
double f, sum=0.0, prod=1.0, resum=0.0;
for (i=1; i<argc; ++i) {
f = atof(argv[i]);
count++;
sum += f;
prod *= f;
resum += (1.0/f);
}
printf("Arithmetic mean = %f\n",sum/count);
printf("Geometric mean = %f\n",pow(prod,(1.0/count)));
printf("Harmonic mean = %f\n",count/resum);
return 0;
}
| fn main() {
let mut sum = 0.0;
let mut prod = 1;
let mut recsum = 0.0;
for i in 1..11{
sum += i as f32;
prod *= i;
recsum += 1.0/(i as f32);
}
let avg = sum/10.0;
let gmean = (prod as f32).powf(0.1);
let hmean = 10.0/recsum;
println!("Average: {}, Geometric mean: {}, Harmonic mean: {}", avg, gmean, hmean);
assert!( ( (avg >= gmean) && (gmean >= hmean) ), "Incorrect calculation");
}
|
Averages_Root mean square | #include <stdio.h>
#include <math.h>
double rms(double *v, int n)
{
int i;
double sum = 0.0;
for(i = 0; i < n; i++)
sum += v[i] * v[i];
return sqrt(sum / n);
}
int main(void)
{
double v[] = {1., 2., 3., 4., 5., 6., 7., 8., 9., 10.};
printf("%f\n", rms(v, sizeof(v)/sizeof(double)));
return 0;
}
| fn root_mean_square(vec: Vec<i32>) -> f32 {
let sum_squares = vec.iter().fold(0, |acc, &x| acc + x.pow(2));
return ((sum_squares as f32)/(vec.len() as f32)).sqrt();
}
fn main() {
let vec = (1..11).collect();
println!("The root mean square is: {}", root_mean_square(vec));
}
|
Averages_Simple moving average | #include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
typedef struct sma_obj {
double sma;
double sum;
int period;
double *values;
int lv;
} sma_obj_t;
typedef union sma_result {
sma_obj_t *handle;
double sma;
double *values;
} sma_result_t;
enum Action { SMA_NEW, SMA_FREE, SMA_VALUES, SMA_ADD, SMA_MEAN };
sma_result_t sma(enum Action action, ...)
{
va_list vl;
sma_result_t r;
sma_obj_t *o;
double v;
va_start(vl, action);
switch(action) {
case SMA_NEW:
r.handle = malloc(sizeof(sma_obj_t));
r.handle->sma = 0.0;
r.handle->period = va_arg(vl, int);
r.handle->values = malloc(r.handle->period * sizeof(double));
r.handle->lv = 0;
r.handle->sum = 0.0;
break;
case SMA_FREE:
r.handle = va_arg(vl, sma_obj_t *);
free(r.handle->values);
free(r.handle);
r.handle = NULL;
break;
case SMA_VALUES:
o = va_arg(vl, sma_obj_t *);
r.values = o->values;
break;
case SMA_MEAN:
o = va_arg(vl, sma_obj_t *);
r.sma = o->sma;
break;
case SMA_ADD:
o = va_arg(vl, sma_obj_t *);
v = va_arg(vl, double);
if ( o->lv < o->period ) {
o->values[o->lv++] = v;
o->sum += v;
o->sma = o->sum / o->lv;
} else {
o->sum -= o->values[ o->lv % o->period];
o->sum += v;
o->sma = o->sum / o->period;
o->values[ o->lv % o->period ] = v; o->lv++;
}
r.sma = o->sma;
break;
}
va_end(vl);
return r;
}
| struct SimpleMovingAverage {
period: usize,
numbers: Vec<usize>
}
impl SimpleMovingAverage {
fn new(p: usize) -> SimpleMovingAverage {
SimpleMovingAverage {
period: p,
numbers: Vec::new()
}
}
fn add_number(&mut self, number: usize) -> f64 {
self.numbers.push(number);
if self.numbers.len() > self.period {
self.numbers.remove(0);
}
if self.numbers.is_empty() {
return 0f64;
}else {
let sum = self.numbers.iter().fold(0, |acc, x| acc+x);
return sum as f64 / self.numbers.len() as f64;
}
}
}
fn main() {
for period in [3, 5].iter() {
println!("Moving average with period {}", period);
let mut sma = SimpleMovingAverage::new(*period);
for i in [1, 2, 3, 4, 5, 5, 4, 3, 2, 1].iter() {
println!("Number: {} | Average: {}", i, sma.add_number(*i));
}
}
}
|
Babbage problem |
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main() {
int current = 0,
square;
while (((square=current*current) % 1000000 != 269696) && (square<INT_MAX)) {
current++;
}
if (square>+INT_MAX)
printf("Condition not satisfied before INT_MAX reached.");
else
printf ("The smallest number whose square ends in 269696 is %d\n", current);
return 0 ;
}
| fn main() {
let mut current = 0;
while (current * current) % 1_000_000 != 269_696 {
current += 1;
}
println!(
"The smallest number whose square ends in 269696 is {}",
current
);
}
|
Balanced brackets | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
int isBal(const char*s,int l){
signed c=0;
while(l--)
if(s[l]==']') ++c;
else if(s[l]=='[') if(--c<0) break;
return !c;
}
void shuffle(char*s,int h){
int x,t,i=h;
while(i--){
t=s[x=rand()%h];
s[x]=s[i];
s[i]=t;
}
}
void genSeq(char*s,int n){
if(n){
memset(s,'[',n);
memset(s+n,']',n);
shuffle(s,n*2);
}
s[n*2]=0;
}
void doSeq(int n){
char s[64];
const char *o="False";
genSeq(s,n);
if(isBal(s,n*2)) o="True";
printf("'%s': %s\n",s,o);
}
int main(){
int n=0;
while(n<9) doSeq(n++);
return 0;
}
| extern crate rand;
trait Balanced {
fn is_balanced(&self) -> bool;
}
impl<'a> Balanced for str {
fn is_balanced(&self) -> bool {
let mut count = 0;
for bracket in self.chars() {
let change = match bracket {
'[' => 1,
']' => -1,
_ => panic!("Strings should only contain brackets")
};
count += change;
if count < 0 { return false; }
}
count == 0
}
}
fn generate_brackets(num: usize) -> String {
use rand::random;
(0..num).map(|_| if random() { '[' } else { ']' }).collect()
}
fn main() {
for i in (0..10) {
let brackets = generate_brackets(i);
println!("{} {}", brackets, brackets.is_balanced())
}
}
|
Balanced ternary | #include <stdio.h>
#include <string.h>
void reverse(char *p) {
size_t len = strlen(p);
char *r = p + len - 1;
while (p < r) {
*p ^= *r;
*r ^= *p;
*p++ ^= *r--;
}
}
void to_bt(int n, char *b) {
static char d[] = { '0', '+', '-' };
static int v[] = { 0, 1, -1 };
char *ptr = b;
*ptr = 0;
while (n) {
int r = n % 3;
if (r < 0) {
r += 3;
}
*ptr = d[r];
*(++ptr) = 0;
n -= v[r];
n /= 3;
}
reverse(b);
}
int from_bt(const char *a) {
int n = 0;
while (*a != '\0') {
n *= 3;
if (*a == '+') {
n++;
} else if (*a == '-') {
n--;
}
a++;
}
return n;
}
char last_char(char *ptr) {
char c;
if (ptr == NULL || *ptr == '\0') {
return '\0';
}
while (*ptr != '\0') {
ptr++;
}
ptr--;
c = *ptr;
*ptr = 0;
return c;
}
void add(const char *b1, const char *b2, char *out) {
if (*b1 != '\0' && *b2 != '\0') {
char c1[16];
char c2[16];
char ob1[16];
char ob2[16];
char d[3] = { 0, 0, 0 };
char L1, L2;
strcpy(c1, b1);
strcpy(c2, b2);
L1 = last_char(c1);
L2 = last_char(c2);
if (L2 < L1) {
L2 ^= L1;
L1 ^= L2;
L2 ^= L1;
}
if (L1 == '-') {
if (L2 == '0') {
d[0] = '-';
}
if (L2 == '-') {
d[0] = '+';
d[1] = '-';
}
}
if (L1 == '+') {
if (L2 == '0') {
d[0] = '+';
}
if (L2 == '-') {
d[0] = '0';
}
if (L2 == '+') {
d[0] = '-';
d[1] = '+';
}
}
if (L1 == '0') {
if (L2 == '0') {
d[0] = '0';
}
}
add(c1, &d[1], ob1);
add(ob1, c2, ob2);
strcpy(out, ob2);
d[1] = 0;
strcat(out, d);
} else if (*b1 != '\0') {
strcpy(out, b1);
} else if (*b2 != '\0') {
strcpy(out, b2);
} else {
*out = '\0';
}
}
void unary_minus(const char *b, char *out) {
while (*b != '\0') {
if (*b == '-') {
*out++ = '+';
b++;
} else if (*b == '+') {
*out++ = '-';
b++;
} else {
*out++ = *b++;
}
}
*out = '\0';
}
void subtract(const char *b1, const char *b2, char *out) {
char buf[16];
unary_minus(b2, buf);
add(b1, buf, out);
}
void mult(const char *b1, const char *b2, char *out) {
char r[16] = "0";
char t[16];
char c1[16];
char c2[16];
char *ptr = c2;
strcpy(c1, b1);
strcpy(c2, b2);
reverse(c2);
while (*ptr != '\0') {
if (*ptr == '+') {
add(r, c1, t);
strcpy(r, t);
}
if (*ptr == '-') {
subtract(r, c1, t);
strcpy(r, t);
}
strcat(c1, "0");
ptr++;
}
ptr = r;
while (*ptr == '0') {
ptr++;
}
strcpy(out, ptr);
}
int main() {
const char *a = "+-0++0+";
char b[16];
const char *c = "+-++-";
char t[16];
char d[16];
to_bt(-436, b);
subtract(b, c, t);
mult(a, t, d);
printf(" a: %14s %10d\n", a, from_bt(a));
printf(" b: %14s %10d\n", b, from_bt(b));
printf(" c: %14s %10d\n", c, from_bt(c));
printf("a*(b-c): %14s %10d\n", d, from_bt(d));
return 0;
}
| use std::{
cmp::min,
convert::{TryFrom, TryInto},
fmt,
ops::{Add, Mul, Neg},
str::FromStr,
};
fn main() -> Result<(), &'static str> {
let a = BalancedTernary::from_str("+-0++0+")?;
let b = BalancedTernary::from(-436);
let c = BalancedTernary::from_str("+-++-")?;
println!("a = {} = {}", a, i128::try_from(a.clone())?);
println!("b = {} = {}", b, i128::try_from(b.clone())?);
println!("c = {} = {}", c, i128::try_from(c.clone())?);
let d = a * (b + -c);
println!("a * (b - c) = {} = {}", d, i128::try_from(d.clone())?);
let e = BalancedTernary::from_str(
"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++",
)?;
assert_eq!(i128::try_from(e).is_err(), true);
Ok(())
}
#[derive(Clone, Copy, PartialEq)]
enum Trit {
Zero,
Pos,
Neg,
}
impl TryFrom<char> for Trit {
type Error = &'static str;
fn try_from(value: char) -> Result<Self, Self::Error> {
match value {
'0' => Ok(Self::Zero),
'+' => Ok(Self::Pos),
'-' => Ok(Self::Neg),
_ => Err("Invalid character for balanced ternary"),
}
}
}
impl From<Trit> for char {
fn from(x: Trit) -> Self {
match x {
Trit::Zero => '0',
Trit::Pos => '+',
Trit::Neg => '-',
}
}
}
impl Add for Trit {
type Output = (Self, Self);
fn add(self, rhs: Self) -> Self::Output {
use Trit::{Neg, Pos, Zero};
match (self, rhs) {
(Zero, x) | (x, Zero) => (Zero, x),
(Pos, Neg) | (Neg, Pos) => (Zero, Zero),
(Pos, Pos) => (Pos, Neg),
(Neg, Neg) => (Neg, Pos),
}
}
}
impl Mul for Trit {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
use Trit::{Neg, Pos, Zero};
match (self, rhs) {
(Zero, _) | (_, Zero) => Zero,
(Pos, Pos) | (Neg, Neg) => Pos,
(Pos, Neg) | (Neg, Pos) => Neg,
}
}
}
impl Neg for Trit {
type Output = Self;
fn neg(self) -> Self::Output {
match self {
Trit::Zero => Trit::Zero,
Trit::Pos => Trit::Neg,
Trit::Neg => Trit::Pos,
}
}
}
#[derive(Clone)]
struct BalancedTernary(Vec<Trit>);
impl fmt::Display for BalancedTernary {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
self.0
.iter()
.rev()
.map(|&d| char::from(d))
.collect::<String>()
)
}
}
impl Add for BalancedTernary {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
use Trit::Zero;
fn trim(v: &mut Vec<Trit>) {
while let Some(last_elem) = v.pop() {
if last_elem != Zero {
v.push(last_elem);
break;
}
}
}
if rhs.0.is_empty() {
if self.0.is_empty() {
return BalancedTernary(vec![Zero]);
}
return self;
}
let length = min(self.0.len(), rhs.0.len());
let mut sum = Vec::new();
let mut carry = vec![Zero];
for i in 0..length {
let (carry_dig, digit) = self.0[i] + rhs.0[i];
sum.push(digit);
carry.push(carry_dig);
}
for i in length..self.0.len() {
sum.push(self.0[i]);
}
for i in length..rhs.0.len() {
sum.push(rhs.0[i]);
}
trim(&mut sum);
trim(&mut carry);
BalancedTernary(sum) + BalancedTernary(carry)
}
}
impl Mul for BalancedTernary {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
let mut results = Vec::with_capacity(rhs.0.len());
for i in 0..rhs.0.len() {
let mut digits = vec![Trit::Zero; i];
for j in 0..self.0.len() {
digits.push(self.0[j] * rhs.0[i]);
}
results.push(BalancedTernary(digits));
}
#[allow(clippy::suspicious_arithmetic_impl)]
results
.into_iter()
.fold(BalancedTernary(vec![Trit::Zero]), |acc, x| acc + x)
}
}
impl Neg for BalancedTernary {
type Output = Self;
fn neg(self) -> Self::Output {
BalancedTernary(self.0.iter().map(|&x| -x).collect())
}
}
impl FromStr for BalancedTernary {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.chars()
.rev()
.map(|c| c.try_into())
.collect::<Result<_, _>>()
.map(BalancedTernary)
}
}
impl From<i128> for BalancedTernary {
fn from(x: i128) -> Self {
let mut v = Vec::new();
let mut curr = x;
loop {
let rem = curr % 3;
match rem {
0 => v.push(Trit::Zero),
1 | -2 => v.push(Trit::Pos),
2 | -1 => v.push(Trit::Neg),
_ => unreachable!(),
}
let offset = (rem as f64 / 3.0).round() as i128;
curr = curr / 3 + offset;
if curr == 0 {
break;
}
}
BalancedTernary(v)
}
}
impl TryFrom<BalancedTernary> for i128 {
type Error = &'static str;
fn try_from(value: BalancedTernary) -> Result<Self, Self::Error> {
value
.0
.iter()
.enumerate()
.try_fold(0_i128, |acc, (i, character)| {
let size_err = "Balanced ternary string is too large to fit into 16 bytes";
let index: u32 = i.try_into().map_err(|_| size_err)?;
match character {
Trit::Zero => Ok(acc),
Trit::Pos => 3_i128
.checked_pow(index)
.and_then(|x| acc.checked_add(x))
.ok_or(size_err),
Trit::Neg => 3_i128
.checked_pow(index)
.and_then(|x| acc.checked_sub(x))
.ok_or(size_err),
}
})
}
}
|
Barnsley fern | #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
void barnsleyFern(int windowWidth, unsigned long iter){
double x0=0,y0=0,x1,y1;
int diceThrow;
time_t t;
srand((unsigned)time(&t));
while(iter>0){
diceThrow = rand()%100;
if(diceThrow==0){
x1 = 0;
y1 = 0.16*y0;
}
else if(diceThrow>=1 && diceThrow<=7){
x1 = -0.15*x0 + 0.28*y0;
y1 = 0.26*x0 + 0.24*y0 + 0.44;
}
else if(diceThrow>=8 && diceThrow<=15){
x1 = 0.2*x0 - 0.26*y0;
y1 = 0.23*x0 + 0.22*y0 + 1.6;
}
else{
x1 = 0.85*x0 + 0.04*y0;
y1 = -0.04*x0 + 0.85*y0 + 1.6;
}
putpixel(30*x1 + windowWidth/2.0,30*y1,GREEN);
x0 = x1;
y0 = y1;
iter--;
}
}
int main()
{
unsigned long num;
printf("Enter number of iterations : ");
scanf("%ld",&num);
initwindow(500,500,"Barnsley Fern");
barnsleyFern(500,num);
getch();
closegraph();
return 0;
}
| extern crate rand;
extern crate raster;
use rand::Rng;
fn main() {
let max_iterations = 200_000u32;
let height = 640i32;
let width = 640i32;
let mut rng = rand::thread_rng();
let mut image = raster::Image::blank(width, height);
raster::editor::fill(&mut image, raster::Color::white()).unwrap();
let mut x = 0.;
let mut y = 0.;
for _ in 0..max_iterations {
let r = rng.gen::<f32>();
let cx: f64;
let cy: f64;
if r <= 0.01 {
cx = 0f64;
cy = 0.16 * y as f64;
} else if r <= 0.08 {
cx = 0.2 * x as f64 - 0.26 * y as f64;
cy = 0.23 * x as f64 + 0.22 * y as f64 + 1.6;
} else if r <= 0.15 {
cx = -0.15 * x as f64 + 0.28 * y as f64;
cy = 0.26 * x as f64 + 0.26 * y as f64 + 0.44;
} else {
cx = 0.85 * x as f64 + 0.04 * y as f64;
cy = -0.04 * x as f64 + 0.85 * y as f64 + 1.6;
}
x = cx;
y = cy;
let _ = image.set_pixel(
((width as f64) / 2. + x * (width as f64) / 11.).round() as i32,
((height as f64) - y * (height as f64) / 11.).round() as i32,
raster::Color::rgb(50, 205, 50));
}
raster::save(&image, "fractal.png").unwrap();
}
|
Base64 decode data | #include <stdio.h>
#include <stdlib.h>
typedef unsigned char ubyte;
const ubyte BASE64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int findIndex(const ubyte val) {
if ('A' <= val && val <= 'Z') {
return val - 'A';
}
if ('a' <= val && val <= 'z') {
return val - 'a' + 26;
}
if ('0' <= val && val <= '9') {
return val - '0' + 52;
}
if (val == '+') {
return 62;
}
if (val == '/') {
return 63;
}
return -1;
}
int decode(const ubyte source[], ubyte sink[]) {
const size_t length = strlen(source);
const ubyte *it = source;
const ubyte *end = source + length;
int acc;
if (length % 4 != 0) {
return 1;
}
while (it != end) {
const ubyte b1 = *it++;
const ubyte b2 = *it++;
const ubyte b3 = *it++;
const ubyte b4 = *it++;
const int i1 = findIndex(b1);
const int i2 = findIndex(b2);
acc = i1 << 2;
acc |= i2 >> 4;
*sink++ = acc;
if (b3 != '=') {
const int i3 = findIndex(b3);
acc = (i2 & 0xF) << 4;
acc += i3 >> 2;
*sink++ = acc;
if (b4 != '=') {
const int i4 = findIndex(b4);
acc = (i3 & 0x3) << 6;
acc |= i4;
*sink++ = acc;
}
}
}
*sink = '\0';
return 0;
}
int main() {
ubyte data[] = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo";
ubyte decoded[1024];
printf("%s\n\n", data);
decode(data, decoded);
printf("%s\n\n", decoded);
return 0;
}
| use std::str;
const INPUT: &str = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo";
const UPPERCASE_OFFSET: i8 = -65;
const LOWERCASE_OFFSET: i8 = 26 - 97;
const NUM_OFFSET: i8 = 52 - 48;
fn main() {
println!("Input: {}", INPUT);
let result = INPUT.chars()
.filter(|&ch| ch != '=')
.map(|ch| {
let ascii = ch as i8;
let convert = match ch {
'0' ... '9' => ascii + NUM_OFFSET,
'a' ... 'z' => ascii + LOWERCASE_OFFSET,
'A' ... 'Z' => ascii + UPPERCASE_OFFSET,
'+' => 62,
'/' => 63,
_ => panic!("Not a valid base64 encoded string")
};
format!("{:#08b}", convert)[2..].to_string()
})
.collect::<String>()
.chars()
.collect::<Vec<char>>()
.chunks(8)
.map(|chunk| {
let num_str = chunk.iter().collect::<String>();
usize::from_str_radix(&num_str, 2).unwrap() as u8
})
.collect::<Vec<_>>();
let result = str::from_utf8(&result).unwrap();
println!("Output: {}", result);
}
|
Bell numbers | #include <stdio.h>
#include <stdlib.h>
size_t bellIndex(int row, int col) {
return row * (row - 1) / 2 + col;
}
int getBell(int *bellTri, int row, int col) {
size_t index = bellIndex(row, col);
return bellTri[index];
}
void setBell(int *bellTri, int row, int col, int value) {
size_t index = bellIndex(row, col);
bellTri[index] = value;
}
int *bellTriangle(int n) {
size_t length = n * (n + 1) / 2;
int *tri = calloc(length, sizeof(int));
int i, j;
setBell(tri, 1, 0, 1);
for (i = 2; i <= n; ++i) {
setBell(tri, i, 0, getBell(tri, i - 1, i - 2));
for (j = 1; j < i; ++j) {
int value = getBell(tri, i, j - 1) + getBell(tri, i - 1, j - 1);
setBell(tri, i, j, value);
}
}
return tri;
}
int main() {
const int rows = 15;
int *bt = bellTriangle(rows);
int i, j;
printf("First fifteen Bell numbers:\n");
for (i = 1; i <= rows; ++i) {
printf("%2d: %d\n", i, getBell(bt, i, 0));
}
printf("\nThe first ten rows of Bell's triangle:\n");
for (i = 1; i <= 10; ++i) {
printf("%d", getBell(bt, i, 0));
for (j = 1; j < i; ++j) {
printf(", %d", getBell(bt, i, j));
}
printf("\n");
}
free(bt);
return 0;
}
| use num::BigUint;
fn main() {
let bt = bell_triangle(51);
for i in 1..=15 {
println!("{}: {}", i, bt[i][0]);
}
println!("50: {}", bt[50][0])
}
fn bell_triangle(n: usize) -> Vec<Vec<BigUint>> {
let mut tri: Vec<Vec<BigUint>> = Vec::with_capacity(n);
for i in 0..n {
let v = vec![BigUint::from(0u32); i];
tri.push(v);
}
tri[1][0] = BigUint::from(1u32);
for i in 2..n {
tri[i][0] = BigUint::from_bytes_be(&tri[i - 1][i - 2].to_bytes_be());
for j in 1..i {
let added_big_uint = &tri[i][j - 1] + &tri[i - 1][j - 1];
tri[i][j] = BigUint::from_bytes_be(&added_big_uint.to_bytes_be());
}
}
tri
}
|
Bernoulli numbers | #include <stdlib.h>
#include <gmp.h>
#define mpq_for(buf, op, n)\
do {\
size_t i;\
for (i = 0; i < (n); ++i)\
mpq_##op(buf[i]);\
} while (0)
void bernoulli(mpq_t rop, unsigned int n)
{
unsigned int m, j;
mpq_t *a = malloc(sizeof(mpq_t) * (n + 1));
mpq_for(a, init, n + 1);
for (m = 0; m <= n; ++m) {
mpq_set_ui(a[m], 1, m + 1);
for (j = m; j > 0; --j) {
mpq_sub(a[j-1], a[j], a[j-1]);
mpq_set_ui(rop, j, 1);
mpq_mul(a[j-1], a[j-1], rop);
}
}
mpq_set(rop, a[0]);
mpq_for(a, clear, n + 1);
free(a);
}
int main(void)
{
mpq_t rop;
mpz_t n, d;
mpq_init(rop);
mpz_inits(n, d, NULL);
unsigned int i;
for (i = 0; i <= 60; ++i) {
bernoulli(rop, i);
if (mpq_cmp_ui(rop, 0, 1)) {
mpq_get_num(n, rop);
mpq_get_den(d, rop);
gmp_printf("B(%-2u) = %44Zd / %Zd\n", i, n, d);
}
}
mpz_clears(n, d, NULL);
mpq_clear(rop);
return 0;
}
|
#![feature(test)]
extern crate num;
extern crate test;
use num::bigint::{BigInt, ToBigInt};
use num::rational::{BigRational};
use std::cmp::max;
use std::env;
use std::ops::{Mul, Sub};
use std::process;
struct Bn {
value: BigRational,
index: i32
}
struct Context {
bigone_const: BigInt,
a: Vec<BigRational>,
index: i32
}
impl Context {
pub fn new() -> Context {
let bigone = 1.to_bigint().unwrap();
let a_vec: Vec<BigRational> = vec![];
Context {
bigone_const: bigone,
a: a_vec,
index: -1
}
}
}
impl Iterator for Context {
type Item = Bn;
fn next(&mut self) -> Option<Bn> {
self.index += 1;
Some(Bn { value: bernoulli(self.index as usize, self), index: self.index })
}
}
fn help() {
println!("Usage: bernoulli_numbers <up_to>");
}
fn main() {
let args: Vec<String> = env::args().collect();
let mut up_to: usize = 60;
match args.len() {
1 => {},
2 => {
up_to = args[1].parse::<usize>().unwrap();
},
_ => {
help();
process::exit(0);
}
}
let context = Context::new();
let res = context.take(up_to + 1).collect::<Vec<_>>();
let width = res.iter().fold(0, |a, r| max(a, r.value.numer().to_string().len()));
for r in res.iter().filter(|r| *r.value.numer() != ToBigInt::to_bigint(&0).unwrap()) {
println!("B({:>2}) = {:>2$} / {denom}", r.index, r.value.numer(), width,
denom = r.value.denom());
}
}
fn _bernoulli_naive(n: usize, c: &mut Context) -> BigRational {
for m in 0..n + 1 {
c.a.push(BigRational::new(c.bigone_const.clone(), (m + 1).to_bigint().unwrap()));
for j in (1..m + 1).rev() {
c.a[j - 1] = (c.a[j - 1].clone().sub(c.a[j].clone())).mul(
BigRational::new(j.to_bigint().unwrap(), c.bigone_const.clone())
);
}
}
c.a[0].reduced()
}
fn bernoulli(n: usize, c: &mut Context) -> BigRational {
for i in 0..n + 1 {
if i >= c.a.len() {
c.a.push(BigRational::new(c.bigone_const.clone(), (i + 1).to_bigint().unwrap()));
for j in (1..i + 1).rev() {
c.a[j - 1] = (c.a[j - 1].clone().sub(c.a[j].clone())).mul(
BigRational::new(j.to_bigint().unwrap(), c.bigone_const.clone())
);
}
}
}
c.a[0].reduced()
}
#[cfg(test)]
mod tests {
use super::{Bn, Context, bernoulli, _bernoulli_naive};
use num::rational::{BigRational};
use std::str::FromStr;
use test::Bencher;
#[bench]
fn bench_bernoulli_naive(b: &mut Bencher) {
let mut context = Context::new();
b.iter(|| {
let mut res: Vec<Bn> = vec![];
for n in 0..30 + 1 {
let b = _bernoulli_naive(n, &mut context);
res.push(Bn { value:b.clone(), index: n as i32});
}
});
}
#[bench]
fn bench_bernoulli(b: &mut Bencher) {
let mut context = Context::new();
b.iter(|| {
let mut res: Vec<Bn> = vec![];
for n in 0..30 + 1 {
let b = bernoulli(n, &mut context);
res.push(Bn { value:b.clone(), index: n as i32});
}
});
}
#[bench]
fn bench_bernoulli_iter(b: &mut Bencher) {
b.iter(|| {
let context = Context::new();
let _res = context.take(30 + 1).collect::<Vec<_>>();
});
}
}
|
Best shuffle | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <limits.h>
#define DEBUG
void best_shuffle(const char* txt, char* result) {
const size_t len = strlen(txt);
if (len == 0)
return;
#ifdef DEBUG
assert(len == strlen(result));
#endif
size_t counts[UCHAR_MAX];
memset(counts, '\0', UCHAR_MAX * sizeof(int));
size_t fmax = 0;
for (size_t i = 0; i < len; i++) {
counts[(unsigned char)txt[i]]++;
const size_t fnew = counts[(unsigned char)txt[i]];
if (fmax < fnew)
fmax = fnew;
}
assert(fmax > 0 && fmax <= len);
size_t *ndx1 = malloc(len * sizeof(size_t));
if (ndx1 == NULL)
exit(EXIT_FAILURE);
for (size_t ch = 0, i = 0; ch < UCHAR_MAX; ch++)
if (counts[ch])
for (size_t j = 0; j < len; j++)
if (ch == (unsigned char)txt[j]) {
ndx1[i] = j;
i++;
}
size_t *ndx2 = malloc(len * sizeof(size_t));
if (ndx2 == NULL)
exit(EXIT_FAILURE);
for (size_t i = 0, n = 0, m = 0; i < len; i++) {
ndx2[i] = ndx1[n];
n += fmax;
if (n >= len) {
m++;
n = m;
}
}
const size_t grp = 1 + (len - 1) / fmax;
assert(grp > 0 && grp <= len);
const size_t lng = 1 + (len - 1) % fmax;
assert(lng > 0 && lng <= len);
for (size_t i = 0, j = 0; i < fmax; i++) {
const size_t first = ndx2[j];
const size_t glen = grp - (i < lng ? 0 : 1);
for (size_t k = 1; k < glen; k++)
ndx1[j + k - 1] = ndx2[j + k];
ndx1[j + glen - 1] = first;
j += glen;
}
result[len] = '\0';
for (size_t i = 0; i < len; i++)
result[ndx2[i]] = txt[ndx1[i]];
free(ndx1);
free(ndx2);
}
void display(const char* txt1, const char* txt2) {
const size_t len = strlen(txt1);
assert(len == strlen(txt2));
int score = 0;
for (size_t i = 0; i < len; i++)
if (txt1[i] == txt2[i])
score++;
(void)printf("%s, %s, (%u)\n", txt1, txt2, score);
}
int main() {
const char* data[] = {"abracadabra", "seesaw", "elk", "grrrrrr",
"up", "a", "aabbbbaa", "", "xxxxx"};
const size_t data_len = sizeof(data) / sizeof(data[0]);
for (size_t i = 0; i < data_len; i++) {
const size_t shuf_len = strlen(data[i]) + 1;
char shuf[shuf_len];
#ifdef DEBUG
memset(shuf, 0xFF, sizeof shuf);
shuf[shuf_len - 1] = '\0';
#endif
best_shuffle(data[i], shuf);
display(data[i], shuf);
}
return EXIT_SUCCESS;
}
| extern crate permutohedron;
extern crate rand;
use std::cmp::{min, Ordering};
use std::env;
use rand::{thread_rng, Rng};
use std::str;
const WORDS: &'static [&'static str] = &["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"];
#[derive(Eq)]
struct Solution {
original: String,
shuffled: String,
score: usize,
}
impl PartialOrd for Solution {
fn partial_cmp(&self, other: &Solution) -> Option<Ordering> {
match (self.score, other.score) {
(s, o) if s < o => Some(Ordering::Less),
(s, o) if s > o => Some(Ordering::Greater),
(s, o) if s == o => Some(Ordering::Equal),
_ => None,
}
}
}
impl PartialEq for Solution {
fn eq(&self, other: &Solution) -> bool {
match (self.score, other.score) {
(s, o) if s == o => true,
_ => false,
}
}
}
impl Ord for Solution {
fn cmp(&self, other: &Solution) -> Ordering {
match (self.score, other.score) {
(s, o) if s < o => Ordering::Less,
(s, o) if s > o => Ordering::Greater,
_ => Ordering::Equal,
}
}
}
fn _help() {
println!("Usage: best_shuffle <word1> <word2> ...");
}
fn main() {
let args: Vec<String> = env::args().collect();
let mut words: Vec<String> = vec![];
match args.len() {
1 => {
for w in WORDS.iter() {
words.push(String::from(*w));
}
}
_ => {
for w in args.split_at(1).1 {
words.push(w.clone());
}
}
}
let solutions = words.iter().map(|w| best_shuffle(w)).collect::<Vec<_>>();
for s in solutions {
println!("{}, {}, ({})", s.original, s.shuffled, s.score);
}
}
fn _best_shuffle_perm(w: &String) -> Solution {
let mut soln = Solution {
original: w.clone(),
shuffled: w.clone(),
score: w.len(),
};
let w_bytes: Vec<u8> = w.clone().into_bytes();
let mut permutocopy = w_bytes.clone();
let mut permutations = permutohedron::Heap::new(&mut permutocopy);
while let Some(p) = permutations.next_permutation() {
let hamm = hamming(&w_bytes, p);
soln = min(soln,
Solution {
original: w.clone(),
shuffled: String::from(str::from_utf8(p).unwrap()),
score: hamm,
});
if hamm == 0 {
break;
}
}
soln
}
fn best_shuffle(w: &String) -> Solution {
let w_bytes: Vec<u8> = w.clone().into_bytes();
let mut shuffled_bytes: Vec<u8> = w.clone().into_bytes();
let sh: &mut [u8] = shuffled_bytes.as_mut_slice();
thread_rng().shuffle(sh);
for i in 0..sh.len() {
for j in 0..sh.len() {
if (i == j) | (sh[i] == w_bytes[j]) | (sh[j] == w_bytes[i]) | (sh[i] == sh[j]) {
continue;
}
sh.swap(i, j);
break;
}
}
let res = String::from(str::from_utf8(sh).unwrap());
let res_bytes: Vec<u8> = res.clone().into_bytes();
Solution {
original: w.clone(),
shuffled: res,
score: hamming(&w_bytes, &res_bytes),
}
}
fn hamming(w0: &Vec<u8>, w1: &Vec<u8>) -> usize {
w0.iter().zip(w1.iter()).filter(|z| z.0 == z.1).count()
}
|
Bin given limits | #include <stdio.h>
#include <stdlib.h>
size_t upper_bound(const int* array, size_t n, int value) {
size_t start = 0;
while (n > 0) {
size_t step = n / 2;
size_t index = start + step;
if (value >= array[index]) {
start = index + 1;
n -= step + 1;
} else {
n = step;
}
}
return start;
}
int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {
int* result = calloc(nlimits + 1, sizeof(int));
if (result == NULL)
return NULL;
for (size_t i = 0; i < ndata; ++i)
++result[upper_bound(limits, nlimits, data[i])];
return result;
}
void print_bins(const int* limits, size_t n, const int* bins) {
if (n == 0)
return;
printf(" < %3d: %2d\n", limits[0], bins[0]);
for (size_t i = 1; i < n; ++i)
printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]);
printf(">= %3d : %2d\n", limits[n - 1], bins[n]);
}
int main() {
const int limits1[] = {23, 37, 43, 53, 67, 83};
const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57,
5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,
8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98,
40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
printf("Example 1:\n");
size_t n = sizeof(limits1) / sizeof(int);
int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits1, n, b);
free(b);
const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};
const int data2[] = {
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
printf("\nExample 2:\n");
n = sizeof(limits2) / sizeof(int);
b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits2, n, b);
free(b);
return EXIT_SUCCESS;
}
| fn make_bins(limits: &Vec<usize>, data: &Vec<usize>) -> Vec<Vec<usize>> {
let mut bins: Vec<Vec<usize>> = Vec::with_capacity(limits.len() + 1);
for _ in 0..=limits.len() {bins.push(Vec::new());}
limits.iter().enumerate().for_each(|(idx, limit)| {
data.iter().for_each(|elem| {
if idx == 0 && elem < limit { bins[0].push(*elem); }
else if idx == limits.len()-1 && elem >= limit { bins[limits.len()].push(*elem); }
else if elem < limit && elem >= &limits[idx-1] { bins[idx].push(*elem); }
});
});
bins
}
fn print_bins(limits: &Vec<usize>, bins: &Vec<Vec<usize>>) {
for (idx, bin) in bins.iter().enumerate() {
if idx == 0 {
println!(" < {:3} := {:3}", limits[idx], bin.len());
} else if idx == limits.len() {
println!(">= {:3} := {:3}", limits[idx-1], bin.len());
}else {
println!(">= {:3} .. < {:3} := {:3}", limits[idx-1], limits[idx], bin.len());
}
};
}
fn main() {
let limits1 = vec![23, 37, 43, 53, 67, 83];
let data1 = vec![95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55];
let limits2 = vec![14, 18, 249, 312, 389, 392, 513, 591, 634, 720];
let data2 = vec![
445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749
];
println!("RC FIRST EXAMPLE");
let bins1 = make_bins(&limits1, &data1);
print_bins(&limits1, &bins1);
println!("\nRC SECOND EXAMPLE");
let bins2 = make_bins(&limits2, &data2);
print_bins(&limits2, &bins2);
}
|
Binary digits | #define _CRT_SECURE_NO_WARNINGS
#define _CRT_NONSTDC_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
char* bin2str(unsigned value, char* buffer)
{
const unsigned N_DIGITS = sizeof(unsigned) * 8;
unsigned mask = 1 << (N_DIGITS - 1);
char* ptr = buffer;
for (int i = 0; i < N_DIGITS; i++)
{
*ptr++ = '0' + !!(value & mask);
mask >>= 1;
}
*ptr = '\0';
for (ptr = buffer; *ptr == '0'; ptr++)
;
return ptr;
}
char* bin2strNaive(unsigned value, char* buffer)
{
unsigned n, m, p;
n = 0;
p = 1;
while (p <= value / 2)
{
n = n + 1;
p = p * 2;
}
m = 0;
while (n > 0)
{
buffer[m] = '0' + value / p;
value = value % p;
m = m + 1;
n = n - 1;
p = p / 2;
}
buffer[m + 1] = '\0';
return buffer;
}
int main(int argc, char* argv[])
{
const unsigned NUMBERS[] = { 5, 50, 9000 };
const int RADIX = 2;
char buffer[(sizeof(unsigned)*8 + 1)];
for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
{
unsigned value = NUMBERS[i];
itoa(value, buffer, RADIX);
printf("itoa: %u decimal = %s binary\n", value, buffer);
}
for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
{
unsigned value = NUMBERS[i];
printf("bin2str: %u decimal = %s binary\n", value, bin2str(value, buffer));
}
for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
{
unsigned value = NUMBERS[i];
printf("bin2strNaive: %u decimal = %s binary\n", value, bin2strNaive(value, buffer));
}
return EXIT_SUCCESS;
}
| fn main() {
for i in 0..8 {
println!("{:b}", i)
}
}
|
Binary search | #include <stdio.h>
int bsearch (int *a, int n, int x) {
int i = 0, j = n - 1;
while (i <= j) {
int k = i + ((j - i) / 2);
if (a[k] == x) {
return k;
}
else if (a[k] < x) {
i = k + 1;
}
else {
j = k - 1;
}
}
return -1;
}
int bsearch_r (int *a, int x, int i, int j) {
if (j < i) {
return -1;
}
int k = i + ((j - i) / 2);
if (a[k] == x) {
return k;
}
else if (a[k] < x) {
return bsearch_r(a, x, k + 1, j);
}
else {
return bsearch_r(a, x, i, k - 1);
}
}
int main () {
int a[] = {-31, 0, 1, 2, 2, 4, 65, 83, 99, 782};
int n = sizeof a / sizeof a[0];
int x = 2;
int i = bsearch(a, n, x);
if (i >= 0)
printf("%d is at index %d.\n", x, i);
else
printf("%d is not found.\n", x);
x = 5;
i = bsearch_r(a, x, 0, n - 1);
if (i >= 0)
printf("%d is at index %d.\n", x, i);
else
printf("%d is not found.\n", x);
return 0;
}
| fn binary_search<T:PartialOrd>(v: &[T], searchvalue: T) -> Option<T> {
let mut lower = 0 as usize;
let mut upper = v.len() - 1;
while upper >= lower {
let mid = (upper + lower) / 2;
if v[mid] == searchvalue {
return Some(searchvalue);
} else if searchvalue < v[mid] {
upper = mid - 1;
} else {
lower = mid + 1;
}
}
None
}
|
Binary strings | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct str_t {
size_t len, alloc;
unsigned char *s;
} bstr_t, *bstr;
#define str_len(s) ((s)->len)
bstr str_new(size_t len)
{
bstr s = malloc(sizeof(bstr_t));
if (len < 8) len = 8;
s->alloc = len;
s->s = malloc(len);
s->len = 0;
return s;
}
void str_extend(bstr s)
{
size_t ns = s->alloc * 2;
if (ns - s->alloc > 1024) ns = s->alloc + 1024;
s->s = realloc(s->s, ns);
s->alloc = ns;
}
void str_del(bstr s)
{
free(s->s), free(s);
}
int str_cmp(bstr l, bstr r)
{
int res, len = l->len;
if (len > r->len) len = r->len;
if ((res = memcmp(l->s, r->s, len))) return res;
return l->len > r->len ? 1 : -1;
}
bstr str_dup(bstr src)
{
bstr x = str_new(src->len);
memcpy(x->s, src->s, src->len);
x->len = src->len;
return x;
}
bstr str_from_chars(const char *t)
{
if (!t) return str_new(0);
size_t l = strlen(t);
bstr x = str_new(l + 1);
x->len = l;
memcpy(x->s, t, l);
return x;
}
void str_append(bstr s, unsigned char b)
{
if (s->len >= s->alloc) str_extend(s);
s->s[s->len++] = b;
}
bstr str_substr(bstr s, int from, int to)
{
if (!to) to = s->len;
if (from < 0) from += s->len;
if (from < 0 || from >= s->len)
return 0;
if (to < from) to = from + 1;
bstr x = str_new(to - from);
x->len = to - from;
memcpy(x->s, s->s + from, x->len);
return x;
}
bstr str_cat(bstr s, bstr s2)
{
while (s->alloc < s->len + s2->len) str_extend(s);
memcpy(s->s + s->len, s2->s, s2->len);
s->len += s2->len;
return s;
}
void str_swap(bstr a, bstr b)
{
size_t tz;
unsigned char *ts;
tz = a->alloc; a->alloc = b->alloc; b->alloc = tz;
tz = a->len; a->len = b->len; b->len = tz;
ts = a->s; a->s = b->s; b->s = ts;
}
bstr str_subst(bstr tgt, bstr pat, bstr repl)
{
bstr tmp = str_new(0);
int i;
for (i = 0; i + pat->len <= tgt->len;) {
if (memcmp(tgt->s + i, pat->s, pat->len)) {
str_append(tmp, tgt->s[i]);
i++;
} else {
str_cat(tmp, repl);
i += pat->len;
if (!pat->len) str_append(tmp, tgt->s[i++]);
}
}
while (i < tgt->len) str_append(tmp, tgt->s[i++]);
str_swap(tmp, tgt);
str_del(tmp);
return tgt;
}
void str_set(bstr dest, bstr src)
{
while (dest->len < src->len) str_extend(dest);
memcpy(dest->s, src->s, src->len);
dest->len = src->len;
}
int main()
{
bstr s = str_from_chars("aaaaHaaaaaFaaaaHa");
bstr s2 = str_from_chars("___.");
bstr s3 = str_from_chars("");
str_subst(s, s3, s2);
printf("%.*s\n", s->len, s->s);
str_del(s);
str_del(s2);
str_del(s3);
return 0;
}
| use std::str;
fn main() {
let string = String::from("Hello world!");
println!("{}", string);
assert_eq!(string, "Hello world!", "Incorrect string text");
let mut assigned_str = String::new();
assert_eq!(assigned_str, "", "Incorrect string creation");
assigned_str += "Text has been assigned!";
println!("{}", assigned_str);
assert_eq!(assigned_str, "Text has been assigned!","Incorrect string text");
if string == "Hello world!" && assigned_str == "Text has been assigned!" {
println!("Strings are equal");
}
let clone_str = string.clone();
println!("String is:{} and Clone string is: {}", string, clone_str);
assert_eq!(clone_str, string, "Incorrect string creation");
let copy_str = string;
println!("String copied now: {}", copy_str);
let empty_str = String::new();
assert!(empty_str.is_empty(), "Error, string should be empty");
let byte_vec = [65];
let byte_str = str::from_utf8(&byte_vec).unwrap();
assert_eq!(byte_str, "A", "Incorrect byte append");
let test_str = "Blah String";
let mut sub_str = &test_str[0..11];
assert_eq!(sub_str, "Blah String", "Error in slicing");
sub_str = &test_str[1..5];
assert_eq!(sub_str, "lah ", "Error in slicing");
sub_str = &test_str[3..];
assert_eq!(sub_str, "h String", "Error in slicing");
sub_str = &test_str[..2];
assert_eq!(sub_str, "Bl", "Error in slicing");
let org_str = "Hello";
assert_eq!(org_str.replace("l", "a"), "Heaao", "Error in replacement");
assert_eq!(org_str.replace("ll", "r"), "Hero", "Error in replacement");
let str1 = "Hi";
let str2 = " There";
let fin_str = str1.to_string() + str2;
assert_eq!(fin_str, "Hi There", "Error in concatenation");
let str1 = "Hi";
let str2 = " There";
let fin_str = str1.to_string() + str2;
assert_eq!(fin_str, "Hi There", "Error in concatenation");
let f_str = "Pooja and Sundar are up in Tumkur";
let split_str: Vec<_> = f_str.split(' ').collect();
assert_eq!(split_str, ["Pooja", "and", "Sundar", "are", "up", "in", "Tumkur"], "Error in string split");
}
|
Bitcoin_address validation | #include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
const char *coin_err;
#define bail(s) { coin_err = s; return 0; }
int unbase58(const char *s, unsigned char *out) {
static const char *tmpl = "123456789"
"ABCDEFGHJKLMNPQRSTUVWXYZ"
"abcdefghijkmnopqrstuvwxyz";
int i, j, c;
const char *p;
memset(out, 0, 25);
for (i = 0; s[i]; i++) {
if (!(p = strchr(tmpl, s[i])))
bail("bad char");
c = p - tmpl;
for (j = 25; j--; ) {
c += 58 * out[j];
out[j] = c % 256;
c /= 256;
}
if (c) bail("address too long");
}
return 1;
}
int valid(const char *s) {
unsigned char dec[32], d1[SHA256_DIGEST_LENGTH], d2[SHA256_DIGEST_LENGTH];
coin_err = "";
if (!unbase58(s, dec)) return 0;
SHA256(SHA256(dec, 21, d1), SHA256_DIGEST_LENGTH, d2);
if (memcmp(dec + 21, d2, 4))
bail("bad digest");
return 1;
}
int main (void) {
const char *s[] = {
"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",
"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I",
0 };
int i;
for (i = 0; s[i]; i++) {
int status = valid(s[i]);
printf("%s: %s\n", s[i], status ? "Ok" : coin_err);
}
return 0;
}
| extern crate crypto;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
const DIGITS58: [char; 58] = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
fn main() {
println!("{}", validate_address("1AGNa15ZQXAZUgFiqJ3i7Z2DPU2J6hW62i"));
println!("{}", validate_address("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i"));
println!("{}", validate_address("17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j"));
println!("{}", validate_address("17NdbrSGoUotzeGCcMMC?nFkEvLymoou9j"));
}
fn validate_address(address: &str) -> bool {
let decoded = match from_base58(address, 25) {
Ok(x) => x,
Err(_) => return false
};
if decoded[0] != 0 {
return false;
}
let mut sha = Sha256::new();
sha.input(&decoded[0..21]);
let mut first_round = vec![0u8; sha.output_bytes()];
sha.result(&mut first_round);
sha.reset();
sha.input(&first_round);
let mut second_round = vec![0u8; sha.output_bytes()];
sha.result(&mut second_round);
if second_round[0..4] != decoded[21..25] {
return false
}
true
}
fn from_base58(encoded: &str, size: usize) -> Result<Vec<u8>, String> {
let mut res: Vec<u8> = vec![0; size];
for base58_value in encoded.chars() {
let mut value: u32 = match DIGITS58
.iter()
.position(|x| *x == base58_value){
Some(x) => x as u32,
None => return Err(String::from("Invalid character found in encoded string."))
};
for result_index in (0..size).rev() {
value += 58 * res[result_index] as u32;
res[result_index] = (value % 256) as u8;
value /= 256;
}
}
Ok(res)
}
|
Bitmap | #ifndef _IMGLIB_0
#define _IMGLIB_0
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <math.h>
#include <sys/queue.h>
typedef unsigned char color_component;
typedef color_component pixel[3];
typedef struct {
unsigned int width;
unsigned int height;
pixel * buf;
} image_t;
typedef image_t * image;
image alloc_img(unsigned int width, unsigned int height);
void free_img(image);
void fill_img(image img,
color_component r,
color_component g,
color_component b );
void put_pixel_unsafe(
image img,
unsigned int x,
unsigned int y,
color_component r,
color_component g,
color_component b );
void put_pixel_clip(
image img,
unsigned int x,
unsigned int y,
color_component r,
color_component g,
color_component b );
#define GET_PIXEL(IMG, X, Y) (IMG->buf[ ((Y) * IMG->width + (X)) ])
#endif
| #[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Rgb {
pub r: u8,
pub g: u8,
pub b: u8,
}
impl Rgb {
pub fn new(r: u8, g: u8, b: u8) -> Self {
Rgb { r, g, b }
}
pub const BLACK: Rgb = Rgb { r: 0, g: 0, b: 0 };
pub const RED: Rgb = Rgb { r: 255, g: 0, b: 0 };
pub const GREEN: Rgb = Rgb { r: 0, g: 255, b: 0 };
pub const BLUE: Rgb = Rgb { r: 0, g: 0, b: 255 };
}
#[derive(Clone, Debug)]
pub struct Image {
width: usize,
height: usize,
pixels: Vec<Rgb>,
}
impl Image {
pub fn new(width: usize, height: usize) -> Self {
Image {
width,
height,
pixels: vec![Rgb::BLACK; width * height],
}
}
pub fn width(&self) -> usize {
self.width
}
pub fn height(&self) -> usize {
self.height
}
pub fn fill(&mut self, color: Rgb) {
for pixel in &mut self.pixels {
*pixel = color;
}
}
pub fn get(&self, row: usize, col: usize) -> Option<&Rgb> {
if row >= self.width {
return None;
}
self.pixels.get(row * self.width + col)
}
pub fn get_mut(&mut self, row: usize, col: usize) -> Option<&mut Rgb> {
if row >= self.width {
return None;
}
self.pixels.get_mut(row * self.width + col)
}
}
fn main() {
let mut image = Image::new(16, 9);
assert_eq!(Some(&Rgb::BLACK), image.get(3, 4));
assert!(image.get(22, 3).is_none());
image.fill(Rgb::RED);
assert_eq!(Some(&Rgb::RED), image.get(3, 4));
if let Some(pixel) = image.get_mut(3, 4) {
*pixel = Rgb::GREEN;
}
assert_eq!(Some(&Rgb::GREEN), image.get(3, 4));
if let Some(pixel) = image.get_mut(3, 4) {
pixel.g -= 100;
pixel.b = 20;
}
assert_eq!(Some(&Rgb::new(0, 155, 20)), image.get(3, 4));
}
|
Bitmap_Bresenham's line algorithm | void line(int x0, int y0, int x1, int y1) {
int dx = abs(x1-x0), sx = x0<x1 ? 1 : -1;
int dy = abs(y1-y0), sy = y0<y1 ? 1 : -1;
int err = (dx>dy ? dx : -dy)/2, e2;
for(;;){
setPixel(x0,y0);
if (x0==x1 && y0==y1) break;
e2 = err;
if (e2 >-dx) { err -= dy; x0 += sx; }
if (e2 < dy) { err += dx; y0 += sy; }
}
}
| struct Point {
x: i32,
y: i32
}
fn main() {
let mut points: Vec<Point> = Vec::new();
points.append(&mut get_coordinates(1, 20, 20, 28));
points.append(&mut get_coordinates(20, 28, 69, 0));
draw_line(points, 70, 30);
}
fn get_coordinates(x1: i32, y1: i32, x2: i32, y2: i32) -> Vec<Point> {
let mut coordinates: Vec<Point> = vec![];
let dx:i32 = i32::abs(x2 - x1);
let dy:i32 = i32::abs(y2 - y1);
let sx:i32 = { if x1 < x2 { 1 } else { -1 } };
let sy:i32 = { if y1 < y2 { 1 } else { -1 } };
let mut error:i32 = (if dx > dy { dx } else { -dy }) / 2 ;
let mut current_x:i32 = x1;
let mut current_y:i32 = y1;
loop {
coordinates.push(Point { x : current_x, y: current_y });
if current_x == x2 && current_y == y2 { break; }
let error2:i32 = error;
if error2 > -dx {
error -= dy;
current_x += sx;
}
if error2 < dy {
error += dx;
current_y += sy;
}
}
coordinates
}
fn draw_line(line: std::vec::Vec<Point>, width: i32, height: i32) {
for col in 0..height {
for row in 0..width {
let is_point_in_line = line.iter().any(| point| point.x == row && point.y == col);
match is_point_in_line {
true => print!("@"),
_ => print!(".")
};
}
print!("\n");
}
}
|
Bitmap_Flood fill |
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 2048
#define BYTE unsigned char
static int width, height;
static BYTE bitmap[MAXSIZE][MAXSIZE];
static BYTE oldColor;
static BYTE newColor;
void floodFill(int i, int j)
{
if ( 0 <= i && i < height
&& 0 <= j && j < width
&& bitmap[i][j] == oldColor )
{
bitmap[i][j] = newColor;
floodFill(i-1,j);
floodFill(i+1,j);
floodFill(i,j-1);
floodFill(i,j+1);
}
}
void skipLine(FILE* file)
{
while(!ferror(file) && !feof(file) && fgetc(file) != '\n')
;
}
void skipCommentLines(FILE* file)
{
int c;
int comment = '#';
while ((c = fgetc(file)) == comment)
skipLine(file);
ungetc(c,file);
}
readPortableBitMap(FILE* file)
{
int i,j;
skipLine(file);
skipCommentLines(file); fscanf(file,"%d",&width);
skipCommentLines(file); fscanf(file,"%d",&height);
skipCommentLines(file);
if ( width <= MAXSIZE && height <= MAXSIZE )
for ( i = 0; i < height; i++ )
for ( j = 0; j < width; j++ )
fscanf(file,"%1d",&(bitmap[i][j]));
else exit(EXIT_FAILURE);
}
void writePortableBitMap(FILE* file)
{
int i,j;
fprintf(file,"P1\n");
fprintf(file,"%d %d\n", width, height);
for ( i = 0; i < height; i++ )
{
for ( j = 0; j < width; j++ )
fprintf(file,"%1d", bitmap[i][j]);
fprintf(file,"\n");
}
}
int main(void)
{
oldColor = 1;
newColor = oldColor ? 0 : 1;
readPortableBitMap(stdin);
floodFill(height/2,width/2);
writePortableBitMap(stdout);
return EXIT_SUCCESS;
}
|
use std::fs::File;
use std::io::{BufReader, BufRead, Write};
fn read_image(filename: String) -> Vec<Vec<(u8,u8,u8)>> {
let file = File::open(filename).unwrap();
let reader = BufReader::new(file);
let mut lines = reader.lines();
let _ = lines.next().unwrap();
let _ = lines.next().unwrap();
let dimensions: (usize, usize) = {
let line = lines.next().unwrap().unwrap();
let values = line.split_whitespace().collect::<Vec<&str>>();
(values[0].parse::<usize>().unwrap(),values[1].parse::<usize>().unwrap())
};
let _ = lines.next().unwrap();
let mut image_data = Vec::with_capacity(dimensions.1);
for y in 0..dimensions.1 {
image_data.push(Vec::new());
for _ in 0..dimensions.0 {
image_data[y].push((lines.next().unwrap().unwrap().parse::<u8>().unwrap(),
lines.next().unwrap().unwrap().parse::<u8>().unwrap(),
lines.next().unwrap().unwrap().parse::<u8>().unwrap()));
}
}
image_data
}
fn write_image(image_data: Vec<Vec<(u8,u8,u8)>>) {
let mut file = File::create(format!("./output.ppm")).unwrap();
write!(file, "P3\n{} {}\n255\n", image_data.len(), image_data[0].len()).unwrap();
for row in &image_data {
let mut line = String::with_capacity(row.len()*6);
for (r,g,b) in row {
line.push_str(&*format!("{} {} {} ", r,g,b));
}
write!(file, "{}", line).unwrap();
}
}
fn flood_fill(x: usize, y: usize, target: &(u8,u8,u8), replacement: &(u8,u8,u8), image_data: &mut Vec<Vec<(u8,u8,u8)>>) {
if &image_data[y][x] == target {
image_data[y][x] = *replacement;
if y > 0 {flood_fill(x,y-1, &target, &replacement, image_data);}
if x > 0 {flood_fill(x-1,y, &target, &replacement, image_data);}
if y < image_data.len()-1 {flood_fill(x,y+1, &target, &replacement, image_data);}
if x < image_data[0].len()-1 {flood_fill(x+1,y, &target, &replacement, image_data);}
}
}
fn main() {
let mut data = read_image(String::from("./input.ppm"));
flood_fill(1,50, &(255,255,255), &(0,255,0), &mut data);
flood_fill(40,35, &(0,0,0), &(255,0,0), &mut data);
write_image(data);
}
|
Bitmap_Read a PPM file | image get_ppm(FILE *pf);
| parser.rs:
use super::{Color, ImageFormat};
use std::str::from_utf8;
use std::str::FromStr;
pub fn parse_version(input: &[u8]) -> nom::IResult<&[u8], ImageFormat> {
use nom::branch::alt;
use nom::bytes::complete::tag;
use nom::character::complete::line_ending;
use nom::combinator::map;
use nom::sequence::terminated;
terminated(
alt((
map(tag("P3".as_bytes()), |_| ImageFormat::P3),
map(tag("P6".as_bytes()), |_| ImageFormat::P6),
)),
line_ending,
)(input)
}
pub fn parse_image_attributes(input: &[u8]) -> nom::IResult<&[u8], (usize, usize, usize)> {
use nom::character::complete::line_ending;
use nom::character::complete::{digit1, space1};
use nom::sequence::terminated;
use nom::sequence::tuple;
terminated(tuple((digit1, space1, digit1, space1, digit1)), line_ending)(input).map(
|(next_input, result)| {
(
next_input,
(
usize::from_str_radix(from_utf8(result.0).unwrap(), 10).unwrap(),
usize::from_str_radix(from_utf8(result.2).unwrap(), 10).unwrap(),
usize::from_str_radix(from_utf8(result.4).unwrap(), 10).unwrap(),
),
)
},
)
}
pub fn parse_color_binary(input: &[u8]) -> nom::IResult<&[u8], Color> {
use nom::number::complete::u8 as nom_u8;
use nom::sequence::tuple;
tuple((nom_u8, nom_u8, nom_u8))(input).map(|(next_input, res)| {
(
next_input,
Color {
red: res.0,
green: res.1,
blue: res.2,
},
)
})
}
pub fn parse_data_binary(input: &[u8]) -> nom::IResult<&[u8], Vec<Color>> {
use nom::multi::many0;
many0(parse_color_binary)(input)
}
pub fn parse_color_ascii(input: &[u8]) -> nom::IResult<&[u8], Color> {
use nom::character::complete::{digit1, space0, space1};
use nom::sequence::tuple;
tuple((digit1, space1, digit1, space1, digit1, space0))(input).map(|(next_input, res)| {
(
next_input,
Color {
red: u8::from_str(from_utf8(res.0).unwrap()).unwrap(),
green: u8::from_str(from_utf8(res.2).unwrap()).unwrap(),
blue: u8::from_str(from_utf8(res.4).unwrap()).unwrap(),
},
)
})
}
pub fn parse_data_ascii(input: &[u8]) -> nom::IResult<&[u8], Vec<Color>> {
use nom::multi::many0;
many0(parse_color_ascii)(input)
}
lib.rs:
extern crate nom;
extern crate thiserror;
mod parser;
use std::default::Default;
use std::fmt;
use std::io::{BufWriter, Error, Write};
use std::ops::{Index, IndexMut};
use std::{fs::File, io::Read};
use thiserror::Error;
#[derive(Copy, Clone, Default, PartialEq, Debug)]
pub struct Color {
pub red: u8,
pub green: u8,
pub blue: u8,
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum ImageFormat {
P3,
P6,
}
impl From<&str> for ImageFormat {
fn from(i: &str) -> Self {
match i.to_lowercase().as_str() {
"p3" => ImageFormat::P3,
"p6" => ImageFormat::P6,
_ => unimplemented!("no other formats supported"),
}
}
}
impl fmt::Display for ImageFormat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ImageFormat::P3 => {
write!(f, "P3")
}
ImageFormat::P6 => {
write!(f, "P6")
}
}
}
}
#[derive(Error, Debug)]
pub enum ImageError {
#[error("File not found")]
FileNotFound,
#[error("File not readable")]
FileNotReadable,
#[error("Invalid header information")]
InvalidHeader,
#[error("Invalid information in the data block")]
InvalidData,
#[error("Invalid max color information")]
InvalidMaxColor,
#[error("File is incomplete")]
IncompleteFile,
#[error("unknown data store error")]
Unknown,
}
pub struct Image {
pub format: ImageFormat,
pub width: usize,
pub height: usize,
pub data: Vec<Color>,
}
impl Image {
#[must_use]
pub fn new(width: usize, height: usize) -> Self {
Self {
format: ImageFormat::P6,
width,
height,
data: vec![Color::default(); width * height],
}
}
pub fn fill(&mut self, color: Color) {
for elem in &mut self.data {
*elem = color;
}
}
pub fn write_ppm(&self, filename: &str) -> Result<(), Error> {
let file = File::create(filename)?;
let mut writer = BufWriter::new(file);
writeln!(&mut writer, "{}", self.format.to_string())?;
writeln!(&mut writer, "{} {} 255", self.width, self.height)?;
match self.format {
ImageFormat::P3 => {
writer.write_all(
&self
.data
.iter()
.flat_map(|color| {
vec![
color.red.to_string(),
color.green.to_string(),
color.blue.to_string(),
]
})
.collect::<Vec<String>>()
.join(" ")
.as_bytes(),
)?;
}
ImageFormat::P6 => {
writer.write_all(
&self
.data
.iter()
.flat_map(|color| vec![color.red, color.green, color.blue])
.collect::<Vec<u8>>(),
)?;
}
}
Ok(())
}
pub fn read_ppm(filename: &str) -> Result<Image, ImageError> {
let mut file = File::open(filename).map_err(|_| ImageError::FileNotFound)?;
let mut data: Vec<u8> = Vec::new();
file.read_to_end(&mut data)
.map_err(|_| ImageError::FileNotReadable)?;
let (i, format) = parser::parse_version(&data).map_err(|_| ImageError::InvalidHeader)?;
let (i, (width, height, max_color)) =
parser::parse_image_attributes(i).map_err(|_| ImageError::InvalidHeader)?;
if max_color != 255 {
return Err(ImageError::InvalidMaxColor);
}
let (_, data) = match format {
ImageFormat::P3 => parser::parse_data_ascii(i).map_err(|_| ImageError::InvalidData)?,
ImageFormat::P6 => parser::parse_data_binary(i).map_err(|_| ImageError::InvalidData)?,
};
if data.len() != height * width {
return Err(ImageError::IncompleteFile);
};
Ok(Image {
format,
width,
height,
data,
})
}
}
impl Index<(usize, usize)> for Image {
type Output = Color;
fn index(&self, (x, y): (usize, usize)) -> &Color {
&self.data[x + y * self.width]
}
}
impl IndexMut<(usize, usize)> for Image {
fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut Color {
&mut self.data[x + y * self.width]
}
}
use bitmap::Image;
pub fn main() {
let image = Image::read_ppm("./test_image.ppm").unwrap();
println!("Read using nom parsing:");
println!("Format: {:?}", image.format);
println!("Dimensions: {} x {}", image.height, image.width);
}
|
Bitmap_Write a PPM file | #include <stdlib.h>
#include <stdio.h>
int main(void)
{
const int dimx = 800, dimy = 800;
int i, j;
FILE *fp = fopen("first.ppm", "wb");
(void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy);
for (j = 0; j < dimy; ++j)
{
for (i = 0; i < dimx; ++i)
{
static unsigned char color[3];
color[0] = i % 256;
color[1] = j % 256;
color[2] = (i * j) % 256;
(void) fwrite(color, 1, 3, fp);
}
}
(void) fclose(fp);
return EXIT_SUCCESS;
}
| use std::path::Path;
use std::io::Write;
use std::fs::File;
pub struct RGB {
r: u8,
g: u8,
b: u8,
}
pub struct PPM {
height: u32,
width: u32,
data: Vec<u8>,
}
impl PPM {
pub fn new(height: u32, width: u32) -> PPM {
let size = 3 * height * width;
let buffer = vec![0; size as usize];
PPM { height: height, width: width, data: buffer }
}
fn buffer_size(&self) -> u32 {
3 * self.height * self.width
}
fn get_offset(&self, x: u32, y: u32) -> Option<usize> {
let offset = (y * self.width * 3) + (x * 3);
if offset < self.buffer_size() {
Some(offset as usize)
} else {
None
}
}
pub fn get_pixel(&self, x: u32, y: u32) -> Option<RGB> {
match self.get_offset(x, y) {
Some(offset) => {
let r = self.data[offset];
let g = self.data[offset + 1];
let b = self.data[offset + 2];
Some(RGB {r: r, g: g, b: b})
},
None => None
}
}
pub fn set_pixel(&mut self, x: u32, y: u32, color: RGB) -> bool {
match self.get_offset(x, y) {
Some(offset) => {
self.data[offset] = color.r;
self.data[offset + 1] = color.g;
self.data[offset + 2] = color.b;
true
},
None => false
}
}
pub fn write_file(&self, filename: &str) -> std::io::Result<()> {
let path = Path::new(filename);
let mut file = File::create(&path)?;
let header = format!("P6 {} {} 255\n", self.width, self.height);
file.write(header.as_bytes())?;
file.write(&self.data)?;
Ok(())
}
}
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 10