Word wrap

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

const char *string = "In olden times when wishing still helped one, there lived a king "
    "whose daughters were all beautiful, but the youngest was so beautiful "
    "that the sun itself, which has seen so much, was astonished whenever "
    "it shone-in-her-face.  Close-by-the-king's castle lay a great dark "
    "forest, and under an old lime-tree in the forest was a well, and when "
    "the day was very warm, the king's child went out into the forest and "
    "sat down by the side of the cool-fountain, and when she was bored she "
    "took a golden ball, and threw it up on high and caught it, and this "
    "ball was her favorite plaything.";

#define PENALTY_LONG    100
#define PENALTY_SHORT   1

typedef struct word_t {
    const char *s;
    int len;
} *word;

word make_word_list(const char *s, int *n)
{
    int max_n = 0;
    word words = 0;

    *n = 0;
    while (1) {
        while (*s && isspace(*s)) s++;
        if (!*s) break;

        if (*n >= max_n) {
            if (!(max_n *= 2)) max_n = 2;
            words = realloc(words, max_n * sizeof(*words));
        }
        words[*n].s = s;
        while (*s && !isspace(*s)) s++;
        words[*n].len = s - words[*n].s;
        (*n) ++;
    }

    return words;
}

int greedy_wrap(word words, int count, int cols, int *breaks)
{
    int score = 0, line, i, j, d;

    i = j = line = 0;
    while (1) {
        if (i == count) {
            breaks[j++] = i;
            break;
        }

        if (!line) {
            line = words[i++].len;
            continue;
        }

        if (line + words[i].len < cols) {
            line += words[i++].len + 1;
            continue;
        }

        breaks[j++] = i;
        if (i < count) {
            d = cols - line;
            if (d > 0)  score += PENALTY_SHORT * d * d;
            else if (d < 0) score += PENALTY_LONG * d * d;
        }

        line = 0;
    }
    breaks[j++] = 0;

    return score;
}

int balanced_wrap(word words, int count, int cols, int *breaks)
{
    int *best = malloc(sizeof(int) * (count + 1));

    int best_score = greedy_wrap(words, count, cols, breaks);

    void test_wrap(int line_no, int start, int score) {
        int line = 0, current_score = -1, d;

        while (start <= count) {
            if (line) line ++;
            line += words[start++].len;
            d = cols - line;
            if (start < count || d < 0) {
                if (d > 0)
                    current_score = score + PENALTY_SHORT * d * d;
                else
                    current_score = score + PENALTY_LONG * d * d;
            } else {
                current_score = score;
            }

            if (current_score >= best_score) {
                if (d <= 0) return;
                continue;
            }

            best[line_no] = start;
            test_wrap(line_no + 1, start, current_score);
        }
        if (current_score >= 0 && current_score < best_score) {
            best_score = current_score;
            memcpy(breaks, best, sizeof(int) * (line_no));
        }
    }
    test_wrap(0, 0, 0);
    free(best);

    return best_score;
}

void show_wrap(word list, int count, int *breaks)
{
    int i, j;
    for (i = j = 0; i < count && breaks[i]; i++) {
        while (j < breaks[i]) {
            printf("%.*s", list[j].len, list[j].s);
            if (j < breaks[i] - 1)
                putchar(' ');
            j++;
        }
        if (breaks[i]) putchar('\n');
    }
}

int main(void)
{
    int len, score, cols;
    word list = make_word_list(string, &len);
    int *breaks = malloc(sizeof(int) * (len + 1));

    cols = 80;
    score = greedy_wrap(list, len, cols, breaks);
    printf("\n== greedy wrap at %d (score %d) ==\n\n", cols, score);
    show_wrap(list, len, breaks);

    score = balanced_wrap(list, len, cols, breaks);
    printf("\n== balanced wrap at %d (score %d) ==\n\n", cols, score);
    show_wrap(list, len, breaks);

    cols = 32;
    score = greedy_wrap(list, len, cols, breaks);
    printf("\n== greedy wrap at %d (score %d) ==\n\n", cols, score);
    show_wrap(list, len, breaks);

    score = balanced_wrap(list, len, cols, breaks);
    printf("\n== balanced wrap at %d (score %d) ==\n\n", cols, score);
    show_wrap(list, len, breaks);

    return 0;
}

