name stringlengths 2 74 | C stringlengths 7 6.19k | Rust stringlengths 19 8.53k |
|---|---|---|
Remove vowels from a string | #include <stdio.h>
void print_no_vowels(const char *s) {
for (; *s != 0; s++) {
switch (*s) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
break;
defaul... | fn remove_vowels(str: String) -> String {
let vowels = "aeiouAEIOU";
let mut devowelled_string = String::from("");
for i in str.chars() {
if vowels.contains(i) {
continue;
} else {
devowelled_string.push(i);
}
}
return devowelled_string;
}
fn main() ... |
Rename a file | #include <stdio.h>
int main()
{
rename("input.txt", "output.txt");
rename("docs", "mydocs");
rename("/input.txt", "/output.txt");
rename("/docs", "/mydocs");
return 0;
}
| use std::fs;
fn main() {
let err = "File move error";
fs::rename("input.txt", "output.txt").ok().expect(err);
fs::rename("docs", "mydocs").ok().expect(err);
fs::rename("/input.txt", "/output.txt").ok().expect(err);
fs::rename("/docs", "/mydocs").ok().expect(err);
}
|
Repeat | #include <stdio.h>
void repeat(void (*f)(void), unsigned int n) {
while (n-->0)
(*f)();
}
void example() {
printf("Example\n");
}
int main(int argc, char *argv[]) {
repeat(example, 4);
return 0;
}
| fn repeat(f: impl FnMut(usize), n: usize) {
(0..n).for_each(f);
}
|
Repeat a string | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * string_repeat( int n, const char * s ) {
size_t slen = strlen(s);
char * dest = malloc(n*slen+1);
int i; char * p;
for ( i=0, p = dest; i < n; ++i, p += slen ) {
memcpy(p, s, slen);
}
*p = '\0';
return dest;
}
int main() {
char * r... | std::iter::repeat("ha").take(5).collect::<String>();
|
Reverse a string | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
const char *sa = "abcdef";
const char *su = "as⃝df̅";
int is_comb(wchar_t c)
{
if (c >= 0x300 && c <= 0x36f) return 1;
if (c >= 0x1dc0 && c <= 0x1dff) return 1;
if (c >= 0x20d0 && c <= 0x20ff) return 1;
if (c >= 0xfe20 && c <= 0xfe2f) ... | let mut buffer = b"abcdef".to_vec();
buffer.reverse();
assert_eq!(buffer, b"fedcba");
|
Reverse words in a string | #include <stdio.h>
#include <ctype.h>
void rev_print(char *s, int n)
{
for (; *s && isspace(*s); s++);
if (*s) {
char *e;
for (e = s; *e && !isspace(*e); e++);
rev_print(e, 0);
printf("%.*s%s", (int)(e - s), s, " " + n);
}
... | const TEXT: &'static str =
"---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------";
fn main() {
println!("{}",
TEXT.lines()... |
Roman numerals_Decode | #include <stdio.h>
int digits[26] = { 0, 0, 100, 500, 0, 0, 0, 0, 1, 1, 0, 50, 1000, 0, 0, 0, 0, 0, 0, 0, 5, 5, 0, 10, 0, 0 };
#define VALUE(x) digits[(~0x20 & (x)) - 'A']
int decode(const char * roman)
{
const char *bigger;
int current;
int arabic = 0;
while (*roman != '\0') {
... | struct RomanNumeral {
symbol: &'static str,
value: u32
}
const NUMERALS: [RomanNumeral; 13] = [
RomanNumeral {symbol: "M", value: 1000},
RomanNumeral {symbol: "CM", value: 900},
RomanNumeral {symbol: "D", value: 500},
RomanNumeral {symbol: "CD", value: 400},
RomanNumeral {symbol: "C", va... |
Roman numerals_Encode | #include <stdio.h>
int main() {
int arabic[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
char roman[13][3] = {"M\0", "CM\0", "D\0", "CD\0", "C\0", "XC\0", "L\0", "XL\0", "X\0", "IX\0", "V\0", "IV\0", "I\0"};
int N;
printf("Enter arabic number:\n");
scanf("%d", &N);
... | struct RomanNumeral {
symbol: &'static str,
value: u32
}
const NUMERALS: [RomanNumeral; 13] = [
RomanNumeral {symbol: "M", value: 1000},
RomanNumeral {symbol: "CM", value: 900},
RomanNumeral {symbol: "D", value: 500},
RomanNumeral {symbol: "CD", value: 400},
RomanNumeral {symbol: "C", va... |
Roots of a function | #include <math.h>
#include <stdio.h>
double f(double x)
{
return x*x*x-3.0*x*x +2.0*x;
}
double secant( double xA, double xB, double(*f)(double) )
{
double e = 1.0e-12;
double fA, fB;
double d;
int i;
int limit = 50;
fA=(*f)(xA);
for (i=0; i<limit; i++) {
fB=(*f)(xB);
... |
use roots::find_roots_cubic;
fn main() {
let roots = find_roots_cubic(1f32, -3f32, 2f32, 0f32);
println!("Result : {:?}", roots);
}
|
Roots of unity | #include <stdio.h>
#include <math.h>
int main()
{
double a, c, s, PI2 = atan2(1, 1) * 8;
int n, i;
for (n = 1; n < 10; n++) for (i = 0; i < n; i++) {
c = s = 0;
if (!i ) c = 1;
else if(n == 4 * i) s = 1;
else if(n == 2 * i) c = -1;
else if(3 * n == 4 * i) s = -1;
else
a = i * PI2 / n, c = cos(a),... | use num::Complex;
fn main() {
let n = 8;
let z = Complex::from_polar(&1.0,&(1.0*std::f64::consts::PI/n as f64));
for k in 0..=n-1 {
println!("e^{:2}πi/{} ≈ {:>14.3}",2*k,n,z.powf(2.0*k as f64));
}
}
|
Rosetta Code_Count examples |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "wren.h"
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *m... | extern crate reqwest;
extern crate url;
extern crate rustc_serialize;
use std::io::Read;
use self::url::Url;
use rustc_serialize::json::{self, Json};
pub struct Task {
page_id: u64,
pub title: String,
}
#[derive(Debug)]
enum ParseError {
Http(reqwest::Error),
Json(json::ParserError),
... |
Rosetta Code_Find unimplemented tasks |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "wren.h"
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *m... | use std::collections::{BTreeMap, HashSet};
use reqwest::Url;
use serde::Deserialize;
use serde_json::Value;
#[derive(Clone, PartialEq, Eq, Hash, Debug, Deserialize)]
pub struct Task {
#[serde(rename = "pageid")]
pub id: u64,
pub title: String,
}
#[derive(Debug)]
enum TaskParseError {
... |
Rot-13 | #include <ctype.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
static char rot13_table[UCHAR_MAX + 1];
static void init_rot13_table(void) {
static const unsigned char upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const unsigned char lower[] = "abcdefghijklmnopqrstuvwxyz";
for (int ch = '\0'; ch <=... | fn rot13(string: &str) -> String {
string.chars().map(|c| {
match c {
'a'..='m' | 'A'..='M' => ((c as u8) + 13) as char,
'n'..='z' | 'N'..='Z' => ((c as u8) - 13) as char,
_ => c
}
}).collect()
}
fn main () {
assert_eq!(rot13("abc"), "nop");
}
|
Run-length encoding | #include <stdio.h>
#include <stdlib.h>
typedef struct stream_t stream_t, *stream;
struct stream_t {
int (*get)(stream);
int (*put)(stream, int);
};
typedef struct {
int (*get)(stream);
int (*put)(stream, int);
char *string;
int pos;
} string_stream;
typedef struct {
int (*get)(stream);
int (*put)(stream... | fn encode(s: &str) -> String {
s.chars()
.map(Some)
.chain(std::iter::once(None))
.scan((0usize, '\0'), |(n, c), elem| match elem {
Some(elem) if *n == 0 || *c == elem => {
*n += 1;
*c = elem;
... |
Runge-Kutta method | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
double rk4(double(*f)(double, double), double dx, double x, double y)
{
double k1 = dx * f(x, y),
k2 = dx * f(x + dx / 2, y + k1 / 2),
k3 = dx * f(x + dx / 2, y + k2 / 2),
k4 = dx * f(x + dx, y + k3);
return y + (k1 + 2 * k2 + 2 * k3 + k4) / 6;
}
double... | fn runge_kutta4(fx: &dyn Fn(f64, f64) -> f64, x: f64, y: f64, dx: f64) -> f64 {
let k1 = dx * fx(x, y);
let k2 = dx * fx(x + dx / 2.0, y + k1 / 2.0);
let k3 = dx * fx(x + dx / 2.0, y + k2 / 2.0);
let k4 = dx * fx(x + dx, y + k3);
y + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0
}
fn f(x: f64, y: f64) -> ... |
S-expressions | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
enum { S_NONE, S_LIST, S_STRING, S_SYMBOL };
typedef struct {
int type;
size_t len;
void *buf;
} s_expr, *expr;
void whine(const char *s)
{
fprintf(stderr, "parse error before ==>%.10s\n", s);
}
expr parse_string(const char *s, char *... |
extern crate typed_arena;
use typed_arena::Arena;
use self::Error::*;
use self::SExp::*;
use self::Token::*;
use std::io;
use std::num::FpCategory;
use std::str::FromStr;
#[derive(PartialEq, Debug)]
pub enum SExp<'a> {
F64(f64),
List(&'a [SExp<'a>]),
Str(&'a str),
... |
SEDOLs | #include <stdio.h>
#include <ctype.h>
#include <string.h>
int sedol_weights[] = {1, 3, 1, 7, 3, 9};
const char *reject = "AEIOUaeiou";
int sedol_checksum(const char *sedol6)
{
int len = strlen(sedol6);
int sum = 0, i;
if ( len == 7 ) {
fprintf(stderr, "SEDOL code already checksummed? (%s)\n", sedol6);
... | fn sedol(input: &str) -> Option<String> {
let weights = vec![1, 3, 1, 7, 3, 9, 1];
let valid_chars = "0123456789BCDFGHJKLMNPQRSTVWXYZ";
if input.len() != 6 {
return None;
}
for c in input.chars() {
if !valid_chars.contains(c) {
return None;
}
}
let... |
SHA-1 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/sha.h>
int main()
{
int i;
unsigned char result[SHA_DIGEST_LENGTH];
const char *string = "Rosetta Code";
SHA1(string, strlen(string), result);
for(i = 0; i < SHA_DIGEST_LENGTH; i++)
printf("%02x%c", result[i], i < (SHA_DIGES... | use sha1::Sha1;
fn main() {
let mut hash_msg = Sha1::new();
hash_msg.update(b"Rosetta Code");
println!("{}", hash_msg.digest().to_string());
}
|
SHA-256 | #include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
int main (void) {
const char *s = "Rosetta code";
unsigned char *d = SHA256(s, strlen(s), 0);
int i;
for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
printf("%02x", d[i]);
putchar('\n');
return 0;
}
| use sha2::{Digest, Sha256};
fn hex_string(input: &[u8]) -> String {
input.as_ref().iter().map(|b| format!("{:x}", b)).collect()
}
fn main() {
let mut hasher = Sha256::new();
hasher.update(b"Rosetta code");
let result = hasher.finalize();
let hex = hex_string(&result);
assert... |
Search a list | #include <stdio.h>
#include <string.h>
const char *haystack[] = {
"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie",
"Bush", "Boz", "Zag", NULL
};
int search_needle(const char *needle, const char **hs)
{
int i = 0;
while( hs[i] != NULL ) {
if ( strcmp(hs[i], needle) == 0 ) return i;
i++;
... | fn main() {
let haystack=vec!["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie",
"Bush", "Boz", "Zag"];
println!("First occurence of 'Bush' at {:?}",haystack.iter().position(|s| *s=="Bush"));
println!("Last occurence of 'Bush' at {:?}",haystack.iter().rposition(|s| *s=="... |
Secure temporary file | #include <stdlib.h>
#include <stdio.h>
int main(void)
{
FILE *fh = tmpfile();
fclose(fh);
return 0;
}
|
use tempfile::tempfile;
fn main() {
let fh = tempfile();
println!("{:?}", fh);
}
|
Semiprime | #include <stdio.h>
int semiprime(int n)
{
int p, f = 0;
for (p = 2; f < 2 && p*p <= n; p++)
while (0 == n % p)
n /= p, f++;
return f + (n > 1) == 2;
}
int main(void)
{
int i;
for (i = 2; i < 100; i++)
if (semiprime(i)) printf(" %d", i);
putchar('\n');
return 0;
}
| extern crate primal;
fn isqrt(n: usize) -> usize {
(n as f64).sqrt() as usize
}
fn is_semiprime(mut n: usize) -> bool {
let root = isqrt(n) + 1;
let primes1 = primal::Sieve::new(root);
let mut count = 0;
for i in primes1.primes_from(2).take_while(|&x| x < root) {
while n % i == 0 {
... |
Semordnilap | #include <stdio.h>
#include <stdlib.h>
#include <alloca.h>
#include <string.h>
static void reverse(char *s, int len)
{
int i, j;
char tmp;
for (i = 0, j = len - 1; i < len / 2; ++i, --j)
tmp = s[i], s[i] = s[j], s[j] = tmp;
}
static int strsort(const void *s1, const void *s2)
{
return strcm... | use std::collections::HashSet;
use std::fs::File;
use std::io::{self, BufRead};
use std::iter::FromIterator;
fn semordnilap(filename: &str) -> std::io::Result<()> {
let file = File::open(filename)?;
let mut seen = HashSet::new();
let mut count = 0;
for line in io::BufReader::new(file).lines() {
... |
Sequence of non-squares | #include <math.h>
#include <stdio.h>
#include <assert.h>
int nonsqr(int n) {
return n + (int)(0.5 + sqrt(n));
}
int main() {
int i;
for (i = 1; i < 23; i++)
printf("%d ", nonsqr(i));
printf("\n");
for (i = 1; i < 1000000; i++) {
double j = sqrt(nonsqr(i));
... | fn f(n: i64) -> i64 {
n + (0.5 + (n as f64).sqrt()) as i64
}
fn is_sqr(n: i64) -> bool {
let a = (n as f64).sqrt() as i64;
n == a * a || n == (a+1) * (a+1) || n == (a-1) * (a-1)
}
fn main() {
println!( "{:?}", (1..23).map(|n| f(n)).collect::<Vec<i64>>() );
let count = (1..1_000_000).map(|n| f(n))... |
Sequence of primes by trial division | #include<stdio.h>
int isPrime(unsigned int n)
{
unsigned int num;
if ( n < 2||!(n & 1))
return n == 2;
for (num = 3; num <= n/num; num += 2)
if (!(n % num))
return 0;
return 1;
}
int main()
{
unsigned int l,u,i,sum=0;
printf("Enter lower and upper bounds: ");
scanf("%ld%ld",&l,&u);
for(i=l;i<=... | fn is_prime(number: u32) -> bool {
#[allow(clippy::cast_precision_loss)]
let limit = (number as f32).sqrt() as u32 + 1;
!(number < 2 || (2..limit).any(|x| number % x == 0))
}
fn main() {
println!(
"Primes below 100:\n{:?}",
(0_u32..100).fold(vec![], |mut acc, number| {
... |
Set | #include <stdio.h>
typedef unsigned int set_t;
void show_set(set_t x, const char *name)
{
int i;
printf("%s is:", name);
for (i = 0; (1U << i) <= x; i++)
if (x & (1U << i))
printf(" %d", i);
putchar('\n');
}
int main(void)
{
int i;
set_t a, b, c;
a = 0;
for (i = 0; i < 10; i += 3)
a |= (1U << i);... | use std::collections::HashSet;
fn main() {
let a = vec![1, 3, 4].into_iter().collect::<HashSet<i32>>();
let b = vec![3, 5, 6].into_iter().collect::<HashSet<i32>>();
println!("Set A: {:?}", a.iter().collect::<Vec<_>>());
println!("Set B: {:?}", b.iter().collect::<Vec<_>>());
println!("Does A contain 4? {}", ... |
Set puzzle | #include <stdio.h>
#include <stdlib.h>
char *names[4][3] = {
{ "red", "green", "purple" },
{ "oval", "squiggle", "diamond" },
{ "one", "two", "three" },
{ "solid", "open", "striped" }
};
int set[81][81];
void init_sets(void)
{
int i, j, t, a, b;
for (i = 0; i < 81; i++) {
for (j = 0; j < 81; j++) {
for (t... | use itertools::Itertools;
use rand::Rng;
const DECK_SIZE: usize = 81;
const NUM_ATTRIBUTES: usize = 4;
const ATTRIBUTES: [&[&str]; NUM_ATTRIBUTES] = [
&["red", "green", "purple"],
&["one", "two", "three"],
&["oval", "squiggle", "diamond"],
&["solid", "open", "striped"],
];
fn get_random_card_indexes(n... |
Short-circuit evaluation | #include <stdio.h>
#include <stdbool.h>
bool a(bool in)
{
printf("I am a\n");
return in;
}
bool b(bool in)
{
printf("I am b\n");
return in;
}
#define TEST(X,Y,O) \
do { \
x = a(X) O b(Y); \
printf(#X " " #O " " #Y " = %s\n\n", x ? "true" : "false"); \
} while(false);
int main()
... | fn a(foo: bool) -> bool {
println!("a");
foo
}
fn b(foo: bool) -> bool {
println!("b");
foo
}
fn main() {
for i in vec![true, false] {
for j in vec![true, false] {
println!("{} and {} == {}", i, j, a(i) && b(j));
println!("{} or {} == {}", i, j, a(i) || b(j));
... |
Show ASCII table | #include <stdio.h>
int main() {
int i, j;
char k[4];
for (i = 0; i < 16; ++i) {
for (j = 32 + i; j < 128; j += 16) {
switch (j) {
default: sprintf(k, "%c", j); break;
case 32: sprintf(k, "Spc"); break;
case 127: sprintf(k, "Del"); break;... | fn main() {
for i in 0u8..16 {
for j in ((32+i)..128).step_by(16) {
let k = (j as char).to_string();
print!("{:3} : {:<3} ", j, match j {
32 => "Spc",
127 => "Del",
_ => &k,
});
}
println!();
}
}
|
Show the (decimal) value of a number of 1s appended with a 3, then squared | #include <stdio.h>
#include <stdint.h>
uint64_t ones_plus_three(uint64_t ones) {
uint64_t r = 0;
while (ones--) r = r*10 + 1;
return r*10 + 3;
}
int main() {
uint64_t n;
for (n=0; n<8; n++) {
uint64_t x = ones_plus_three(n);
printf("%8lu^2 = %15lu\n", x, x*x);
}
return 0;
}... | fn main() {
let mut big_squares : Vec<u64> = Vec::new( ) ;
let mut numberstrings : Vec<String> = Vec::new( ) ;
for n in 0..8 {
let mut numberstring : String = String::new( ) ;
for i in 0..=n {
if i != 0 {
numberstring.push( '1' ) ;
}
}
numberstring.push('... |
Show the epoch | #include <time.h>
#include <stdio.h>
int main() {
time_t t = 0;
printf("%s", asctime(gmtime(&t)));
return 0;
}
| extern crate time;
use time::{at_utc, Timespec};
fn main() {
let epoch = at_utc(Timespec::new(0, 0));
println!("{}", epoch.asctime());
}
|
Sierpinski carpet | #include <stdio.h>
int main()
{
int i, j, dim, d;
int depth = 3;
for (i = 0, dim = 1; i < depth; i++, dim *= 3);
for (i = 0; i < dim; i++) {
for (j = 0; j < dim; j++) {
for (d = dim / 3; d; d /= 3)
if ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)
break;
printf(d ? " " : "##");
}
printf... | fn main() {
for i in 0..4 {
println!("\nN={}", i);
println!("{}", sierpinski_carpet(i));
}
}
fn sierpinski_carpet(n: u32) -> String {
let mut carpet = vec!["#".to_string()];
for _ in 0..n {
let mut top: Vec<_> = carpet.iter().map(|x| x.repeat(3)).collect();
let middle: V... |
Sierpinski triangle | #include <stdio.h>
#define SIZE (1 << 4)
int main()
{
int x, y, i;
for (y = SIZE - 1; y >= 0; y--, putchar('\n')) {
for (i = 0; i < y; i++) putchar(' ');
for (x = 0; x + y < SIZE; x++)
printf((x & y) ? " " : "* ");
}
return 0;
}
| use std::iter::repeat;
fn sierpinski(order: usize) {
let mut triangle = vec!["*".to_string()];
for i in 0..order {
let space = repeat(' ').take(2_usize.pow(i as u32)).collect::<String>();
let mut d = triangle.clone();
d.iter_mut().for_each(|r| {
let new_r... |
Sieve of Eratosthenes | #include <stdlib.h>
#include <math.h>
char*
eratosthenes(int n, int *c)
{
char* sieve;
int i, j, m;
if(n < 2)
return NULL;
*c = n-1;
m = (int) sqrt((double) n);
sieve = calloc(n+1,sizeof(char));
sieve[0] = 1;
sieve[1] = 1;
for(i = 2; i <= m; i++)
if(!sieve[i])
for (j = i*i; j <= n; j += i)
... | fn primes(n: usize) -> impl Iterator<Item = usize> {
const START: usize = 2;
if n < START {
Vec::new()
} else {
let mut is_prime = vec![true; n + 1 - START];
let limit = (n as f64).sqrt() as usize;
for i in START..limit + 1 {
let mut it = is_prime[i - START..].ite... |
Simple windowed application | #include <stdio.h>
#include <gtk/gtk.h>
const gchar *clickme = "Click Me";
guint counter = 0;
#define MAXLEN 64
void clickedme(GtkButton *o, gpointer d)
{
GtkLabel *l = GTK_LABEL(d);
char nt[MAXLEN];
counter++;
snprintf(nt, MAXLEN, "You clicked me %d times", counter);
gtk_label_set_text(l, nt... | use iced::{
button, Button, Column, Element, Length,
Text, Sandbox, Settings, Space,
};
#[derive(Debug, Copy, Clone)]
struct Pressed;
struct Simple {
value: i32,
button: button::State,
}
impl Sandbox for Simple {
type Message = Pressed;
fn new() -> Simple {
Simple {
value... |
Singly-linked list_Element definition | struct link {
struct link *next;
int data;
};
| struct Node<T> {
elem: T,
next: Option<Box<Node<T>>>,
}
|
Singly-linked list_Element insertion | void insert_append (struct link *anchor, struct link *newlink) {
newlink->next = anchor->next;
anchor->next = newlink;
}
| impl<T> List<T> {
pub fn new() -> Self {
List { head: None }
}
pub fn push(&mut self, elem: T) {
let new_node = Box::new(Node {
elem: elem,
next: self.head.take(),
});
self.head = Some(new_node);
}
|
Singly-linked list_Traversal | struct link *first;
struct link *iter;
for(iter = first; iter != NULL; iter = iter->next) {
}
|
pub struct IntoIter<T>(List<T>);
impl<T> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.0.head.take().map(|node| {
let node = *node;
self.0.head = node.next;
node.elem
})
}
}
pub struct Iter<'a, T: '... |
Sleep | #include <stdio.h>
#include <unistd.h>
int main()
{
unsigned int seconds;
scanf("%u", &seconds);
printf("Sleeping...\n");
sleep(seconds);
printf("Awake!\n");
return 0;
}
| use std::{io, time, thread};
fn main() {
println!("How long should we sleep in milliseconds?");
let mut sleep_string = String::new();
io::stdin().read_line(&mut sleep_string)
.expect("Failed to read line");
let sleep_timer: u64 = sleep_string.trim()
... |
Smith numbers | #include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
int numPrimeFactors(unsigned x) {
unsigned p = 2;
int pf = 0;
if (x == 1)
return 1;
else {
while (true) {
if (!(x % p)) {
pf++;
x /= p;
if (x == 1)
... | fn main () {
let primes = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
let mut solution = Vec::new();
let mut number;
for i in 4..10000 {
let mut prime_factors = Vec::new();
number = i;
for j in &primes {
... |
Sockets | #include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
const char *msg = "hello socket world";
int main()
{
int i, sock, len, slen;
struct addrinfo hints, *addrs;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_sockt... | use std::io::prelude::*;
use std::net::TcpStream;
fn main() {
let mut my_stream = TcpStream::connect("127.0.0.1:256").unwrap();
let _ = my_stream.write(b"hello socket world");
}
|
Soloway's recurring rainfall | #include <stdio.h>
int main(int argc, char **argv)
{
(void)argc;
(void)argv;
float currentAverage = 0;
unsigned int currentEntryNumber = 0;
for (;;)
{
int ret, entry;
printf("Enter rainfall int, 99999 to quit: ");
ret = scanf("%d", &entry);
if (ret)
{
if (entry == 99999)
{
printf(... | fn main() {
let mut current_average:f32 = 0.0;
let mut current_entry_number:u32 = 0;
loop
{
let current_entry;
println!("Enter rainfall int, 99999 to quit: ");
let mut input_text = String::new();
std::io::stdin().read_line(&mut input_text).expect("Failed to read from stdin");
let trimmed = input_tex... |
Sort a list of object identifiers | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct oid_tag {
char* str_;
int* numbers_;
int length_;
} oid;
void oid_destroy(oid* p) {
if (p != 0) {
free(p->str_);
free(p->numbers_);
free(p);
}
}
int char_count(const char* str, char ch) {
int co... | fn split(s: &str) -> impl Iterator<Item = u64> + '_ {
s.split('.').map(|x| x.parse().unwrap())
}
fn main() {
let mut oids = vec![
"1.3.6.1.4.1.11.2.17.19.3.4.0.10",
"1.3.6.1.4.1.11.2.17.5.2.0.79",
"1.3.6.1.4.1.11.2.17.19.3.4.0.4",
"1.3.6.1.4.1.11150.3.4.0.1",
"1.3.6.1.4.... |
Sort an array of composite structures | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct twoStringsStruct {
char * key, *value;
} sTwoStrings;
int ord( char v )
{
static char *dgts = "012345679";
char *cp;
for (cp=dgts; v != *cp; cp++);
return (cp-dgts);
}
int cmprStrgs(const sTwoStrings *s1,const sTwoStrings *... | use std::cmp::Ordering;
#[derive(Debug)]
struct Employee {
name: String,
category: String,
}
impl Employee {
fn new(name: &str, category: &str) -> Self {
Employee {
name: name.into(),
category: category.into(),
}
}
}
impl PartialEq for Employee {
fn eq(&sel... |
Sort an integer array | #include <stdlib.h>
#include <stdio.h>
int intcmp(const void *aa, const void *bb)
{
const int *a = aa, *b = bb;
return (*a < *b) ? -1 : (*a > *b);
}
int main()
{
int nums[5] = {2,4,3,1,2};
qsort(nums, 5, sizeof(int), intcmp);
printf("result: %d %d %d %d %d\n",
nums[0], nums[1], nums[2],... | fn main() {
let mut a = vec!(9, 8, 7, 6, 5, 4, 3, 2, 1, 0);
a.sort();
println!("{:?}", a);
}
|
Sort disjoint sublist | #include <stdio.h>
void bubble_sort(int *idx, int n_idx, int *buf)
{
int i, j, tmp;
#define for_ij for (i = 0; i < n_idx; i++) for (j = i + 1; j < n_idx; j++)
#define sort(a, b) if (a < b) { tmp = a; a = b; b = tmp;}
for_ij { sort(idx[j], idx[i]); }
for_ij { sort(buf[idx[j]], buf[idx[... | use std::collections::BTreeSet;
fn disjoint_sort(array: &mut [impl Ord], indices: &[usize]) {
let mut sorted = indices.to_owned();
sorted.sort_unstable_by_key(|k| &array[*k]);
indices
.iter()
.zip(sorted.iter())
.map(|(&a, &b)| if a > b { (b, a) } else { (a, b) })
.collect::... |
Sort numbers lexicographically | #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compareStrings(const void *a, const void *b) {
const char **aa = (const char **)a;
const char **bb = (const char **)b;
return strcmp(*aa, *bb);
}
void lexOrder(int n, int *ints) {
char **strs;
int i, first = 1, last =... | fn lex_sorted_vector(num: i32) -> Vec<i32> {
let (min, max) = if num >= 1 { (1, num) } else { (num, 1) };
let mut str: Vec<String> = (min..=max).map(|i| i.to_string()).collect();
str.sort();
str.iter().map(|s| s.parse::<i32>().unwrap()).collect()
}
fn main() {
for n in &[0, 5, 13, 21, -22] {
... |
Sort three variables | #include<string.h>
#include<stdlib.h>
#include<stdio.h>
#define MAX 3
int main()
{
char values[MAX][100],tempStr[100];
int i,j,isString=0;
double val[MAX],temp;
for(i=0;i<MAX;i++){
printf("Enter %d%s value : ",i+1,(i==0)?"st":((i==1)?"nd":"rd"));
fgets(values[i],100,stdin);
for(j=0;values[... | fn main() {
let mut array = [5, 1, 3];
array.sort();
println!("Sorted: {:?}", array);
array.sort_by(|a, b| b.cmp(a));
println!("Reverse sorted: {:?}", array);
}
|
Sort using a custom comparator | #include <stdlib.h>
#include <string.h>
#include <strings.h>
int mycmp(const void *s1, const void *s2)
{
const char *l = *(const char **)s1, *r = *(const char **)s2;
size_t ll = strlen(l), lr = strlen(r);
if (ll > lr) return -1;
if (ll < lr) return 1;
return strcasecmp(l, r);
}
int main()
{
... | fn main() {
let mut words = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"];
words.sort_by(|l, r| Ord::cmp(&r.len(), &l.len()).then(Ord::cmp(l, r)));
println!("{:?}", words);
}
|
Sorting algorithms_Bogosort | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool is_sorted(int *a, int n)
{
while ( --n >= 1 ) {
if ( a[n] < a[n-1] ) return false;
}
return true;
}
void shuffle(int *a, int n)
{
int i, t, r;
for(i=0; i < n; i++) {
t = a[i];
r = rand() % n;
a[i] = a[r];
a[r] = t;
}
}
v... | extern crate rand;
use rand::Rng;
fn bogosort_by<T,F>(order: F, coll: &mut [T])
where F: Fn(&T, &T) -> bool
{
let mut rng = rand::thread_rng();
while !is_sorted_by(&order, coll) {
rng.shuffle(coll);
}
}
#[inline]
fn is_sorted_by<T,F>(order: F, coll: &[T]) -> bool
where F: Fn(&T,&T) -> bool... |
Sorting algorithms_Bubble sort | #include <stdio.h>
void bubble_sort (int *a, int n) {
int i, t, j = n, s = 1;
while (s) {
s = 0;
for (i = 1; i < j; i++) {
if (a[i] < a[i - 1]) {
t = a[i];
a[i] = a[i - 1];
a[i - 1] = t;
s = 1;
}
}
... | fn bubble_sort<T: Ord>(values: &mut[T]) {
let mut n = values.len();
let mut swapped = true;
while swapped {
swapped = false;
for i in 1..n {
if values[i - 1] > values[i] {
values.swap(i - 1, i);
swapped = true;
}
}
n ... |
Sorting algorithms_Cocktail sort | #include <stdio.h>
void swap(int *x, int *y) {
if(x == y)
return;
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
void cocktailsort(int *a, size_t n) {
while(1) {
char flag;
size_t start[2] = {1, n - 1},
end[2] = {n, 0},
inc[2] = {1, -1};
for(int it = 0; it < 2; ++it) {
flag = 1;
for(int i = start[i... | fn cocktail_sort<T: PartialOrd>(a: &mut [T]) {
let len = a.len();
loop {
let mut swapped = false;
let mut i = 0;
while i + 1 < len {
if a[i] > a[i + 1] {
a.swap(i, i + 1);
swapped = true;
}
i += 1;
}
if s... |
Sorting algorithms_Comb sort | void Combsort11(double a[], int nElements)
{
int i, j, gap, swapped = 1;
double temp;
gap = nElements;
while (gap > 1 || swapped == 1)
{
gap = gap * 10 / 13;
if (gap == 9 || gap == 10) gap = 11;
if (gap < 1) gap = 1;
swapped = 0;
for (i = 0, j = gap; j < nElements; i++, j++)
{
i... | fn comb_sort<T: PartialOrd>(a: &mut [T]) {
let len = a.len();
let mut gap = len;
let mut swapped = true;
while gap > 1 || swapped {
gap = (4 * gap) / 5;
if gap < 1 {
gap = 1;
}
let mut i = 0;
swapped = false;
while i + gap < len {
i... |
Sorting algorithms_Counting sort | #include <stdio.h>
#include <stdlib.h>
void counting_sort_mm(int *array, int n, int min, int max)
{
int i, j, z;
int range = max - min + 1;
int *count = malloc(range * sizeof(*array));
for(i = 0; i < range; i++) count[i] = 0;
for(i = 0; i < n; i++) count[ array[i] - min ]++;
for(i = min, z = 0; i <= max... | fn counting_sort(
mut data: Vec<usize>,
min: usize,
max: usize,
) -> Vec<usize> {
let mut count: Vec<usize> = Vec::with_capacity(data.len());
count.resize(data.len(), 0);
for num in &data {
count[num - min] = count[num - min] + 1;
}
let mut z: usize = 0;
for i in min..m... |
Sorting algorithms_Gnome sort | void gnome_sort(int *a, int n)
{
int i=1, j=2, t;
# define swap(i, j) { t = a[i]; a[i] = a[j]; a[j] = t; }
while(i < n) {
if (a[i - 1] > a[i]) {
swap(i - 1, i);
if (--i) continue;
}
i = j++;
}
# undef swap
}
| fn gnome_sort<T: PartialOrd>(a: &mut [T]) {
let len = a.len();
let mut i: usize = 1;
let mut j: usize = 2;
while i < len {
if a[i - 1] <= a[i] {
i = j;
j += 1;
} else {
a.swap(i - 1, i);
i -= 1;
if i == 0 {
... |
Sorting algorithms_Heapsort | #include <stdio.h>
int max (int *a, int n, int i, int j, int k) {
int m = i;
if (j < n && a[j] > a[m]) {
m = j;
}
if (k < n && a[k] > a[m]) {
m = k;
}
return m;
}
void downheap (int *a, int n, int i) {
while (1) {
int j = max(a, n, i, 2 * i + 1, 2 * i + 2);
... | fn main() {
let mut v = [4, 6, 8, 1, 0, 3, 2, 2, 9, 5];
heap_sort(&mut v, |x, y| x < y);
println!("{:?}", v);
}
fn heap_sort<T, F>(array: &mut [T], order: F)
where
F: Fn(&T, &T) -> bool,
{
let len = array.len();
for start in (0..len / 2).rev() {
shift_down(array, &order, start, len... |
Sorting algorithms_Insertion sort | #include <stdio.h>
void insertion_sort(int*, const size_t);
void insertion_sort(int *a, const size_t n) {
for(size_t i = 1; i < n; ++i) {
int key = a[i];
size_t j = i;
while( (j > 0) && (key < a[j - 1]) ) {
a[j] = a[j - 1];
--j;
}
a[j] = key;
}
}
int main (int argc, char** argv) {
int a[] = {... | fn insertion_sort<T: std::cmp::Ord>(arr: &mut [T]) {
for i in 1..arr.len() {
let mut j = i;
while j > 0 && arr[j] < arr[j-1] {
arr.swap(j, j-1);
j = j-1;
}
}
}
|
Sorting algorithms_Merge sort | #include <stdio.h>
#include <stdlib.h>
void merge (int *a, int n, int m) {
int i, j, k;
int *x = malloc(n * sizeof (int));
for (i = 0, j = m, k = 0; k < n; k++) {
x[k] = j == n ? a[i++]
: i == m ? a[j++]
: a[j] < a[i] ? a[j++]
: a[i++];... | pub fn merge_sort1<T: Copy + Ord>(v: &mut [T]) {
sort(v, &mut Vec::new());
fn sort<T: Copy + Ord>(v: &mut [T], t: &mut Vec<T>) {
match v.len() {
0 | 1 => (),
n => {
if t.is_empty() {
t.reserve_exact(n);
t.resiz... |
Sorting algorithms_Quicksort | #include <stdio.h>
void quicksort(int *A, int len);
int main (void) {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");
quicksort(a, n);
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
... | fn main() {
println!("Sort numbers in descending order");
let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1];
println!("Before: {:?}", numbers);
quick_sort(&mut numbers, &|x,y| x > y);
println!("After: {:?}\n", numbers);
println!("Sort strings alphabetically");
let mut strings = ["be... |
Sorting algorithms_Radix sort | #include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <time.h>
#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)
#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));
static void swap(unsigned *a, unsigned *b) {
unsigned tmp = *a;
*a = *b;
*b = tmp;
}
static void rad_sort_u(un... | fn merge(in1: &[i32], in2: &[i32], out: &mut [i32]) {
let (left, right) = out.split_at_mut(in1.len());
left.clone_from_slice(in1);
right.clone_from_slice(in2);
}
fn radix_sort(data: &mut [i32]) {
for bit in 0..31 {
let (small, big): (Vec<_>, Vec<_>) = data.iter().partition(|&... |
Sorting algorithms_Selection sort | #include <stdio.h>
void selection_sort (int *a, int n) {
int i, j, m, t;
for (i = 0; i < n; i++) {
for (j = i, m = i; j < n; j++) {
if (a[j] < a[m]) {
m = j;
}
}
t = a[i];
a[i] = a[m];
a[m] = t;
}
}
int main () {
int a[] =... | fn selection_sort(array: &mut [i32]) {
let mut min;
for i in 0..array.len() {
min = i;
for j in (i+1)..array.len() {
if array[j] < array[min] {
min = j;
}
}
let tmp = array[i];
array[i] = array[min];
array[min] = tmp;
... |
Sorting algorithms_Sleep sort | >>>>>,----------[++++++++
++[->+>+<<]>+>[-<<+>>]+++
+++++[-<------>]>>+>,----
------<<+[->>>>>+<<<<<]>>
]>>>[<<<<[<<<[->>+<<[->+>
[-]<<]]>[-<+>]>[-<<<.>>>>
->>>>>[>>>>>]<-<<<<[<<<<<
]+<]<<<<]>>>>>[>>>>>]<]
| use std::thread;
fn sleepsort<I: Iterator<Item=u32>>(nums: I) {
let threads: Vec<_> = nums.map(|n|
thread::spawn(move || {
thread::sleep_ms(n);
println!("{}", n); })).collect();
for t in threads { t.join(); }
}
fn main() {
sleepsort(std::env::args().skip(1).map(|s| s.parse(... |
Spiral matrix | #include <stdio.h>
#include <stdlib.h>
#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]
int main(int c, char **v)
{
int i, j, m = 0, n = 0;
if (c >= 2) m = atoi(v[1]);
if (c >= 3) n = atoi(v[2]);
if (m <= 0) m = 5;
if (n <= 0) n = m;
int **s = calloc(1, sizeof(int *) * m + sizeof(int) * ... | const VECTORS: [(isize, isize); 4] = [(1, 0), (0, 1), (-1, 0), (0, -1)];
pub fn spiral_matrix(size: usize) -> Vec<Vec<u32>> {
let mut matrix = vec![vec![0; size]; size];
let mut movement = VECTORS.iter().cycle();
let (mut x, mut y, mut n) = (-1, 0, 1..);
for (move_x, move_y) in std::iter::once(size)
... |
Split a character string based on change of character | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *split(char *str);
int main(int argc,char **argv)
{
char input[13]="gHHH5YY++
printf("%s\n",split(input));
}
char *split(char *str)
{
char last=*str,*result=malloc(3*strlen(str)),*counter=result;
for (char *c=str;*c;c++) {
if (*c!=last) {
strcpy(c... | fn splitter(string: &str) -> String {
let chars: Vec<_> = string.chars().collect();
let mut result = Vec::new();
let mut last_mismatch = 0;
for i in 0..chars.len() {
if chars.len() == 1 {
return chars[0..1].iter().collect();
}
if i > 0 && chars[i-1] != chars[i] {
... |
Square but not cube | #include <stdio.h>
#include <math.h>
int main() {
int n = 1, count = 0, sq, cr;
for ( ; count < 30; ++n) {
sq = n * n;
cr = (int)cbrt((double)sq);
if (cr * cr * cr != sq) {
count++;
printf("%d\n", sq);
}
else {
printf("%d is square and... | fn main() {
let mut s = 1;
let mut c = 1;
let mut cube = 1;
let mut n = 0;
while n < 30 {
let square = s * s;
while cube < square {
c += 1;
cube = c * c * c;
}
if cube == square {
println!("{} is a square and a cube.", square);
... |
Stack | #include <stdio.h>
#include <stdlib.h>
#define DECL_STACK_TYPE(type, name) \
typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name; \
stk_##name stk_##name##_create(size_t init_size) { \
stk_##name s; if (!init_size) init_size = 4; \
s = malloc(sizeof(struct stk_##name##_t)); \
if (!s) r... | fn main() {
let mut stack = Vec::new();
stack.push("Element1");
stack.push("Element2");
stack.push("Element3");
assert_eq!(Some(&"Element3"), stack.last());
assert_eq!(Some("Element3"), stack.pop());
assert_eq!(Some("Element2"), stack.pop());
assert_eq!(Some("Element1"), stack.pop());
... |
Stair-climbing puzzle | void step_up(void)
{
while (!step()) {
step_up();
}
}
| fn step_up() {
while !step() {
step_up();
}
}
|
Statistics_Basic | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdint.h>
#define n_bins 10
double rand01() { return rand() / (RAND_MAX + 1.0); }
double avg(int count, double *stddev, int *hist)
{
double x[count];
double m = 0, s = 0;
for (int i = 0; i < n_bins; i++) hist[i] = 0;
for (int i = 0; i < count; i... | #![feature(iter_arith)]
extern crate rand;
use rand::distributions::{IndependentSample, Range};
pub fn mean(data: &[f32]) -> Option<f32> {
if data.is_empty() {
None
} else {
let sum: f32 = data.iter().sum();
Some(sum / data.len() as f32)
}
}
pub fn variance(data: &[f32]) -> Option... |
String append | #include<stdio.h>
#include<string.h>
int main()
{
char str[24]="Good Morning";
char *cstr=" to all";
char *cstr2=" !!!";
int x=0;
if(sizeof(str)>strlen(str)+strlen(cstr)+strlen(cstr2))
{
strcat(str,cstr);
x=strlen(... | use std::ops::Add;
fn main(){
let hello = String::from("Hello world");
println!("{}", hello.add("!!!!"));
}
|
String case |
#include <ctype.h>
#include <stdio.h>
void str_toupper(char *s)
{
while(*s)
{
*s=toupper(*s);
s++;
}
}
void str_tolower(char *s)
{
while(*s)
{
*s=tolower(*s);
s++;
}
}
int main(int argc, char *argv[])
{
char t[255]="alphaBETA";
str_toupper(t);
p... | fn main() {
println!("{}", "jalapeño".to_uppercase());
println!("{}", "JALAPEÑO".to_lowercase());
}
|
String concatenation | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *sconcat(const char *s1, const char *s2)
{
char *s0 = malloc(strlen(s1)+strlen(s2)+1);
strcpy(s0, s1);
strcat(s0, s2);
return s0;
}
int main()
{
const char *s = "hello";
char *s2;
printf("%s literal\n", s);
printf("%s%s\n", s,... | fn main() {
let s = "hello".to_owned();
println!("{}", s);
let s1 = s + " world";
println!("{}", s1);
}
|
String interpolation (included) | #include <stdio.h>
int main() {
const char *extra = "little";
printf("Mary had a %s lamb.\n", extra);
return 0;
}
| fn main() {
println!("Mary had a {} lamb", "little");
println!("{1} had a {0} lamb", "little", "Mary");
println!("{name} had a {adj} lamb", adj="little", name="Mary");
}
|
String length | #include <string.h>
int main(void)
{
const char *string = "Hello, world!";
size_t length = strlen(string);
return 0;
}
| fn main() {
let s = "文字化け";
println!("Character length: {}", s.chars().count());
}
|
String matching | #include <string.h>
#include <stdio.h>
int startsWith(const char* container, const char* target)
{
size_t clen = strlen(container), tlen = strlen(target);
if (clen < tlen)
return 0;
return strncmp(container, target, tlen) == 0;
}
int endsWith(const char* container, const char* target)
{
size_t clen = strl... | fn print_match(possible_match: Option<usize>) {
match possible_match {
Some(match_pos) => println!("Found match at pos {}", match_pos),
None => println!("Did not find any matches")
}
}
fn main() {
let s1 = "abcd";
let s2 = "abab";
let s3 = "ab";
assert!(s1.starts_with(... |
String prepend | #include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char str[100]="my String";
char *cstr="Changed ";
char *dup;
sprintf(str,"%s%s",cstr,(dup=strdup(str)));
free(dup);
printf("%s\n",str);
return 0;
}
| let mut s = "World".to_string();
s.insert_str(0, "Hello ");
println!("{}", s);
|
Strip a set of characters from a string | #include <string.h>
#include <stdio.h>
#include <stdlib.h>
char *strip_chars(const char *string, const char *chars)
{
char * newstr = malloc(strlen(string) + 1);
int counter = 0;
for ( ; *string; string++) {
if (!strchr(chars, *string)) {
newstr[ counter ] = *string;
++ counter;
}
}
... | fn strip_characters(original : &str, to_strip : &str) -> String {
let mut result = String::new();
for c in original.chars() {
if !to_strip.contains(c) {
result.push(c);
}
}
result
}
|
Strip comments from a string | #include<stdio.h>
int main()
{
char ch, str[100];
int i;
do{
printf("\nEnter the string :");
fgets(str,100,stdin);
for(i=0;str[i]!=00;i++)
{
if(str[i]=='#'||str[i]==';')
{
str[i]=00;
break;
}
}
printf("\nThe modified string is : %s",str);
printf("\nDo you want to repeat (y/n): ");
... | fn strip_comment<'a>(input: &'a str, markers: &[char]) -> &'a str {
input
.find(markers)
.map(|idx| &input[..idx])
.unwrap_or(input)
.trim()
}
fn main() {
println!("{:?}", strip_comment("apples, pears # and bananas", &['#', ';']));
println!("{:?}", strip_comment("apples, pea... |
Strip whitespace from a string_Top and tail | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char *rtrim(const char *s)
{
while( isspace(*s) || !isprint(*s) ) ++s;
return strdup(s);
}
char *ltrim(const char *s)
{
char *r = strdup(s);
if (r != NULL)
{
char *fr = r + strlen(s) - 1;
while( (isspace(*fr) || !isprint(*... | fn main() {
let spaces = " \t\n\x0B\x0C\r \u{A0} \u{2000}\u{3000}";
let string_with_spaces = spaces.to_owned() + "String without spaces" + spaces;
assert_eq!(string_with_spaces.trim(), "String without spaces");
assert_eq!(string_with_spaces.trim_left(), "String without spaces".to_owned() + spaces);
... |
Substring |
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void putm(char* string, size_t m)
{
while(*string && m--)
putchar(*string++);
}
int main(void)
{
char string[] =
"Programs for other encodings (such as 8-bit ASCII, or EUC-JP)."
int n = 3;
... | let s = "abc文字化けdef";
let n = 2;
let m = 3;
println!("{}", s.chars().skip(n).take(m).collect::<String>());
println!("{}", s.chars().skip(n).collect::<String>());
println!("{}", s.chars().rev().skip(1).collect::<String>());
let cpos = s.find('b').unwrap();
println!("{}", s[cpos..].chars().take(m)... |
Subtractive generator | #include<stdio.h>
#define MOD 1000000000
int state[55], si = 0, sj = 0;
int subrand();
void subrand_seed(int p1)
{
int i, j, p2 = 1;
state[0] = p1 % MOD;
for (i = 1, j = 21; i < 55; i++, j += 21) {
if (j >= 55) j -= 55;
state[j] = p2;
if ((p2 = p1 - p2) < 0) p2 += MOD;
p1 = state[j];
}
si = 0;
sj = 24... | struct SubtractiveGenerator {
modulo: i32,
offsets: (u32, u32),
state: Vec<i32>,
position: usize,
}
impl SubtractiveGenerator {
fn new(modulo: i32, first_offset: u32, second_offset: u32) -> Self {
let state_size: usize = first_offset.try_into().unwrap()... |
Sudoku | #include <stdio.h>
void show(int *x)
{
int i, j;
for (i = 0; i < 9; i++) {
if (!(i % 3)) putchar('\n');
for (j = 0; j < 9; j++)
printf(j % 3 ? "%2d" : "%3d", *x++);
putchar('\n');
}
}
int trycell(int *x, int pos)
{
int row = pos / 9;
int col = pos % 9;
int i, j, used = 0;
if (pos == 81) return 1;
if... | type Sudoku = [u8; 81];
fn is_valid(val: u8, x: usize, y: usize, sudoku_ar: &mut Sudoku) -> bool {
(0..9).all(|i| sudoku_ar[y * 9 + i] != val && sudoku_ar[i * 9 + x] != val) && {
let (start_x, start_y) = ((x / 3) * 3, (y / 3) * 3);
(start_y..start_y + 3).all(|i| (start_x..start_x + 3).all(|j| sudok... |
Sum and product of an array |
int arg[] = { 1,2,3,4,5 };
int arg_length = sizeof(arg)/sizeof(arg[0]);
int *end = arg+arg_length;
int sum = 0, prod = 1;
int *p;
for (p = arg; p!=end; ++p) {
sum += *p;
prod *= *p;
}
| fn main() {
let arr = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
let sum = arr.iter().fold(0i32, |a, &b| a + b);
let product = arr.iter().fold(1i32, |a, &b| a * b);
println!("the sum is {} and the product is {}", sum, product);
let sum = arr.iter().sum::<i32>();
let product = arr.iter().produc... |
Sum digits of an integer | #include <stdio.h>
int SumDigits(unsigned long long n, const int base) {
int sum = 0;
for (; n; n /= base)
sum += n % base;
return sum;
}
int main() {
printf("%d %d %d %d %d\n",
SumDigits(1, 10),
SumDigits(12345, 10),
SumDigits(123045, 10),
SumDigits(0xfe, 16),
... | struct DigitIter(usize, usize);
impl Iterator for DigitIter {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.0 == 0 {
None
} else {
let ret = self.0 % self.1;
self.0 /= self.1;
Some(ret)
}
}
}
fn main() {
pr... |
Sum multiples of 3 and 5 | #include <stdio.h>
#include <stdlib.h>
unsigned long long sum35(unsigned long long limit)
{
unsigned long long sum = 0;
for (unsigned long long i = 0; i < limit; i++)
if (!(i % 3) || !(i % 5))
sum += i;
return sum;
}
int main(int argc, char **argv)
{
unsigned long long limit;
... | extern crate rug;
use rug::Integer;
use rug::ops::Pow;
fn main() {
for i in [3, 20, 100, 1_000].iter() {
let ten = Integer::from(10);
let mut limit = Integer::from(Integer::from(&ten.pow(*i as u32)) - 1);
let mut aux_3_1 = &limit.mod_u(3u32);
let mut aux_3_2 = Integer::from(&limit ... |
Sum of a series | #include <stdio.h>
double Invsqr(double n)
{
return 1 / (n*n);
}
int main (int argc, char *argv[])
{
int i, start = 1, end = 1000;
double sum = 0.0;
for( i = start; i <= end; i++)
sum += Invsqr((double)i);
printf("%16.14f\n", sum);
return 0;
}
| const LOWER: i32 = 1;
const UPPER: i32 = 1000;
const NUMBER_OF_TERMS: i32 = (UPPER + 1) - LOWER;
fn main() {
println!("{}", (NUMBER_OF_TERMS * (LOWER + UPPER)) / 2);
println!("{}", (LOWER..UPPER + 1).fold(0, |sum, x| sum + x));
}
|
Sum of squares | #include <stdio.h>
double squaredsum(double *l, int e)
{
int i; double sum = 0.0;
for(i = 0 ; i < e ; i++) sum += l[i]*l[i];
return sum;
}
int main()
{
double list[6] = {3.0, 1.0, 4.0, 1.0, 5.0, 9.0};
printf("%lf\n", squaredsum(list, 6));
printf("%lf\n", squaredsum(list, 0));
printf("%lf\... | fn sq_sum(v: &[f64]) -> f64 {
v.iter().fold(0., |sum, &num| sum + num*num)
}
fn main() {
let v = vec![3.0, 1.0, 4.0, 1.0, 5.5, 9.7];
println!("{}", sq_sum(&v));
let u : Vec<f64> = vec![];
println!("{}", sq_sum(&u));
}
|
Symmetric difference | #include <stdio.h>
#include <string.h>
const char *A[] = { "John", "Serena", "Bob", "Mary", "Serena" };
const char *B[] = { "Jim", "Mary", "John", "Jim", "Bob" };
#define LEN(x) sizeof(x)/sizeof(x[0])
void uniq(const char *x[], int len)
{
int i, j;
for (i = 0; i < len; i++)
for (j = i + 1; j < len; j++)
if (... | use std::collections::HashSet;
fn main() {
let a: HashSet<_> = ["John", "Bob", "Mary", "Serena"]
.iter()
.collect();
let b = ["Jim", "Mary", "John", "Bob"]
.iter()
.collect();
let diff = a.symmetric_difference(&b);
println!("{:?}", diff);
}
|
Synchronous concurrency | #include <stdlib.h>
#include <stdio.h>
#include <libco.h>
void
fail(const char *message) {
perror(message);
exit(1);
}
cothread_t reader;
cothread_t printer;
struct {
char *buf;
size_t len;
size_t cap;
} line;
size_t count;
void
reader_entry(void)
{
FILE *input;
size_t newcap;
int c, eof, eol;
ch... | use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::sync::mpsc::{channel, sync_channel};
use std::thread;
fn main() {
let (reader_send, writer_recv) = channel();
let (writer_send, reader_recv) = sync_channel(0);
let reader_work = move || {
let file = Fil... |
System time | #include<time.h>
#include<stdio.h>
#include<stdlib.h>
int main(){
time_t my_time = time(NULL);
printf("%s", ctime(&my_time));
return 0;
}
|
extern crate chrono;
use chrono::prelude::*;
fn main() {
let utc: DateTime<Utc> = Utc::now();
println!("{}", utc.format("%d/%m/%Y %T"));
}
|
Take notes on the command line | #include <stdio.h>
#include <time.h>
#define note_file "NOTES.TXT"
int main(int argc, char**argv)
{
FILE *note = 0;
time_t tm;
int i;
char *p;
if (argc < 2) {
if ((note = fopen(note_file, "r")))
while ((i = fgetc(note)) != EOF)
putchar(i);
} else if ((note = fopen(note_file, "a"))) {
tm = time(0);
... | extern crate chrono;
use std::fs::OpenOptions;
use std::io::{self, BufReader, BufWriter};
use std::io::prelude::*;
use std::env;
const FILENAME: &str = "NOTES.TXT";
fn show_notes() -> Result<(), io::Error> {
let file = OpenOptions::new()
.read(true)
.create(true)
.write(true)
.o... |
Temperature conversion | #include <stdio.h>
#include <stdlib.h>
double kelvinToCelsius(double k){
return k - 273.15;
}
double kelvinToFahrenheit(double k){
return k * 1.8 - 459.67;
}
double kelvinToRankine(double k){
return k * 1.8;
}
void convertKelvin(double kelvin) {
printf("K %.2f\n", kelvin);
printf("C %.2f\n", kelv... | fn main() -> std::io::Result<()> {
print!("Enter temperature in Kelvin to convert: ");
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
match input.trim().parse::<f32>() {
Ok(kelvin) => {
if kelvin < 0.0 {
println!("Negative Kelvin values are no... |
Terminal control_Clear the screen | void cls(void) {
printf("\33[2J");
}
| print!("\x1B[2J");
|
Terminal control_Coloured text | #include <stdio.h>
void table(const char *title, const char *mode)
{
int f, b;
printf("\n\033[1m%s\033[m\n bg\t fg\n", title);
for (b = 40; b <= 107; b++) {
if (b == 48) b = 100;
printf("%3d\t\033[%s%dm", b, mode, b);
for (f = 30; f <= 97; f++) {
if (f == 38) f = 90;
printf("\033[%dm%3d ", f, f);
}
... | const ESC: &str = "\x1B[";
const RESET: &str = "\x1B[0m";
fn main() {
println!("Foreground¦Background--------------------------------------------------------------");
print!(" ¦");
for i in 40..48 {
print!(" ESC[{}m ", i);
}
println!("\n----------¦----------------------------------... |
Terminal control_Ringing the terminal bell | #include <stdio.h>
int main() {
printf("\a");
return 0;
}
| fn main() {
print!("\x07");
}
|
Ternary logic | #include <stdio.h>
typedef enum {
TRITTRUE,
TRITMAYBE,
TRITFALSE
} trit;
trit tritNot[3] = {TRITFALSE , TRITMAYBE, TRITTRUE};
trit tritAnd[3][3] = { {TRITTRUE, TRITMAYBE, TRITFALSE},
{TRITMAYBE, TRITMAYBE, TRITFALSE},
{TRITFALSE, TRITFALSE, TRITFALSE} };
t... | use std::{ops, fmt};
#[derive(Copy, Clone, Debug)]
enum Trit {
True,
Maybe,
False,
}
impl ops::Not for Trit {
type Output = Self;
fn not(self) -> Self {
match self {
Trit::True => Trit::False,
Trit::Maybe => Trit::Maybe,
Trit::False => Trit::True,
... |
Test a function | #include <assert.h>
int IsPalindrome(char *Str);
int main()
{
assert(IsPalindrome("racecar"));
assert(IsPalindrome("alice"));
}
|
pub fn is_palindrome(s: &str) -> bool {
let half = s.len();
s.chars().take(half).eq(s.chars().rev().take(half))
}
#[cfg(test)]
mod tests {
use super::is_palindrome;
#[test]
fn test_is_palindrome() {
assert!(is_palindrome("abba"));
}
}
|
Text processing_Max licenses in use | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#define INOUT_LEN 4
#define TIME_LEN 20
#define MAX_MAXOUT 1000
char inout[INOUT_LEN];
char time[TIME_LEN];
uint jobnum;
char maxtime[MAX_MAXOUT][TIME_LEN];
int main(int argc, char **argv)
{
FILE *in = NULL;
int l_out = 0, maxout=... | type Timestamp = String;
fn compute_usage<R, S, E>(lines: R) -> Result<(u32, Vec<Timestamp>), E>
where
S: AsRef<str>,
R: Iterator<Item = Result<S, E>>,
{
let mut timestamps = Vec::new();
let mut current = 0;
let mut maximum = 0;
for line in lines {
let line = line?;
let line = ... |
The Twelve Days of Christmas | #include<stdio.h>
int main()
{
int i,j;
char days[12][10] =
{
"First",
"Second",
"Third",
"Fourth",
"Fifth",
"Sixth",
"Seventh",
"Eighth",
"Ninth",
"Tenth",
"Eleventh",
"Twelfth"
};
char gifts[12][3... | fn main() {
let days = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth",
"ninth", "tenth", "eleventh", "twelfth"];
let gifts = ["A Partridge in a Pear Tree",
"Two Turtle Doves and",
"Three French Hens",
"Four Calling... |
Thue-Morse | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
char sequence[256+1] = "0";
char inverse[256+1] = "1";
char buffer[256+1];
int i;
for(i = 0; i < 8; i++){
strcpy(buffer, sequence);
strcat(sequence, inverse);
strcat(inverse, buffer);
}
puts(sequence);
return... | const ITERATIONS: usize = 8;
fn neg(sequence: &String) -> String {
sequence.chars()
.map(|ch| {
(1 - ch.to_digit(2).unwrap()).to_string()
})
.collect::<String>()
}
fn main() {
let mut sequence: String = String::from("0");
for i in 0..ITERATIONS {
println!("{}: {... |
Tic-tac-toe | #include <stdio.h>
#include <stdlib.h>
int b[3][3];
int check_winner()
{
int i;
for (i = 0; i < 3; i++) {
if (b[i][0] && b[i][1] == b[i][0] && b[i][2] == b[i][0])
return b[i][0];
if (b[0][i] && b[1][i] == b[0][i] && b[2][i] == b[0][i])
return b[0][i];
}
if (!b[1][1]) return 0;
if (b[1][1] == b[0][0] ... | use GameState::{ComputerWin, Draw, PlayerWin, Playing};
use rand::prelude::*;
#[derive(PartialEq, Debug)]
enum GameState {
PlayerWin,
ComputerWin,
Draw,
Playing,
}
type Board = [[char; 3]; 3];
fn main() {
let mut rng = StdRng::from_entropy();
let mut board: Board = [['1', '2', '3'], ['4', '... |
Subsets and Splits
SQL Console for aandvalenzuela/test
Displays the highest values of 'C' and 'Rust' for each distinct name, highlighting the maximum levels of these two features per name.
SQL Console for aandvalenzuela/test
Retrieves distinct names along with the highest values for 'C' and 'Rust' if both are present for each name, providing a comparison of these metrics.
SQL Console for aandvalenzuela/test
The query retrieves names from the validation dataset where both the C and Rust columns are not null, providing a basic filter for entries with complete data on these languages.