#[derive(Clone, Debug)]
pub struct LineComposer<I> {
    words: I,
    width: usize,
    current: Option<String>,
}

impl<I> LineComposer<I> {
    pub(crate) fn new<S>(words: I, width: usize) -> Self
    where
        I: Iterator<Item = S>,
        S: AsRef<str>,
    {
        LineComposer {
            words,
            width,
            current: None,
        }
    }
}

impl<I, S> Iterator for LineComposer<I>
where
    I: Iterator<Item = S>,
    S: AsRef<str>,
{
    type Item = String;

    fn next(&mut self) -> Option<Self::Item> {
        let mut next = match self.words.next() {
            None => return self.current.take(),
            Some(value) => value,
        };

        let mut current = self.current.take().unwrap_or_else(String::new);

        loop {
            let word = next.as_ref();
            if self.width <= current.len() + word.len() {
                self.current = Some(String::from(word));

                if !current.is_empty() {
                    return Some(current);
                }
            }

            if !current.is_empty() {
                current.push_str(" ")
            }

            current.push_str(word);

            match self.words.next() {
                None => return Some(current),
                Some(word) => next = word,
            }
        }
    }
}

pub trait ComposeLines: Iterator {
    fn compose_lines(self, width: usize) -> LineComposer<Self>
    where
        Self: Sized,
        Self::Item: AsRef<str>,
    {
        LineComposer::new(self, width)
    }
}

impl<T, S> ComposeLines for T
where
    T: Iterator<Item = S>,
    S: AsRef<str>,
{
}

fn main() {
    let text = r"
        In olden times when wishing still helped one, there lived a king whose
        daughters were all beautiful, but the youngest was so beautiful that the
        sun itself, which has seen so much, was astonished whenever it shone in
        her face. Close by the king's castle lay a great dark forest, and under
        an old lime tree in the forest was a well, and when the day was very
        warm, the king's child went out into the forest and sat down by the side
        of the cool fountain, and when she was bored she took a golden ball, and
        threw it up on high and caught it, and this ball was her favorite
        plaything.";

    text.split_whitespace()
        .compose_lines(80)
        .for_each(|line| println!("{}", line));
}


Write entire file

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void)
{
    return 0 >= fputs("ANY STRING TO WRITE TO A FILE AT ONCE.",
        freopen("sample.txt","wb",stdout));
}

use std::fs::File;
use std::io::Write;

fn main() -> std::io::Result<()> {
    let data = "Sample text.";
    let mut file = File::create("filename.txt")?;
    write!(file, "{}", data)?;
    Ok(())
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>

static void print_names(xmlNode *node)
{
  xmlNode *cur_node = NULL;
  for (cur_node = node; cur_node; cur_node = cur_node->next) {
    if (cur_node->type == XML_ELEMENT_NODE) {
      if ( strcmp(cur_node->name, "Student") == 0 ) {
	xmlAttr *prop = NULL;
	if ( (prop = xmlHasProp(cur_node, "Name")) != NULL ) {
	  printf("%s\n", prop->children->content);

	}
      }
    }
    print_names(cur_node->children);
  }
}

const char *buffer =
  "<Students>\n"
  "  <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n"
  "  <Student Name=\"Bob\" Gender=\"M\"  DateOfBirth=\"1990-03-04\" />\n"
  "  <Student Name=\"Chad\" Gender=\"M\"  DateOfBirth=\"1991-05-06\" />\n"
  "  <Student Name=\"Dave\" Gender=\"M\"  DateOfBirth=\"1992-07-08\">\n"
  "    <Pet Type=\"dog\" Name=\"Rover\" />\n"
  "  </Student>\n"
  "  <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />\n"
  "</Students>\n";

int main()
{
  xmlDoc *doc = NULL;
  xmlNode *root = NULL;

  doc = xmlReadMemory(buffer, strlen(buffer), NULL, NULL, 0);
  if ( doc != NULL ) {
    root = xmlDocGetRootElement(doc);
    print_names(root);
    xmlFreeDoc(doc);
  }
  xmlCleanupParser();
  return 0;
}

extern crate xml;
use xml::{name::OwnedName, reader::EventReader, reader::XmlEvent};

const DOCUMENT: &str = r#"
<Students>
  <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
  <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
  <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
  <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
    <Pet Type="dog" Name="Rover" />
  </Student>
  <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
"#;

fn main() -> Result<(), xml::reader::Error> {
    let parser = EventReader::new(DOCUMENT.as_bytes());

    let tag_name = OwnedName::local("Student");
    let attribute_name = OwnedName::local("Name");

    for event in parser {
        match event? {
            XmlEvent::StartElement {
                name,
                attributes,
                ..
            } if name == tag_name => {
                if let Some(attribute) = attributes.iter().find(|&attr| attr.name == attribute_name) {
                    println!("{}", attribute.value);
                }
            }
            _ => (),
        }
    }
    Ok(())
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>

const char *names[] = {
  "April", "Tam O'Shanter", "Emily", NULL
};
const char *remarks[] = {
  "Bubbly: I'm > Tam and <= Emily",
  "Burns: \"When chapman billies leave the street ...\"",
  "Short & shrift", NULL
};

int main()
{
  xmlDoc *doc = NULL;
  xmlNode *root = NULL, *node;
  const char **next;
  int a;

  doc = xmlNewDoc("1.0");
  root = xmlNewNode(NULL, "CharacterRemarks");
  xmlDocSetRootElement(doc, root);

  for(next = names, a = 0; *next != NULL; next++, a++) {
    node = xmlNewNode(NULL, "Character");
    (void)xmlNewProp(node, "name", *next);
    xmlAddChild(node, xmlNewText(remarks[a]));
    xmlAddChild(root, node);
  }

  xmlElemDump(stdout, doc, root);

  xmlFreeDoc(doc);
  xmlCleanupParser();

  return EXIT_SUCCESS;
}

extern crate xml;

use std::collections::HashMap;
use std::str;

use xml::writer::{EmitterConfig, XmlEvent};

fn characters_to_xml(characters: HashMap<String, String>) -> String {
    let mut output: Vec<u8> = Vec::new();
    let mut writer = EmitterConfig::new()
        .perform_indent(true)
        .create_writer(&mut output);

    writer
        .write(XmlEvent::start_element("CharacterRemarks"))
        .unwrap();

    for (character, line) in &characters {
        let element = XmlEvent::start_element("Character").attr("name", character);
        writer.write(element).unwrap();
        writer.write(XmlEvent::characters(line)).unwrap();
        writer.write(XmlEvent::end_element()).unwrap();
    }

    writer.write(XmlEvent::end_element()).unwrap();
    str::from_utf8(&output).unwrap().to_string()
}

#[cfg(test)]
mod tests {
    use super::characters_to_xml;
    use std::collections::HashMap;

    #[test]
    fn test_xml_output() {
        let mut input = HashMap::new();
        input.insert(
            "April".to_string(),
            "Bubbly: I'm > Tam and <= Emily".to_string(),
        );
        input.insert(
            "Tam O'Shanter".to_string(),
            "Burns: \"When chapman billies leave the street ...\"".to_string(),
        );
        input.insert("Emily".to_string(), "Short & shrift".to_string());

        let output = characters_to_xml(input);

        println!("{}", output);
        assert!(output.contains(
            "<Character name=\"Tam O'Shanter\">Burns: \"When chapman \
             billies leave the street ...\"</Character>"
        ));
        assert!(output
            .contains("<Character name=\"April\">Bubbly: I'm > Tam and <= Emily</Character>"));
        assert!(output.contains("<Character name=\"Emily\">Short & shrift</Character>"));
    }
}


Yin and yang

#include <stdio.h>

void draw_yinyang(int trans, double scale)
{
	printf("<use xlink:href='#y' transform='translate(%d,%d) scale(%g)'/>",
		trans, trans, scale);
}

int main()
{	printf(
	"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n"
	"<!DOCTYPE svg PUBLIC '-
	"	'http:
	"<svg xmlns='http:
	"	xmlns:xlink='http:
	"		width='30' height='30'>\n"
	"	<defs><g id='y'>\n"
	"		<circle cx='0' cy='0' r='200' stroke='black'\n"
	"			fill='white' stroke-width='1'/>\n"
	"		<path d='M0 -200 A 200 200 0 0 0 0 200\n"
	"			100 100 0 0 0 0 0 100 100 0 0 1 0 -200\n"
	"			z' fill='black'/>\n"
	"		<circle cx='0' cy='100' r='33' fill='white'/>\n"
	"		<circle cx='0' cy='-100' r='33' fill='black'/>\n"
	"	</g></defs>\n");
	draw_yinyang(20, .05);
	draw_yinyang(8, .02);
	printf("</svg>");
	return 0;
}


Zero to the zero power

#include <stdio.h>
#include <math.h>
#include <complex.h>

int main()
{
	printf("0 ^ 0 = %f\n", pow(0,0));
        double complex c = cpow(0,0);
	printf("0+0i ^ 0+0i = %f+%fi\n", creal(c), cimag(c));
	return 0;
}


Zig-zag matrix

#include <stdio.h>
#include <stdlib.h>

int main(int c, char **v)
{
	int i, j, m, n, *s;

	if (c < 2 || ((m = atoi(v[1]))) <= 0) m = 5;

	s = malloc(sizeof(int) * m * m);

	for (i = n = 0; i < m * 2; i++)
		for (j = (i < m) ? 0 : i-m+1; j <= i && j < m; j++)
			s[(i&1)? j*(m-1)+i : (i-j)*m+j ] = n++;

	for (i = 0; i < m * m; putchar((++i % m) ? ' ':'\n'))
		printf("%3d", s[i]);

	return 0;
}

use std::cmp::Ordering;
use std::cmp::Ordering::{Equal, Greater, Less};
use std::iter::repeat;

#[derive(Debug, PartialEq, Eq)]
struct SortIndex {
    x: usize,
    y: usize,
}

impl SortIndex {
    fn new(x: usize, y: usize) -> SortIndex {
        SortIndex { x, y }
    }
}

impl PartialOrd for SortIndex {
    fn partial_cmp(&self, other: &SortIndex) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for SortIndex {
    fn cmp(&self, other: &SortIndex) -> Ordering {
        let lower = if self.x + self.y == other.x + other.y {
            if (self.x + self.y) % 2 == 0 {
                self.x < other.x
            } else {
                self.y < other.y
            }
        } else {
            (self.x + self.y) < (other.x + other.y)
        };

        if lower {
            Less
        } else if self == other {
            Equal
        } else {
            Greater
        }
    }
}

fn zigzag(n: usize) -> Vec<Vec<usize>> {
    let mut l: Vec<SortIndex> = (0..n * n).map(|i| SortIndex::new(i % n, i / n)).collect();
    l.sort();

    let init_vec = vec![0; n];
    let mut result: Vec<Vec<usize>> = repeat(init_vec).take(n).collect();
    for (i, &SortIndex { x, y }) in l.iter().enumerate() {
        result[y][x] = i
    }
    result
}

fn main() {
    println!("{:?}", zigzag(5));
}