title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
War card game
C++
War Card Game Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional. References: :* Bicycle card company: War game site :* Wikipedia: War (card game) Related tasks: * [[Playing cards]] * [[Card shuffles]] * [[Deal cards for FreeCell]] * [[Poker hand_analyser]] * [[Go Fish]]
#include <iostream> #include <vector> #include <algorithm> class war_game { public: war_game() { for ( char suit : SUITS ) { for ( char pip : PIPS ) { deck.emplace_back(card(suit, pip)); } } std::random_shuffle(deck.begin(), deck.end()); handA = { deck.begin(), deck.begin() + 26 }; handB = { deck.begin() + 26, deck.end() }; } void next_turn() { card cardA = handA.front(); handA.erase(handA.begin()); card cardB = handB.front(); handB.erase(handB.begin()); tabledCards.emplace_back(cardA); tabledCards.emplace_back(cardB); int32_t rankA = getRank(cardA.pip); int32_t rankB = getRank(cardB.pip); std::cout << cardA.pip << cardA.suit << " " << cardB.pip << cardB.suit << std::endl; if ( rankA > rankB ) { std::cout << " Player A takes the cards" << std::endl; std::random_shuffle(tabledCards.begin(), tabledCards.end()); handA.insert(handA.end(), tabledCards.begin(), tabledCards.end()); tabledCards.clear(); } else if ( rankA < rankB ) { std::cout << " Player B takes the cards" << std::endl; std::random_shuffle(tabledCards.begin(), tabledCards.end()); handB.insert(handB.end(), tabledCards.begin(), tabledCards.end());; tabledCards.clear(); } else { std::cout << " War!" << std::endl; if ( game_over() ) { return; } card cardAA = handA.front(); handA.erase(handA.begin()); card cardBB = handB.front(); handB.erase(handB.begin()); tabledCards.emplace_back(cardAA); tabledCards.emplace_back(cardBB); std::cout << "? ? Cards are face down" << std::endl; if ( game_over() ) { return; } next_turn(); } } bool game_over() const { return handA.size() == 0 || handB.size() == 0; } void declare_winner() const { if ( handA.size() == 0 && handB.size() == 0 ) { std::cout << "The game ended in a tie" << std::endl; } else if ( handA.size() == 0 ) { std::cout << "Player B has won the game" << std::endl; } else { std::cout << "Player A has won the game" << std::endl; } } private: class card { public: card(const char suit, const char pip) : suit(suit), pip(pip) {}; char suit, pip; }; int32_t getRank(const char ch) const { auto it = find(PIPS.begin(), PIPS.end(), ch); if ( it != PIPS.end() ) { return it - PIPS.begin(); } return -1; } std::vector<card> deck, handA, handB, tabledCards; inline static const std::vector<char> PIPS = { '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' }; inline static const std::vector<char> SUITS = { 'C', 'D', 'H', 'S' }; }; int main() { war_game wargame; while ( ! wargame.game_over() ) { wargame.next_turn(); } wargame.declare_winner(); }
Water collected between towers
C++
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, completely filling all convex enclosures in the chart with water. 9 ## 9 ## 8 ## 8 ## 7 ## ## 7 #### 6 ## ## ## 6 ###### 5 ## ## ## #### 5 ########## 4 ## ## ######## 4 ############ 3 ###### ######## 3 ############## 2 ################ ## 2 ################## 1 #################### 1 #################### In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water. Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart. Calculate the number of water units that could be collected by bar charts representing each of the following seven series: [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]] See, also: * Four Solutions to a Trivial Problem - a Google Tech Talk by Guy Steele * Water collected between towers on Stack Overflow, from which the example above is taken) * An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
#include <iostream> #include <vector> #include <algorithm> enum { EMPTY, WALL, WATER }; auto fill(const std::vector<int> b) { auto water = 0; const auto rows = *std::max_element(std::begin(b), std::end(b)); const auto cols = std::size(b); std::vector<std::vector<int>> g(rows); for (auto& r : g) { for (auto i = 0; i < cols; ++i) { r.push_back(EMPTY); } } for (auto c = 0; c < cols; ++c) { for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) { g[r][c] = WALL; } } for (auto c = 0; c < cols - 1; ++c) { auto start_row = rows - b[c]; while (start_row < rows) { if (g[start_row][c] == EMPTY) break; auto c2 = c + 1; bool hitWall = false; while (c2 < cols) { if (g[start_row][c2] == WALL) { hitWall = true; break; } ++c2; } if (hitWall) { for (auto i = c + 1; i < c2; ++i) { g[start_row][i] = WATER; ++water; } } ++start_row; } } return water; } int main() { std::vector<std::vector<int>> b = { { 1, 5, 3, 7, 2 }, { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 }, { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 }, { 5, 5, 5, 5 }, { 5, 6, 7, 8 }, { 8, 7, 7, 6 }, { 6, 7, 10, 7, 6 } }; for (const auto v : b) { auto water = fill(v); std::cout << water << " water drops." << std::endl; } std::cin.ignore(); std::cin.get(); return 0; }
Weird numbers
C++ from D
In number theory, a perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect''). For example: * '''12''' is ''not'' a weird number. ** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12), ** but it ''is'' semiperfect, e.g.: '''6 + 4 + 2 == 12'''. * '''70''' ''is'' a weird number. ** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70), ** and there is no subset of proper divisors that sum to '''70'''. ;Task: Find and display, here on this page, the first '''25''' weird numbers. ;Related tasks: :* Abundant, deficient and perfect number classifications :* Proper divisors ;See also: :* OEIS: A006037 weird numbers :* Wikipedia: weird number :* MathWorld: weird number
#include <algorithm> #include <iostream> #include <numeric> #include <vector> std::vector<int> divisors(int n) { std::vector<int> divs = { 1 }; std::vector<int> divs2; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs.push_back(i); if (i != j) { divs2.push_back(j); } } } std::copy(divs.cbegin(), divs.cend(), std::back_inserter(divs2)); return divs2; } bool abundant(int n, const std::vector<int> &divs) { return std::accumulate(divs.cbegin(), divs.cend(), 0) > n; } template<typename IT> bool semiperfect(int n, const IT &it, const IT &end) { if (it != end) { auto h = *it; auto t = std::next(it); if (n < h) { return semiperfect(n, t, end); } else { return n == h || semiperfect(n - h, t, end) || semiperfect(n, t, end); } } else { return false; } } template<typename C> bool semiperfect(int n, const C &c) { return semiperfect(n, std::cbegin(c), std::cend(c)); } std::vector<bool> sieve(int limit) { // false denotes abundant and not semi-perfect. // Only interested in even numbers >= 2 std::vector<bool> w(limit); for (int i = 2; i < limit; i += 2) { if (w[i]) continue; auto divs = divisors(i); if (!abundant(i, divs)) { w[i] = true; } else if (semiperfect(i, divs)) { for (int j = i; j < limit; j += i) { w[j] = true; } } } return w; } int main() { auto w = sieve(17000); int count = 0; int max = 25; std::cout << "The first 25 weird numbers:"; for (int n = 2; count < max; n += 2) { if (!w[n]) { std::cout << n << ' '; count++; } } std::cout << '\n'; return 0; }
Word frequency
C++
Given a text file and an integer '''n''', print/display the '''n''' most common words in the file (and the number of their occurrences) in decreasing frequency. For the purposes of this task: * A word is a sequence of one or more contiguous letters. * You are free to define what a ''letter'' is. * Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion. * You may treat a compound word like '''well-dressed''' as either one word or two. * The word '''it's''' could also be one or two words as you see fit. * You may also choose not to support non US-ASCII characters. * Assume words will not span multiple lines. * Don't worry about normalization of word spelling differences. * Treat '''color''' and '''colour''' as two distinct words. * Uppercase letters are considered equivalent to their lowercase counterparts. * Words of equal frequency can be listed in any order. * Feel free to explicitly state the thoughts behind the program decisions. Show example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words. ;History: This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6 where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy, demonstrating solving the problem in a 6 line Unix shell script (provided as an example below). ;References: *McIlroy's program
#include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> #include <iterator> #include <string> #include <unordered_map> #include <vector> int main(int ac, char** av) { std::ios::sync_with_stdio(false); int head = (ac > 1) ? std::atoi(av[1]) : 10; std::istreambuf_iterator<char> it(std::cin), eof; std::filebuf file; if (ac > 2) { if (file.open(av[2], std::ios::in), file.is_open()) { it = std::istreambuf_iterator<char>(&file); } else return std::cerr << "file " << av[2] << " open failed\n", 1; } auto alpha = [](unsigned c) { return c-'A' < 26 || c-'a' < 26; }; auto lower = [](unsigned c) { return c | '\x20'; }; std::unordered_map<std::string, int> counts; std::string word; for (; it != eof; ++it) { if (alpha(*it)) { word.push_back(lower(*it)); } else if (!word.empty()) { ++counts[word]; word.clear(); } } if (!word.empty()) ++counts[word]; // if file ends w/o ws std::vector<std::pair<const std::string,int> const*> out; for (auto& count : counts) out.push_back(&count); std::partial_sort(out.begin(), out.size() < head ? out.end() : out.begin() + head, out.end(), [](auto const* a, auto const* b) { return a->second > b->second; }); if (out.size() > head) out.resize(head); for (auto const& count : out) { std::cout << count->first << ' ' << count->second << '\n'; } return 0; }
Word frequency
C++ from C#
Given a text file and an integer '''n''', print/display the '''n''' most common words in the file (and the number of their occurrences) in decreasing frequency. For the purposes of this task: * A word is a sequence of one or more contiguous letters. * You are free to define what a ''letter'' is. * Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion. * You may treat a compound word like '''well-dressed''' as either one word or two. * The word '''it's''' could also be one or two words as you see fit. * You may also choose not to support non US-ASCII characters. * Assume words will not span multiple lines. * Don't worry about normalization of word spelling differences. * Treat '''color''' and '''colour''' as two distinct words. * Uppercase letters are considered equivalent to their lowercase counterparts. * Words of equal frequency can be listed in any order. * Feel free to explicitly state the thoughts behind the program decisions. Show example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words. ;History: This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6 where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy, demonstrating solving the problem in a 6 line Unix shell script (provided as an example below). ;References: *McIlroy's program
#include <algorithm> #include <iostream> #include <format> #include <fstream> #include <map> #include <ranges> #include <regex> #include <string> #include <vector> int main() { std::ifstream in("135-0.txt"); std::string text{ std::istreambuf_iterator<char>{in}, std::istreambuf_iterator<char>{} }; in.close(); std::regex word_rx("\\w+"); std::map<std::string, int> freq; for (const auto& a : std::ranges::subrange( std::sregex_iterator{ text.cbegin(),text.cend(), word_rx }, std::sregex_iterator{} )) { auto word = a.str(); transform(word.begin(), word.end(), word.begin(), ::tolower); freq[word]++; } std::vector<std::pair<std::string, int>> pairs; for (const auto& elem : freq) { pairs.push_back(elem); } std::ranges::sort(pairs, std::ranges::greater{}, &std::pair<std::string, int>::second); std::cout << "Rank Word Frequency\n" "==== ==== =========\n"; for (int rank=1; const auto& [word, count] : pairs | std::views::take(10)) { std::cout << std::format("{:2} {:>4} {:5}\n", rank++, word, count); } }
Word ladder
C++
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into a man: boy -> bay -> ban -> man With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane A child can not be turned into an adult. Optional transpositions of your choice.
#include <algorithm> #include <fstream> #include <iostream> #include <map> #include <string> #include <vector> using word_map = std::map<size_t, std::vector<std::string>>; // Returns true if strings s1 and s2 differ by one character. bool one_away(const std::string& s1, const std::string& s2) { if (s1.size() != s2.size()) return false; bool result = false; for (size_t i = 0, n = s1.size(); i != n; ++i) { if (s1[i] != s2[i]) { if (result) return false; result = true; } } return result; } // Join a sequence of strings into a single string using the given separator. template <typename iterator_type, typename separator_type> std::string join(iterator_type begin, iterator_type end, separator_type separator) { std::string result; if (begin != end) { result += *begin++; for (; begin != end; ++begin) { result += separator; result += *begin; } } return result; } // If possible, print the shortest chain of single-character modifications that // leads from "from" to "to", with each intermediate step being a valid word. // This is an application of breadth-first search. bool word_ladder(const word_map& words, const std::string& from, const std::string& to) { auto w = words.find(from.size()); if (w != words.end()) { auto poss = w->second; std::vector<std::vector<std::string>> queue{{from}}; while (!queue.empty()) { auto curr = queue.front(); queue.erase(queue.begin()); for (auto i = poss.begin(); i != poss.end();) { if (!one_away(*i, curr.back())) { ++i; continue; } if (to == *i) { curr.push_back(to); std::cout << join(curr.begin(), curr.end(), " -> ") << '\n'; return true; } std::vector<std::string> temp(curr); temp.push_back(*i); queue.push_back(std::move(temp)); i = poss.erase(i); } } } std::cout << from << " into " << to << " cannot be done.\n"; return false; } int main() { word_map words; std::ifstream in("unixdict.txt"); if (!in) { std::cerr << "Cannot open file unixdict.txt.\n"; return EXIT_FAILURE; } std::string word; while (getline(in, word)) words[word.size()].push_back(word); word_ladder(words, "boy", "man"); word_ladder(words, "girl", "lady"); word_ladder(words, "john", "jane"); word_ladder(words, "child", "adult"); word_ladder(words, "cat", "dog"); word_ladder(words, "lead", "gold"); word_ladder(words, "white", "black"); word_ladder(words, "bubble", "tickle"); return EXIT_SUCCESS; }
Word search
C++
A word search puzzle typically consists of a grid of letters in which words are hidden. There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards. The words may overlap but are not allowed to zigzag, or wrap around. ;Task Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters. The cells not used by the hidden words should contain the message: ''Rosetta Code'', read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message. Pack a minimum of 25 words into the grid. Print the resulting grid and the solutions. ;Example 0 1 2 3 4 5 6 7 8 9 0 n a y r y R e l m f 1 y O r e t s g n a g 2 t n e d i S k y h E 3 n o t n c p c w t T 4 a l s u u n T m a x 5 r o k p a r i s h h 6 a A c f p a e a c C 7 u b u t t t O l u n 8 g y h w a D h p m u 9 m i r p E h o g a n parish (3,5)(8,5) gangster (9,1)(2,1) paucity (4,6)(4,0) guaranty (0,8)(0,1) prim (3,9)(0,9) huckster (2,8)(2,1) plasm (7,8)(7,4) fancy (3,6)(7,2) hogan (5,9)(9,9) nolo (1,2)(1,5) under (3,4)(3,0) chatham (8,6)(8,0) ate (4,8)(6,6) nun (9,7)(9,9) butt (1,7)(4,7) hawk (9,5)(6,2) why (3,8)(1,8) ryan (3,0)(0,0) fay (9,0)(7,2) much (8,8)(8,5) tar (5,7)(5,5) elm (6,0)(8,0) max (7,4)(9,4) pup (5,3)(3,5) mph (8,8)(6,8)
#include <iomanip> #include <ctime> #include <iostream> #include <vector> #include <string> #include <algorithm> #include <fstream> const int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25; class Cell { public: Cell() : val( 0 ), cntOverlap( 0 ) {} char val; int cntOverlap; }; class Word { public: Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) : word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {} bool operator ==( const std::string& s ) { return 0 == word.compare( s ); } std::string word; int cols, rows, cole, rowe, dx, dy; }; class words { public: void create( std::string& file ) { std::ifstream f( file.c_str(), std::ios_base::in ); std::string word; while( f >> word ) { if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue; if( word.find_first_not_of( "abcdefghijklmnopqrstuvwxyz" ) != word.npos ) continue; dictionary.push_back( word ); } f.close(); std::random_shuffle( dictionary.begin(), dictionary.end() ); buildPuzzle(); } void printOut() { std::cout << "\t"; for( int x = 0; x < WID; x++ ) std::cout << x << " "; std::cout << "\n\n"; for( int y = 0; y < HEI; y++ ) { std::cout << y << "\t"; for( int x = 0; x < WID; x++ ) std::cout << puzzle[x][y].val << " "; std::cout << "\n"; } size_t wid1 = 0, wid2 = 0; for( size_t x = 0; x < used.size(); x++ ) { if( x & 1 ) { if( used[x].word.length() > wid1 ) wid1 = used[x].word.length(); } else { if( used[x].word.length() > wid2 ) wid2 = used[x].word.length(); } } std::cout << "\n"; std::vector<Word>::iterator w = used.begin(); while( w != used.end() ) { std::cout << std::right << std::setw( wid1 ) << ( *w ).word << " (" << ( *w ).cols << ", " << ( *w ).rows << ") (" << ( *w ).cole << ", " << ( *w ).rowe << ")\t"; w++; if( w == used.end() ) break; std::cout << std::setw( wid2 ) << ( *w ).word << " (" << ( *w ).cols << ", " << ( *w ).rows << ") (" << ( *w ).cole << ", " << ( *w ).rowe << ")\n"; w++; } std::cout << "\n\n"; } private: void addMsg() { std::string msg = "ROSETTACODE"; int stp = 9, p = rand() % stp; for( size_t x = 0; x < msg.length(); x++ ) { puzzle[p % WID][p / HEI].val = msg.at( x ); p += rand() % stp + 4; } } int getEmptySpaces() { int es = 0; for( int y = 0; y < HEI; y++ ) { for( int x = 0; x < WID; x++ ) { if( !puzzle[x][y].val ) es++; } } return es; } bool check( std::string word, int c, int r, int dc, int dr ) { for( size_t a = 0; a < word.length(); a++ ) { if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false; if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false; c += dc; r += dr; } return true; } bool setWord( std::string word, int c, int r, int dc, int dr ) { if( !check( word, c, r, dc, dr ) ) return false; int sx = c, sy = r; for( size_t a = 0; a < word.length(); a++ ) { if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a ); else puzzle[c][r].cntOverlap++; c += dc; r += dr; } used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) ); return true; } bool add2Puzzle( std::string word ) { int x = rand() % WID, y = rand() % HEI, z = rand() % 8; for( int d = z; d < z + 8; d++ ) { switch( d % 8 ) { case 0: if( setWord( word, x, y, 1, 0 ) ) return true; break; case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break; case 2: if( setWord( word, x, y, 0, 1 ) ) return true; break; case 3: if( setWord( word, x, y, 1, -1 ) ) return true; break; case 4: if( setWord( word, x, y, -1, 0 ) ) return true; break; case 5: if( setWord( word, x, y, -1, 1 ) ) return true; break; case 6: if( setWord( word, x, y, 0, -1 ) ) return true; break; case 7: if( setWord( word, x, y, 1, 1 ) ) return true; break; } } return false; } void clearWord() { if( used.size() ) { Word lastW = used.back(); used.pop_back(); for( size_t a = 0; a < lastW.word.length(); a++ ) { if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) { puzzle[lastW.cols][lastW.rows].val = 0; } if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) { puzzle[lastW.cols][lastW.rows].cntOverlap--; } lastW.cols += lastW.dx; lastW.rows += lastW.dy; } } } void buildPuzzle() { addMsg(); int es = 0, cnt = 0; size_t idx = 0; do { for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) { if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue; if( add2Puzzle( *w ) ) { es = getEmptySpaces(); if( !es && used.size() >= MIN_WORD_CNT ) return; } } clearWord(); std::random_shuffle( dictionary.begin(), dictionary.end() ); } while( ++cnt < 100 ); } std::vector<Word> used; std::vector<std::string> dictionary; Cell puzzle[WID][HEI]; }; int main( int argc, char* argv[] ) { unsigned s = unsigned( time( 0 ) ); srand( s ); words w; w.create( std::string( "unixdict.txt" ) ); w.printOut(); return 0; }
Word wrap
C++ from Go
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. ;Basic task: The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. ;Extra credit: Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you ''must reference documentation'' indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results.
#include <iostream> #include <sstream> #include <string> const char *text = { "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." }; std::string wrap(const char *text, size_t line_length = 72) { std::istringstream words(text); std::ostringstream wrapped; std::string word; if (words >> word) { wrapped << word; size_t space_left = line_length - word.length(); while (words >> word) { if (space_left < word.length() + 1) { wrapped << '\n' << word; space_left = line_length - word.length(); } else { wrapped << ' ' << word; space_left -= word.length() + 1; } } } return wrapped.str(); } int main() { std::cout << "Wrapped at 72:\n" << wrap(text) << "\n\n"; std::cout << "Wrapped at 80:\n" << wrap(text, 80) << "\n"; }
World Cup group stage
C++ from Go
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team. :::* A win is worth three points. :::* A draw/tie is worth one point. :::* A loss is worth zero points. ;Task: :* Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them. :* Calculate the standings points for each team with each combination of outcomes. :* Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. Don't worry about tiebreakers as they can get complicated. We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". ''Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.''
#include <algorithm> #include <array> #include <iomanip> #include <iostream> #include <sstream> std::array<std::string, 6> games{ "12", "13", "14", "23", "24", "34" }; std::string results = "000000"; int fromBase3(std::string num) { int out = 0; for (auto c : num) { int d = c - '0'; out = 3 * out + d; } return out; } std::string toBase3(int num) { std::stringstream ss; while (num > 0) { int rem = num % 3; num /= 3; ss << rem; } auto str = ss.str(); std::reverse(str.begin(), str.end()); return str; } bool nextResult() { if (results == "222222") { return false; } auto res = fromBase3(results); std::stringstream ss; ss << std::setw(6) << std::setfill('0') << toBase3(res + 1); results = ss.str(); return true; } int main() { std::array<std::array<int, 10>, 4> points; for (auto &row : points) { std::fill(row.begin(), row.end(), 0); } do { std::array<int, 4> records {0, 0, 0, 0 }; for (size_t i = 0; i < games.size(); i++) { switch (results[i]) { case '2': records[games[i][0] - '1'] += 3; break; case '1': records[games[i][0] - '1']++; records[games[i][1] - '1']++; break; case '0': records[games[i][1] - '1'] += 3; break; default: break; } } std::sort(records.begin(), records.end()); for (size_t i = 0; i < records.size(); i++) { points[i][records[i]]++; } } while (nextResult()); std::cout << "POINTS 0 1 2 3 4 5 6 7 8 9\n"; std::cout << "-------------------------------------------------------------\n"; std::array<std::string, 4> places{ "1st", "2nd", "3rd", "4th" }; for (size_t i = 0; i < places.size(); i++) { std::cout << places[i] << " place"; for (size_t j = 0; j < points[i].size(); j++) { std::cout << std::setw(5) << points[3 - i][j]; } std::cout << '\n'; } return 0; }
Write float arrays to a text file
C++
Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].
#include <algorithm> #include <cmath> // ::sqrt() #include <fstream> #include <iomanip> // setprecision() #include <iostream> #include <string> #include <vector> int main() { try { // prepare test data double x[] = {1, 2, 3, 1e11}; const size_t xsize = sizeof(x) / sizeof(*x); std::vector<double> y(xsize); std::transform(&x[0], &x[xsize], y.begin(), ::sqrt); // write file using default precisions writedat("sqrt.dat", &x[0], &x[xsize], y.begin(), y.end()); // print the result file std::ifstream f("sqrt.dat"); for (std::string line; std::getline(f, line); ) std::cout << line << std::endl; } catch(std::exception& e) { std::cerr << "writedat: exception: '" << e.what() << "'\n"; return 1; } return 0; }
Write language name in 3D ASCII
C++
Write/display a language's name in '''3D''' ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) ;Related tasks: * draw a sphere * draw a cuboid * draw a rotating cube * draw a Deathstar
#include <windows.h> #include <iostream> //-------------------------------------------------------------------------------------------------- using namespace std; //-------------------------------------------------------------------------------------------------- int main(int argc, char* argv[]) { cout << " ______ ______ " << endl << " _____ _____|\\ \\ _____|\\ \\ " << endl << " _____\\ \\_ / / | | / / | |" << endl << " / /| || |/ /|| |/ /|" << endl << " / / /____/|| |\\____/ || |\\____/ |" << endl << "| | |____|/ |\\ \\ | / |\\ \\ | / " << endl << "| | _____ | \\ \\___|/ | \\ \\___|/ " << endl << "|\\ \\|\\ \\ | \\ \\ | \\ \\ " << endl << "| \\_____\\| | \\ \\_____\\ \\ \\_____\\ " << endl << "| | /____/| \\ | | \\ | | " << endl << " \\|_____| || \\|_____| \\|_____| " << endl << " |____|/ "; cout << endl << endl << endl; system( "pause" ); return 0; } //--------------------------------------------------------------------------------------------------
Write to Windows event log
C++ from C
Write script status to the Windows Event Log
#include <iostream> #include <sstream> int main(int argc, char *argv[]) { using namespace std; #if _WIN32 if (argc != 5) { cout << "Usage : " << argv[0] << " (type) (id) (source string) (description>)\n"; cout << " Valid types: SUCCESS, ERROR, WARNING, INFORMATION\n"; } else { stringstream ss; ss << "EventCreate /t " << argv[1] << " /id " << argv[2] << " /l APPLICATION /so " << argv[3] << " /d \"" << argv[4] << "\""; system(ss.str().c_str()); } #else cout << "Not implemented for *nix, only windows.\n"; #endif return 0; }
Yellowstone sequence
C++
The '''Yellowstone sequence''', also called the '''Yellowstone permutation''', is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence. ;Example: a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2). ;Task : Find and show as output the first '''30''' Yellowstone numbers. ;Extra : Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers. ;Related tasks: :* Greatest common divisor. :* Plot coordinate pairs. ;See also: :* The OEIS entry: A098550 The Yellowstone permutation. :* Applegate et al, 2015: The Yellowstone Permutation [https://arxiv.org/abs/1501.01669].
#include <iostream> #include <numeric> #include <set> template <typename integer> class yellowstone_generator { public: integer next() { n2_ = n1_; n1_ = n_; if (n_ < 3) { ++n_; } else { for (n_ = min_; !(sequence_.count(n_) == 0 && std::gcd(n1_, n_) == 1 && std::gcd(n2_, n_) > 1); ++n_) {} } sequence_.insert(n_); for (;;) { auto it = sequence_.find(min_); if (it == sequence_.end()) break; sequence_.erase(it); ++min_; } return n_; } private: std::set<integer> sequence_; integer min_ = 1; integer n_ = 0; integer n1_ = 0; integer n2_ = 0; }; int main() { std::cout << "First 30 Yellowstone numbers:\n"; yellowstone_generator<unsigned int> ygen; std::cout << ygen.next(); for (int i = 1; i < 30; ++i) std::cout << ' ' << ygen.next(); std::cout << '\n'; return 0; }
Zeckendorf number representation
C++11
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution. ;Task: Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. ;Also see: * OEIS A014417 for the the sequence of required results. * Brown's Criterion - Numberphile ;Related task: * [[Fibonacci sequence]]
// For a class N which implements Zeckendorf numbers: // I define an increment operation ++() // I define a comparison operation <=(other N) // Nigel Galloway October 22nd., 2012 #include <iostream> class N { private: int dVal = 0, dLen; public: N(char const* x = "0"){ int i = 0, q = 1; for (; x[i] > 0; i++); for (dLen = --i/2; i >= 0; i--) { dVal+=(x[i]-48)*q; q*=2; }} const N& operator++() { for (int i = 0;;i++) { if (dLen < i) dLen = i; switch ((dVal >> (i*2)) & 3) { case 0: dVal += (1 << (i*2)); return *this; case 1: dVal += (1 << (i*2)); if (((dVal >> ((i+1)*2)) & 1) != 1) return *this; case 2: dVal &= ~(3 << (i*2)); }}} const bool operator<=(const N& other) const {return dVal <= other.dVal;} friend std::ostream& operator<<(std::ostream&, const N&); }; N operator "" N(char const* x) {return N(x);} std::ostream &operator<<(std::ostream &os, const N &G) { const static std::string dig[] {"00","01","10"}, dig1[] {"","1","10"}; if (G.dVal == 0) return os << "0"; os << dig1[(G.dVal >> (G.dLen*2)) & 3]; for (int i = G.dLen-1; i >= 0; i--) os << dig[(G.dVal >> (i*2)) & 3]; return os; }
Zero to the zero power
C++
Some computer programming languages are not exactly consistent (with other computer programming languages) when ''raising zero to the zeroth power'': 00 ;Task: Show the results of raising zero to the zeroth power. If your computer language objects to '''0**0''' or '''0^0''' at compile time, you may also try something like: x = 0 y = 0 z = x**y say 'z=' z '''Show the result here.''' And of course use any symbols or notation that is supported in your computer programming language for exponentiation. ;See also: * The Wiki entry: Zero to the power of zero. * The Wiki entry: Zero to the power of zero: History. * The MathWorld(tm) entry: exponent laws. ** Also, in the above MathWorld(tm) entry, see formula ('''9'''): x^0=1. * The OEIS entry: The special case of zero to the zeroth power
#include <iostream> #include <cmath> #include <complex> int main() { std::cout << "0 ^ 0 = " << std::pow(0,0) << std::endl; std::cout << "0+0i ^ 0+0i = " << std::pow(std::complex<double>(0),std::complex<double>(0)) << std::endl; return 0; }
Zhang-Suen thinning algorithm
C++
This is an algorithm used to thin a black and white i.e. one bit per pixel images. For example, with an input image of: ################# ############# ################## ################ ################### ################## ######## ####### ################### ###### ####### ####### ###### ###### ####### ####### ################# ####### ################ ####### ################# ####### ###### ####### ####### ###### ####### ####### ###### ####### ####### ###### ######## ####### ################### ######## ####### ###### ################## ###### ######## ####### ###### ################ ###### ######## ####### ###### ############# ###### It produces the thinned output: # ########## ####### ## # #### # # # ## # # # # # # # # # ############ # # # # # # # # # # # # # # ## # ############ ### ### ;Algorithm: Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes. The algorithm operates on all black pixels P1 that can have eight neighbours. The neighbours are, in order, arranged as: P9 P2 P3 P8 P1 P4 P7 P6 P5 Obviously the boundary pixels of the image cannot have the full eight neighbours. * Define A(P1) = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular). * Define B(P1) = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) ) ;Step 1: All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage. * (0) The pixel is black and has eight neighbours * (1) 2 <= B(P1) <= 6 * (2) A(P1) = 1 * (3) At least one of P2 and P4 and P6 is white * (4) At least one of P4 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white. ;Step 2: All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage. * (0) The pixel is black and has eight neighbours * (1) 2 <= B(P1) <= 6 * (2) A(P1) = 1 * (3) At least one of P2 and P4 and '''P8''' is white * (4) At least one of '''P2''' and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white. ;Iteration: If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed. ;Task: # Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes. # Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000 ;Reference: * Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza. * "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
#include <iostream> #include <string> #include <sstream> #include <valarray> const std::string input { "................................" ".#########.......########......." ".###...####.....####..####......" ".###....###.....###....###......" ".###...####.....###............." ".#########......###............." ".###.####.......###....###......" ".###..####..###.####..####.###.." ".###...####.###..########..###.." "................................" }; const std::string input2 { ".........................................................." ".#################...................#############........" ".##################...............################........" ".###################............##################........" ".########.....#######..........###################........" "...######.....#######.........#######.......######........" "...######.....#######........#######......................" "...#################.........#######......................" "...################..........#######......................" "...#################.........#######......................" "...######.....#######........#######......................" "...######.....#######........#######......................" "...######.....#######.........#######.......######........" ".########.....#######..........###################........" ".########.....#######.######....##################.######." ".########.....#######.######......################.######." ".########.....#######.######.........#############.######." ".........................................................." }; class ZhangSuen; class Image { public: friend class ZhangSuen; using pixel_t = char; static const pixel_t BLACK_PIX; static const pixel_t WHITE_PIX; Image(unsigned width = 1, unsigned height = 1) : width_{width}, height_{height}, data_( '\0', width_ * height_) {} Image(const Image& i) : width_{ i.width_}, height_{i.height_}, data_{i.data_} {} Image(Image&& i) : width_{ i.width_}, height_{i.height_}, data_{std::move(i.data_)} {} ~Image() = default; Image& operator=(const Image& i) { if (this != &i) { width_ = i.width_; height_ = i.height_; data_ = i.data_; } return *this; } Image& operator=(Image&& i) { if (this != &i) { width_ = i.width_; height_ = i.height_; data_ = std::move(i.data_); } return *this; } size_t idx(unsigned x, unsigned y) const noexcept { return y * width_ + x; } bool operator()(unsigned x, unsigned y) { return data_[idx(x, y)]; } friend std::ostream& operator<<(std::ostream& o, const Image& i) { o << i.width_ << " x " << i.height_ << std::endl; size_t px = 0; for(const auto& e : i.data_) { o << (e?Image::BLACK_PIX:Image::WHITE_PIX); if (++px % i.width_ == 0) o << std::endl; } return o << std::endl; } friend std::istream& operator>>(std::istream& in, Image& img) { auto it = std::begin(img.data_); const auto end = std::end(img.data_); Image::pixel_t tmp; while(in && it != end) { in >> tmp; if (tmp != Image::BLACK_PIX && tmp != Image::WHITE_PIX) throw "Bad character found in image"; *it = (tmp == Image::BLACK_PIX)?1:0; ++it; } return in; } unsigned width() const noexcept { return width_; } unsigned height() const noexcept { return height_; } struct Neighbours { // 9 2 3 // 8 1 4 // 7 6 5 Neighbours(const Image& img, unsigned p1_x, unsigned p1_y) : img_{img} , p1_{img.idx(p1_x, p1_y)} , p2_{p1_ - img.width()} , p3_{p2_ + 1} , p4_{p1_ + 1} , p5_{p4_ + img.width()} , p6_{p5_ - 1} , p7_{p6_ - 1} , p8_{p1_ - 1} , p9_{p2_ - 1} {} const Image& img_; const Image::pixel_t& p1() const noexcept { return img_.data_[p1_]; } const Image::pixel_t& p2() const noexcept { return img_.data_[p2_]; } const Image::pixel_t& p3() const noexcept { return img_.data_[p3_]; } const Image::pixel_t& p4() const noexcept { return img_.data_[p4_]; } const Image::pixel_t& p5() const noexcept { return img_.data_[p5_]; } const Image::pixel_t& p6() const noexcept { return img_.data_[p6_]; } const Image::pixel_t& p7() const noexcept { return img_.data_[p7_]; } const Image::pixel_t& p8() const noexcept { return img_.data_[p8_]; } const Image::pixel_t& p9() const noexcept { return img_.data_[p9_]; } const size_t p1_, p2_, p3_, p4_, p5_, p6_, p7_, p8_, p9_; }; Neighbours neighbours(unsigned x, unsigned y) const { return Neighbours(*this, x, y); } private: unsigned height_ { 0 }; unsigned width_ { 0 }; std::valarray<pixel_t> data_; }; constexpr const Image::pixel_t Image::BLACK_PIX = '#'; constexpr const Image::pixel_t Image::WHITE_PIX = '.'; class ZhangSuen { public: // the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2 unsigned transitions_white_black(const Image::Neighbours& a) const { unsigned sum = 0; sum += (a.p9() == 0) && a.p2(); sum += (a.p2() == 0) && a.p3(); sum += (a.p3() == 0) && a.p4(); sum += (a.p8() == 0) && a.p9(); sum += (a.p4() == 0) && a.p5(); sum += (a.p7() == 0) && a.p8(); sum += (a.p6() == 0) && a.p7(); sum += (a.p5() == 0) && a.p6(); return sum; } // The number of black pixel neighbours of P1. ( = sum(P2 .. P9) ) unsigned black_pixels(const Image::Neighbours& a) const { unsigned sum = 0; sum += a.p9(); sum += a.p2(); sum += a.p3(); sum += a.p8(); sum += a.p4(); sum += a.p7(); sum += a.p6(); sum += a.p5(); return sum; } const Image& operator()(const Image& img) { tmp_a_ = img; size_t changed_pixels = 0; do { changed_pixels = 0; // Step 1 tmp_b_ = tmp_a_; for(size_t y = 1; y < tmp_a_.height() - 1; ++y) { for(size_t x = 1; x < tmp_a_.width() - 1; ++x) { if (tmp_a_.data_[tmp_a_.idx(x, y)]) { auto n = tmp_a_.neighbours(x, y); auto bp = black_pixels(n); if (bp >= 2 && bp <= 6) { auto tr = transitions_white_black(n); if ( tr == 1 && (n.p2() * n.p4() * n.p6() == 0) && (n.p4() * n.p6() * n.p8() == 0) ) { tmp_b_.data_[n.p1_] = 0; ++changed_pixels; } } } } } // Step 2 tmp_a_ = tmp_b_; for(size_t y = 1; y < tmp_b_.height() - 1; ++y) { for(size_t x = 1; x < tmp_b_.width() - 1; ++x) { if (tmp_b_.data_[tmp_b_.idx(x, y)]) { auto n = tmp_b_.neighbours(x, y); auto bp = black_pixels(n); if (bp >= 2 && bp <= 6) { auto tr = transitions_white_black(n); if ( tr == 1 && (n.p2() * n.p4() * n.p8() == 0) && (n.p2() * n.p6() * n.p8() == 0) ) { tmp_a_.data_[n.p1_] = 0; ++changed_pixels; } } } } } } while(changed_pixels > 0); return tmp_a_; } private: Image tmp_a_; Image tmp_b_; }; int main(int argc, char const *argv[]) { using namespace std; Image img(32, 10); istringstream iss{input}; iss >> img; cout << img; cout << "ZhangSuen" << endl; ZhangSuen zs; Image res = std::move(zs(img)); cout << res << endl; Image img2(58,18); istringstream iss2{input2}; iss2 >> img2; cout << img2; cout << "ZhangSuen with big image" << endl; Image res2 = std::move(zs(img2)); cout << res2 << endl; return 0; }
100 doors
C
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it). The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door. ;Task: Answer the question: what state are the doors in after the last pass? Which are open, which are closed? '''Alternate:''' As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an optimization that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#include <stdio.h> #define NUM_DOORS 100 int main(int argc, char *argv[]) { int is_open[NUM_DOORS] = { 0 } ; int * doorptr, * doorlimit = is_open + NUM_DOORS ; int pass ; /* do the N passes, go backwards because the order is not important */ for ( pass= NUM_DOORS ; ( pass ) ; -- pass ) { for ( doorptr= is_open + ( pass-1 ); ( doorptr < doorlimit ) ; doorptr += pass ) { ( * doorptr ) ^= 1 ; } } /* output results */ for ( doorptr= is_open ; ( doorptr != doorlimit ) ; ++ doorptr ) { printf("door #%lld is %s\n", ( doorptr - is_open ) + 1, ( * doorptr ) ? "open" : "closed" ) ; } }
100 prisoners
C
The Problem: * 100 prisoners are individually numbered 1 to 100 * A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. * Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. * Prisoners start outside the room :* They can decide some strategy before any enter the room. :* Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. :* A prisoner can open no more than 50 drawers. :* A prisoner tries to find his own number. :* A prisoner finding his own number is then held apart from the others. * If '''all''' 100 prisoners find their own numbers then they will all be pardoned. If ''any'' don't then ''all'' sentences stand. ;The task: # Simulate several thousand instances of the game where the prisoners randomly open drawers # Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: :* First opening the drawer whose outside number is his prisoner number. :* If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum). Show and compare the computed probabilities of success for the two strategies, here, on this page. ;References: # The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). # [[wp:100 prisoners problem]] # 100 Prisoners Escape Puzzle DataGenetics. # Random permutation statistics#One hundred prisoners on Wikipedia.
#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; }
15 puzzle game
C
Implement the Fifteen Puzzle Game. The '''15-puzzle''' is also known as: :::* '''Fifteen Puzzle''' :::* '''Gem Puzzle''' :::* '''Boss Puzzle''' :::* '''Game of Fifteen''' :::* '''Mystic Square''' :::* '''14-15 Puzzle''' :::* and some others. ;Related Tasks: :* 15 Puzzle Solver :* [[16 Puzzle Game]]
/* * RosettaCode: Fifteen puzle game, C89, plain vanillia TTY, MVC */ #define _CRT_SECURE_NO_WARNINGS /* unlocks printf etc. in MSVC */ #include <stdio.h> #include <stdlib.h> #include <time.h> enum Move { MOVE_UP = 0, MOVE_DOWN = 1, MOVE_LEFT = 2, MOVE_RIGHT = 3 }; /* ***************************************************************************** * Model */ #define NROWS 4 #define NCOLLUMNS 4 int holeRow; int holeCollumn; int cells[NROWS][NCOLLUMNS]; const int nShuffles = 100; int Game_update(enum Move move){ const int dx[] = { 0, 0, -1, +1 }; const int dy[] = { -1, +1, 0, 0 }; int i = holeRow + dy[move]; int j = holeCollumn + dx[move]; if ( i >= 0 && i < NROWS && j >= 0 && j < NCOLLUMNS ){ cells[holeRow][holeCollumn] = cells[i][j]; cells[i][j] = 0; holeRow = i; holeCollumn = j; return 1; } return 0; } void Game_setup(void){ int i,j,k; for ( i = 0; i < NROWS; i++ ) for ( j = 0; j < NCOLLUMNS; j++ ) cells[i][j] = i * NCOLLUMNS + j + 1; cells[NROWS-1][NCOLLUMNS-1] = 0; holeRow = NROWS - 1; holeCollumn = NCOLLUMNS - 1; k = 0; while ( k < nShuffles ) k += Game_update((enum Move)(rand() % 4)); } int Game_isFinished(void){ int i,j; int k = 1; for ( i = 0; i < NROWS; i++ ) for ( j = 0; j < NCOLLUMNS; j++ ) if ( (k < NROWS*NCOLLUMNS) && (cells[i][j] != k++ ) ) return 0; return 1; } /* ***************************************************************************** * View */ void View_showBoard(){ int i,j; putchar('\n'); for ( i = 0; i < NROWS; i++ ) for ( j = 0; j < NCOLLUMNS; j++ ){ if ( cells[i][j] ) printf(j != NCOLLUMNS-1 ? " %2d " : " %2d \n", cells[i][j]); else printf(j != NCOLLUMNS-1 ? " %2s " : " %2s \n", ""); } putchar('\n'); } void View_displayMessage(char* text){ printf("\n%s\n", text); } /* ***************************************************************************** * Controller */ enum Move Controller_getMove(void){ int c; for(;;){ printf("%s", "enter u/d/l/r : "); c = getchar(); while( getchar() != '\n' ) ; switch ( c ){ case 27: exit(EXIT_SUCCESS); case 'd' : return MOVE_UP; case 'u' : return MOVE_DOWN; case 'r' : return MOVE_LEFT; case 'l' : return MOVE_RIGHT; } } } void Controller_pause(void){ getchar(); } int main(void){ srand((unsigned)time(NULL)); do Game_setup(); while ( Game_isFinished() ); View_showBoard(); while( !Game_isFinished() ){ Game_update( Controller_getMove() ); View_showBoard(); } View_displayMessage("You win"); Controller_pause(); return EXIT_SUCCESS; }
21 game
C
'''21''' is a two player game, the game is played by choosing a number ('''1''', '''2''', or '''3''') to be added to the ''running total''. The game is won by the player whose chosen number causes the ''running total'' to reach ''exactly'' '''21'''. The ''running total'' starts at zero. One player will be the computer. Players alternate supplying a number to be added to the ''running total''. ;Task: Write a computer program that will: ::* do the prompting (or provide a button menu), ::* check for errors and display appropriate error messages, ::* do the additions (add a chosen number to the ''running total''), ::* display the ''running total'', ::* provide a mechanism for the player to quit/exit/halt/stop/close the program, ::* issue a notification when there is a winner, and ::* determine who goes first (maybe a random or user choice, or can be specified when the game begins).
/** * Game 21 - an example in C language for Rosseta Code. * * A simple game program whose rules are described below * - see DESCRIPTION string. * * This program should be compatible with C89 and up. */ /* * Turn off MS Visual Studio panic warnings which disable to use old gold * library functions like printf, scanf etc. This definition should be harmless * for non-MS compilers. */ #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> /* * Define bool, true and false as needed. The stdbool.h is a standard header * in C99, therefore for older compilers we need DIY booleans. BTW, there is * no __STDC__VERSION__ predefined macro in MS Visual C, therefore we need * check also _MSC_VER. */ #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 /* * Spaces are meaningful: on some systems they can be visible. */ 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() { /* * There is a winning strategy for the first player. The second player can win * then and only then the frist player does not use the winning strategy. * * The winning strategy may be defined as best move for the given running total. * The running total is a number from 0 to GOAL. Therefore, for given GOAL, best * moves may be precomputed (and stored in a lookup table). Actually (when legal * moves are 1 or 2 or 3) the table may be truncated to four first elements. */ #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(); } } }
24 game
C
The 24 Game tests one's mental arithmetic. ;Task Write a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to '''24'''. * Only the following operators/functions are allowed: multiplication, division, addition, subtraction * Division should use floating point or rational arithmetic, etc, to preserve remainders. * Brackets are allowed, if using an infix expression evaluator. * Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). * The order of the digits when given does not have to be preserved. ;Notes * The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. * The task is not for the program to generate the expression, or test whether an expression is even possible. ;Related tasks * [[24 game/Solve]] ;Reference * The 24 Game on h2g2.
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <setjmp.h> #include <time.h> jmp_buf ctx; const char *msg; enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV }; typedef struct expr_t *expr, expr_t; struct expr_t { int op, val, used; expr left, right; }; #define N_DIGITS 4 expr_t digits[N_DIGITS]; void gen_digits() { int i; for (i = 0; i < N_DIGITS; i++) digits[i].val = 1 + rand() % 9; } #define MAX_INPUT 64 char str[MAX_INPUT]; int pos; #define POOL_SIZE 8 expr_t pool[POOL_SIZE]; int pool_ptr; void reset() { int i; msg = 0; pool_ptr = pos = 0; for (i = 0; i < POOL_SIZE; i++) { pool[i].op = OP_NONE; pool[i].left = pool[i].right = 0; } for (i = 0; i < N_DIGITS; i++) digits[i].used = 0; } /* longish jumpish back to input cycle */ void bail(const char *s) { msg = s; longjmp(ctx, 1); } expr new_expr() { if (pool_ptr < POOL_SIZE) return pool + pool_ptr++; return 0; } /* check next input char */ int next_tok() { while (isspace(str[pos])) pos++; return str[pos]; } /* move input pointer forward */ int take() { if (str[pos] != '\0') return ++pos; return 0; } /* BNF(ish) expr = term { ("+")|("-") term } term = fact { ("*")|("/") expr } fact = number | '(' expr ')' */ expr get_fact(); expr get_term(); expr get_expr(); expr get_expr() { int c; expr l, r, ret; if (!(ret = get_term())) bail("Expected term"); while ((c = next_tok()) == '+' || c == '-') { if (!take()) bail("Unexpected end of input"); if (!(r = get_term())) bail("Expected term"); l = ret; ret = new_expr(); ret->op = (c == '+') ? OP_ADD : OP_SUB; ret->left = l; ret->right = r; } return ret; } expr get_term() { int c; expr l, r, ret; ret = get_fact(); while((c = next_tok()) == '*' || c == '/') { if (!take()) bail("Unexpected end of input"); r = get_fact(); l = ret; ret = new_expr(); ret->op = (c == '*') ? OP_MUL : OP_DIV; ret->left = l; ret->right = r; } return ret; } expr get_digit() { int i, c = next_tok(); expr ret; if (c >= '0' && c <= '9') { take(); ret = new_expr(); ret->op = OP_NUM; ret->val = c - '0'; for (i = 0; i < N_DIGITS; i++) if (digits[i].val == ret->val && !digits[i].used) { digits[i].used = 1; return ret; } bail("Invalid digit"); } return 0; } expr get_fact() { int c; expr l = get_digit(); if (l) return l; if ((c = next_tok()) == '(') { take(); l = get_expr(); if (next_tok() != ')') bail("Unbalanced parens"); take(); return l; } return 0; } expr parse() { int i; expr ret = get_expr(); if (next_tok() != '\0') bail("Trailing garbage"); for (i = 0; i < N_DIGITS; i++) if (!digits[i].used) bail("Not all digits are used"); return ret; } typedef struct frac_t frac_t, *frac; struct frac_t { int denom, num; }; int gcd(int m, int n) { int t; while (m) { t = m; m = n % m; n = t; } return n; } /* evaluate expression tree. result in fraction form */ void eval_tree(expr e, frac res) { frac_t l, r; int t; if (e->op == OP_NUM) { res->num = e->val; res->denom = 1; return; } eval_tree(e->left, &l); eval_tree(e->right, &r); switch(e->op) { case OP_ADD: res->num = l.num * r.denom + l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_SUB: res->num = l.num * r.denom - l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_MUL: res->num = l.num * r.num; res->denom = l.denom * r.denom; break; case OP_DIV: res->num = l.num * r.denom; res->denom = l.denom * r.num; break; } if ((t = gcd(res->denom, res->num))) { res->denom /= t; res->num /= t; } } void get_input() { int i; reinput: reset(); printf("\nAvailable digits are:"); for (i = 0; i < N_DIGITS; i++) printf(" %d", digits[i].val); printf(". Type an expression and I'll check it for you, or make new numbers.\n" "Your choice? [Expr/n/q] "); while (1) { for (i = 0; i < MAX_INPUT; i++) str[i] = '\n'; fgets(str, MAX_INPUT, stdin); if (*str == '\0') goto reinput; if (str[MAX_INPUT - 1] != '\n') bail("string too long"); for (i = 0; i < MAX_INPUT; i++) if (str[i] == '\n') str[i] = '\0'; if (str[0] == 'q') { printf("Bye\n"); exit(0); } if (str[0] == 'n') { gen_digits(); goto reinput; } return; } } int main() { frac_t f; srand(time(0)); gen_digits(); while(1) { get_input(); setjmp(ctx); /* if parse error, jump back here with err msg set */ if (msg) { /* after error jump; announce, reset, redo */ printf("%s at '%.*s'\n", msg, pos, str); continue; } eval_tree(parse(), &f); if (f.denom == 0) bail("Divide by zero"); if (f.denom == 1 && f.num == 24) printf("You got 24. Very good.\n"); else { if (f.denom == 1) printf("Eval to: %d, ", f.num); else printf("Eval to: %d/%d, ", f.num, f.denom); printf("no good. Try again.\n"); } } return 0; }
24 game/Solve
C
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the [[24 game]]. Show examples of solutions generated by the program. ;Related task: * [[Arithmetic Evaluator]]
#include <stdio.h> typedef struct {int val, op, left, right;} Node; Node nodes[10000]; int iNodes; int b; float eval(Node x){ if (x.op != -1){ float l = eval(nodes[x.left]), r = eval(nodes[x.right]); switch(x.op){ case 0: return l+r; case 1: return l-r; case 2: return r-l; case 3: return l*r; case 4: return r?l/r:(b=1,0); case 5: return l?r/l:(b=1,0); } } else return x.val*1.; } void show(Node x){ if (x.op != -1){ printf("("); switch(x.op){ case 0: show(nodes[x.left]); printf(" + "); show(nodes[x.right]); break; case 1: show(nodes[x.left]); printf(" - "); show(nodes[x.right]); break; case 2: show(nodes[x.right]); printf(" - "); show(nodes[x.left]); break; case 3: show(nodes[x.left]); printf(" * "); show(nodes[x.right]); break; case 4: show(nodes[x.left]); printf(" / "); show(nodes[x.right]); break; case 5: show(nodes[x.right]); printf(" / "); show(nodes[x.left]); break; } printf(")"); } else printf("%d", x.val); } int float_fix(float x){ return x < 0.00001 && x > -0.00001; } void solutions(int a[], int n, float t, int s){ if (s == n){ b = 0; float e = eval(nodes[0]); if (!b && float_fix(e-t)){ show(nodes[0]); printf("\n"); } } else{ nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1}; for (int op = 0; op < 6; op++){ int k = iNodes-1; for (int i = 0; i < k; i++){ nodes[iNodes++] = nodes[i]; nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2}; solutions(a, n, t, s+1); nodes[i] = nodes[--iNodes]; } } iNodes--; } }; int main(){ // define problem int a[4] = {8, 3, 8, 3}; float t = 24; // print all solutions nodes[0] = (typeof(Node)){a[0],-1,-1,-1}; iNodes = 1; solutions(a, sizeof(a)/sizeof(int), t, 1); return 0; }
4-rings or 4-squares puzzle
C
Replace '''a, b, c, d, e, f,''' and '''g ''' with the decimal digits LOW ---> HIGH such that the sum of the letters inside of each of the four large squares add up to the same sum. +--------------+ +--------------+ | | | | | a | | e | | | | | | +---+------+---+ +---+---------+ | | | | | | | | | | b | | d | | f | | | | | | | | | | | | | | | | | | +----------+---+ +---+------+---+ | | c | | g | | | | | | | | | +--------------+ +-------------+ Show all output here. :* Show all solutions for each letter being unique with LOW=1 HIGH=7 :* Show all solutions for each letter being unique with LOW=3 HIGH=9 :* Show only the ''number'' of solutions when each letter can be non-unique LOW=0 HIGH=9 ;Related task: * [[Solve the no connection 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); }
A+B
C
'''A+B''' --- a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used. ;Task: Given two integers, '''A''' and '''B'''. Their sum needs to be calculated. ;Input data: Two integers are written in the input stream, separated by space(s): : (-1000 \le A,B \le +1000) ;Output data: The required output is one integer: the sum of '''A''' and '''B'''. ;Example: ::{|class="standard" ! input ! output |- | 2 2 | 4 |- | 3 2 | 5 |}
// Input file: input.txt // Output file: output.txt #include <stdio.h> int main() { freopen("input.txt", "rt", stdin); freopen("output.txt", "wt", stdout); int a, b; scanf("%d%d", &a, &b); printf("%d\n", a + b); return 0; }
ABC problem
C
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sides of the blocks. The sample collection of blocks: (B O) (X K) (D Q) (C P) (N A) (G T) (R E) (T G) (Q D) (F S) (J W) (H U) (V I) (A N) (O B) (E R) (F S) (L Y) (P C) (Z M) ;Task: Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple: ::# Once a letter on a block is used that block cannot be used again ::# The function should be case-insensitive ::# Show the output on this page for the following 7 words in the following example ;Example: >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True
#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; }
ASCII art diagram converter
C
Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string: http://www.ietf.org/rfc/rfc1035.txt +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ Where (every column of the table is 1 bit): ID is 16 bits QR = Query (0) or Response (1) Opcode = Four bits defining kind of query: 0: a standard query (QUERY) 1: an inverse query (IQUERY) 2: a server status request (STATUS) 3-15: reserved for future use AA = Authoritative Answer bit TC = Truncation bit RD = Recursion Desired bit RA = Recursion Available bit Z = Reserved RCODE = Response code QC = Question Count ANC = Answer Count AUC = Authority Count ADC = Additional Count Write a function, member function, class or template that accepts a similar multi-line string as input to define a data structure or something else able to decode or store a header with that specified bit structure. If your language has macros, introspection, code generation, or powerful enough templates, then accept such string at compile-time to define the header data structure statically. Such "Header" function or template should accept a table with 8, 16, 32 or 64 columns, and any number of rows. For simplicity the only allowed symbols to define the table are + - | (plus, minus, pipe), and whitespace. Lines of the input string composed just of whitespace should be ignored. Leading and trailing whitespace in the input string should be ignored, as well as before and after each table row. The box for each bit of the diagram takes four chars "+--+". The code should perform a little of validation of the input string, but for brevity a full validation is not required. Bonus: perform a thoroughly validation of the input string.
#include <stdlib.h> #include <stdio.h> #include <string.h> enum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 }; char *Lines[MAX_ROWS] = { " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ID |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " |QR| Opcode |AA|TC|RD|RA| Z | RCODE |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | QDCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ANCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | NSCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ARCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" }; typedef struct { unsigned bit3s; unsigned mask; unsigned data; char A[NAME_SZ+2]; }NAME_T; NAME_T names[MAX_NAMES]; unsigned idx_name; enum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR}; unsigned header[MAX_HDR]; // for test unsigned idx_hdr; int bit_hdr(char *pLine); int bit_names(char *pLine); void dump_names(void); void make_test_hdr(void); int main(void){ char *p1; int rv; printf("Extract meta-data from bit-encoded text form\n"); make_test_hdr(); idx_name = 0; for( int i=0; i<MAX_ROWS;i++ ){ p1 = Lines[i]; if( p1==NULL ) break; if( rv = bit_hdr(Lines[i]), rv>0) continue; if( rv = bit_names(Lines[i]),rv>0) continue; //printf("%s, %d\n",p1, numbits ); } dump_names(); } int bit_hdr(char *pLine){ // count the '+--' char *p1 = strchr(pLine,'+'); if( p1==NULL ) return 0; int numbits=0; for( int i=0; i<strlen(p1)-1; i+=3 ){ if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0; numbits++; } return numbits; } int bit_names(char *pLine){ // count the bit-group names char *p1,*p2 = pLine, tmp[80]; unsigned sz=0, maskbitcount = 15; while(1){ p1 = strchr(p2,'|'); if( p1==NULL ) break; p1++; p2 = strchr(p1,'|'); if( p2==NULL ) break; sz = p2-p1; tmp[sz] = 0; // set end of string int k=0; for(int j=0; j<sz;j++){ // strip spaces if( p1[j] > ' ') tmp[k++] = p1[j]; } tmp[k]= 0; sz++; NAME_T *pn = &names[idx_name++]; strcpy(&pn->A[0], &tmp[0]); pn->bit3s = sz/3; if( pn->bit3s < 16 ){ for( int i=0; i<pn->bit3s; i++){ pn->mask |= 1 << maskbitcount--; } pn->data = header[idx_hdr] & pn->mask; unsigned m2 = pn->mask; while( (m2 & 1)==0 ){ m2>>=1; pn->data >>= 1; } if( pn->mask == 0xf ) idx_hdr++; } else{ pn->data = header[idx_hdr++]; } } return sz; } void dump_names(void){ // print extracted names and bits NAME_T *pn; printf("-name-bits-mask-data-\n"); for( int i=0; i<MAX_NAMES; i++ ){ pn = &names[i]; if( pn->bit3s < 1 ) break; printf("%10s %2d X%04x = %u\n",pn->A, pn->bit3s, pn->mask, pn->data); } puts("bye.."); } void make_test_hdr(void){ header[ID] = 1024; header[QDCOUNT] = 12; header[ANCOUNT] = 34; header[NSCOUNT] = 56; header[ARCOUNT] = 78; // QR OP AA TC RD RA Z RCODE // 1 0110 1 0 1 0 000 1010 // 1011 0101 0000 1010 // B 5 0 A header[BITS] = 0xB50A; }
Abbreviations, easy
C
This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]]. For this task, the following ''command table'' will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up Notes concerning the above ''command table'': ::* it can be thought of as one long literal string (with blanks at end-of-lines) ::* it may have superfluous blanks ::* it may be in any case (lower/upper/mixed) ::* the order of the words in the ''command table'' must be preserved as shown ::* the user input(s) may be in any case (upper/lower/mixed) ::* commands will be restricted to the Latin alphabet (A --> Z, a --> z) ::* A valid abbreviation is a word that has: :::* at least the minimum length of the number of capital letters of the word in the ''command table'' :::* compares equal (regardless of case) to the leading characters of the word in the ''command table'' :::* a length not longer than the word in the ''command table'' ::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer''' ::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer''' ::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters ::::* Any word longer than five characters can't be an abbreviation for '''ALTer''' ::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay''' ::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted ;Task: ::* The command table needn't be verified/validated. ::* Write a function to validate if the user "words" (given as input) are valid (in the ''command table''). ::* If the word is valid, then return the full uppercase version of that "word". ::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters). ::* A blank input (or a null input) should return a null string. ::* Show all output here. ;An example test case to be used for this task: For a user string of: riG rePEAT copies put mo rest types fup. 6 poweRin the computer program should return the string: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; // str is assumed to be all uppercase bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } // convert string to uppercase char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } size_t get_min_length(const char* str, size_t n) { size_t len = 0; while (len < n && isupper((unsigned char)str[len])) ++len; return len; } void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = get_min_length(word, word_len); new_cmd->cmd = uppercase(word, word_len); new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(" input: %s\n", input); printf("output:"); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*"); free(word); } free(words); printf("\n"); } int main() { command_t* commands = make_command_list(command_table); const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; test(commands, input); free_command_list(commands); return 0; }
Abbreviations, simple
C
The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an easy way to add flexibility when specifying or using commands, sub-commands, options, etc. For this task, the following ''command table'' will be used: add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 Notes concerning the above ''command table'': ::* it can be thought of as one long literal string (with blanks at end-of-lines) ::* it may have superfluous blanks ::* it may be in any case (lower/upper/mixed) ::* the order of the words in the ''command table'' must be preserved as shown ::* the user input(s) may be in any case (upper/lower/mixed) ::* commands will be restricted to the Latin alphabet (A --> Z, a --> z) ::* a command is followed by an optional number, which indicates the minimum abbreviation ::* A valid abbreviation is a word that has: :::* at least the minimum length of the word's minimum number in the ''command table'' :::* compares equal (regardless of case) to the leading characters of the word in the ''command table'' :::* a length not longer than the word in the ''command table'' ::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3''' ::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3''' ::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters ::::* Any word longer than five characters can't be an abbreviation for '''ALTER''' ::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1''' ::* if there isn't a number after the command, then there isn't an abbreviation permitted ;Task: ::* The command table needn't be verified/validated. ::* Write a function to validate if the user "words" (given as input) are valid (in the ''command table''). ::* If the word is valid, then return the full uppercase version of that "word". ::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters). ::* A blank input (or a null input) should return a null string. ::* Show all output here. ;An example test case to be used for this task: For a user string of: riG rePEAT copies put mo rest types fup. 6 poweRin the computer program should return the string: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; // str is assumed to be all uppercase bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } // convert string to uppercase char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = word_len; new_cmd->cmd = uppercase(word, word_len); if (i + 1 < count) { char* eptr = 0; unsigned long min_len = strtoul(words[i + 1], &eptr, 10); if (min_len > 0 && *eptr == 0) { free(words[i + 1]); new_cmd->min_len = min_len; ++i; } } new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(" input: %s\n", input); printf("output:"); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*"); free(word); } free(words); printf("\n"); } int main() { command_t* commands = make_command_list(command_table); const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; test(commands, input); free_command_list(commands); return 0; }
Abelian sandpile model
C
{{wikipedia|Abelian sandpile model}} Implement the '''Abelian sandpile model''' also known as '''Bak-Tang-Wiesenfeld model'''. Its history, mathematical definition and properties can be found under its wikipedia article. The task requires the creation of a 2D grid of arbitrary size on which "piles of sand" can be placed. Any "pile" that has 4 or more sand particles on it ''collapses'', resulting in '''four particles being subtracted from the pile''' and '''distributed among its neighbors.''' It is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task. Examples up to 2^30, wow! javascript running on web '''Examples:''' 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 4 0 0 -> 0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 6 0 0 -> 0 1 2 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 2 1 2 0 0 0 16 0 0 -> 1 1 0 1 1 0 0 0 0 0 0 2 1 2 0 0 0 0 0 0 0 0 1 0 0
#include<stdlib.h> #include<string.h> #include<stdio.h> int main(int argc, char** argv) { int i,j,sandPileEdge, centerPileHeight, processAgain = 1,top,down,left,right; int** sandPile; char* fileName; static unsigned char colour[3]; if(argc!=3){ printf("Usage: %s <Sand pile side> <Center pile height>",argv[0]); return 0; } sandPileEdge = atoi(argv[1]); centerPileHeight = atoi(argv[2]); if(sandPileEdge<=0 || centerPileHeight<=0){ printf("Sand pile and center pile dimensions must be positive integers."); return 0; } sandPile = (int**)malloc(sandPileEdge * sizeof(int*)); for(i=0;i<sandPileEdge;i++){ sandPile[i] = (int*)calloc(sandPileEdge,sizeof(int)); } sandPile[sandPileEdge/2][sandPileEdge/2] = centerPileHeight; printf("Initial sand pile :\n\n"); for(i=0;i<sandPileEdge;i++){ for(j=0;j<sandPileEdge;j++){ printf("%3d",sandPile[i][j]); } printf("\n"); } while(processAgain == 1){ processAgain = 0; top = 0; down = 0; left = 0; right = 0; for(i=0;i<sandPileEdge;i++){ for(j=0;j<sandPileEdge;j++){ if(sandPile[i][j]>=4){ if(i-1>=0){ top = 1; sandPile[i-1][j]+=1; if(sandPile[i-1][j]>=4) processAgain = 1; } if(i+1<sandPileEdge){ down = 1; sandPile[i+1][j]+=1; if(sandPile[i+1][j]>=4) processAgain = 1; } if(j-1>=0){ left = 1; sandPile[i][j-1]+=1; if(sandPile[i][j-1]>=4) processAgain = 1; } if(j+1<sandPileEdge){ right = 1; sandPile[i][j+1]+=1; if(sandPile[i][j+1]>=4) processAgain = 1; } sandPile[i][j] -= (top + down + left + right); if(sandPile[i][j]>=4) processAgain = 1; } } } } printf("Final sand pile : \n\n"); for(i=0;i<sandPileEdge;i++){ for(j=0;j<sandPileEdge;j++){ printf("%3d",sandPile[i][j]); } printf("\n"); } fileName = (char*)malloc((strlen(argv[1]) + strlen(argv[2]) + 23)*sizeof(char)); strcpy(fileName,"Final_Sand_Pile_"); strcat(fileName,argv[1]); strcat(fileName,"_"); strcat(fileName,argv[2]); strcat(fileName,".ppm"); FILE *fp = fopen(fileName,"wb"); fprintf(fp,"P6\n%d %d\n255\n",sandPileEdge,sandPileEdge); for(i=0;i<sandPileEdge;i++){ for(j=0;j<sandPileEdge;j++){ colour[0] = (sandPile[i][j] + i)%256; colour[1] = (sandPile[i][j] + j)%256; colour[2] = (sandPile[i][j] + i*j)%256; fwrite(colour,1,3,fp); } } fclose(fp); printf("\nImage file written to %s\n",fileName); return 0; }
Abundant odd numbers
C
An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''', or, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''. ;E.G.: '''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n'''); or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n'''). Abundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers. To make things more interesting, this task is specifically about finding ''odd abundant numbers''. ;Task *Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum. *Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum. *Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum. ;References: :* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n) :* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)
#include <stdio.h> #include <math.h> // The following function is for odd numbers ONLY // Please use "for (unsigned i = 2, j; i*i <= n; i ++)" for even and odd numbers 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; }
Accumulator factory
C
{{requires|Mutable State}} A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). ;Rules: The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text''). :Before you submit an example, make sure the function :# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used :# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)'' :# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)'' :# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)'' :# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)'' : E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'': :: x = foo(1); x(5); foo(3); print x(2.3); : It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)'' ;Task: Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#include <stdio.h> //~ Take a number n and return a function that takes a number i #define ACCUMULATOR(name,n) __typeof__(n) name (__typeof__(n) i) { \ static __typeof__(n) _n=n; LOGIC; } //~ have it return n incremented by the accumulation of i #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)); /* 6.000000 */ printf ("%f\n", x(2.3)); /* 8.300000 */ printf ("%i\n", y(5.0)); /* 8 */ printf ("%i\n", y(3.3)); /* 11 */ printf ("%c\n", z(5)); /* f */ return 0; }
Aliquot sequence classifications
C
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the [[Proper divisors]] of the previous term. :* If the terms eventually reach 0 then the series for K is said to '''terminate'''. :There are several classifications for non termination: :* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''. :* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''. :* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''. :Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions... :* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''. :* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''. :And finally: :* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. ;Task: # Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above. # Use it to display the classification and sequences of the numbers one to ten inclusive. # Use it to show the classification and sequences of the following integers, in order: :: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080. Show all output on this page. ;Related tasks: * [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence). * [[Proper divisors]] * [[Amicable pairs]]
#include<string.h> #include<stdlib.h> #include<stdio.h> unsigned long long raiseTo(unsigned long long base, unsigned long long power){ unsigned long long result = 1,i; for (i=0; i<power;i++) { result*=base; } return result; } unsigned long long properDivisorSum(unsigned long long n){ unsigned long long prod = 1; unsigned long long temp = n,i,count = 0; while(n%2 == 0){ count++; n /= 2; } if(count!=0) prod *= (raiseTo(2,count + 1) - 1); for(i=3;i*i<=n;i+=2){ count = 0; while(n%i == 0){ count++; n /= i; } if(count==1) prod *= (i+1); else if(count > 1) prod *= ((raiseTo(i,count + 1) - 1)/(i-1)); } if(n>2) prod *= (n+1); return prod - temp; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); } void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j; arr[0] = n; for(i=1;i<16;i++){ arr[i] = properDivisorSum(arr[i-1]); if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; } for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } } printSeries(arr,i+1,"Non-Terminating"); } void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21]; while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10)); fclose(fp); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }
Amb
C
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure. Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails. For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence: #"the" "that" "a" #"frog" "elephant" "thing" #"walked" "treaded" "grows" #"slowly" "quickly" The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
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; }
Anagrams/Deranged anagrams
C
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words. ;Task Use the word list at unixdict to find and display the longest deranged anagram. ;Related * [[Permutations/Derangements]] * Best shuffle {{Related tasks/Word plays}}
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <fcntl.h> #include <sys/stat.h> // Letter lookup by frequency. This is to reduce word insertion time. const char *freq = "zqxjkvbpygfwmucldrhsnioate"; int char_to_idx[128]; // Trie structure of sorts 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; /* count words, change newline to null */ 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; }
Angle difference between two bearings
C
Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings] ;Task: Find the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. Input bearings are expressed in the range '''-180''' to '''+180''' degrees. The result is also expressed in the range '''-180''' to '''+180''' degrees. Compute the angle for the following pairs: * 20 degrees ('''b1''') and 45 degrees ('''b2''') * -45 and 45 * -85 and 90 * -95 and 90 * -45 and 125 * -45 and 145 * 29.4803 and -88.6381 * -78.3251 and -159.036 ;Optional extra: Allow the input bearings to be any (finite) value. ;Test cases: * -70099.74233810938 and 29840.67437876723 * -165313.6666297357 and 33693.9894517456 * 1174.8380510598456 and -154146.66490124757 * 60175.77306795546 and 42213.07192354373
#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; }
Apply a digital filter (direct form II transposed)
C
Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [https://ccrma.stanford.edu/~jos/fp/Transposed_Direct_Forms.html] ;Task: Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667] The signal that needs filtering is the following vector: [-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] ;See also: [Wikipedia on Butterworth filters]
#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; }
Archimedean spiral
C
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: :\, r=a+b\theta with real numbers ''a'' and ''b''. ;Task Draw an Archimedean spiral.
#include<graphics.h> #include<stdio.h> #include<math.h> #define pi M_PI int main(){ double a,b,cycles,incr,i; int steps,x=500,y=500; printf("Enter the parameters a and b : "); scanf("%lf%lf",&a,&b); printf("Enter cycles : "); scanf("%lf",&cycles); printf("Enter divisional steps : "); scanf("%d",&steps); incr = 1.0/steps; initwindow(1000,1000,"Archimedean Spiral"); for(i=0;i<=cycles*pi;i+=incr){ putpixel(x + (a + b*i)*cos(i),x + (a + b*i)*sin(i),15); } getch(); closegraph(); }
Arena storage pool
C
Dynamically allocated objects take their memory from a [[heap]]. The memory for an object is provided by an '''allocator''' which maintains the storage pool used for the [[heap]]. Often a call to allocator is denoted as P := new T where '''T''' is the type of an allocated object, and '''P''' is a [[reference]] to the object. The storage pool chosen by the allocator can be determined by either: * the object type '''T''' * the type of pointer '''P''' In the former case objects can be allocated only in one storage pool. In the latter case objects of the type can be allocated in any storage pool or on the [[stack]]. ;Task: The task is to show how allocators and user-defined storage pools are supported by the language. In particular: # define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups. # allocate some objects (e.g., integers) in the pool. Explain what controls the storage pool choice in the language.
#include <sys/mman.h> #include <unistd.h> #include <stdio.h> // VERY rudimentary C memory management independent of C library's malloc. // Linked list (yes, this is inefficient) struct __ALLOCC_ENTRY__ { void * allocatedAddr; size_t size; struct __ALLOCC_ENTRY__ * next; }; typedef struct __ALLOCC_ENTRY__ __ALLOCC_ENTRY__; // Keeps track of allocated memory and metadata __ALLOCC_ENTRY__ * __ALLOCC_ROOT__ = NULL; __ALLOCC_ENTRY__ * __ALLOCC_TAIL__ = NULL; // Add new metadata to the table void _add_mem_entry(void * location, size_t size) { __ALLOCC_ENTRY__ * newEntry = (__ALLOCC_ENTRY__ *) mmap(NULL, sizeof(__ALLOCC_ENTRY__), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (__ALLOCC_TAIL__ != NULL) { __ALLOCC_TAIL__ -> next = newEntry; __ALLOCC_TAIL__ = __ALLOCC_TAIL__ -> next; } else { // Create new table __ALLOCC_ROOT__ = newEntry; __ALLOCC_TAIL__ = newEntry; } __ALLOCC_ENTRY__ * tail = __ALLOCC_TAIL__; tail -> allocatedAddr = location; tail -> size = size; tail -> next = NULL; __ALLOCC_TAIL__ = tail; } // Remove metadata from the table given pointer size_t _remove_mem_entry(void * location) { __ALLOCC_ENTRY__ * curNode = __ALLOCC_ROOT__; // Nothing to do if (curNode == NULL) { return 0; } // First entry matches if (curNode -> allocatedAddr == location) { __ALLOCC_ROOT__ = curNode -> next; size_t chunkSize = curNode -> size; // No nodes left if (__ALLOCC_ROOT__ == NULL) { __ALLOCC_TAIL__ = NULL; } munmap(curNode, sizeof(__ALLOCC_ENTRY__)); return chunkSize; } // If next node is null, remove it while (curNode -> next != NULL) { __ALLOCC_ENTRY__ * nextNode = curNode -> next; if (nextNode -> allocatedAddr == location) { size_t chunkSize = nextNode -> size; if(curNode -> next == __ALLOCC_TAIL__) { __ALLOCC_TAIL__ = curNode; } curNode -> next = nextNode -> next; munmap(nextNode, sizeof(__ALLOCC_ENTRY__)); return chunkSize; } curNode = nextNode; } // Nothing was found return 0; } // Allocate a block of memory with size // When customMalloc an already mapped location, causes undefined behavior void * customMalloc(size_t size) { // Now we can use 0 as our error state if (size == 0) { return NULL; } void * mapped = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); // Store metadata _add_mem_entry(mapped, size); return mapped; } // Free a block of memory that has been customMalloc'ed void customFree(void * addr) { size_t size = _remove_mem_entry(addr); munmap(addr, size); } int main(int argc, char const *argv[]) { int *p1 = customMalloc(4*sizeof(int)); // allocates enough for an array of 4 int int *p2 = customMalloc(sizeof(int[4])); // same, naming the type directly int *p3 = customMalloc(4*sizeof *p3); // same, without repeating the type name if(p1) { for(int n=0; n<4; ++n) // populate the array p1[n] = n*n; for(int n=0; n<4; ++n) // print it back out printf("p1[%d] == %d\n", n, p1[n]); } customFree(p1); customFree(p2); customFree(p3); return 0; }
Arithmetic-geometric mean
C
{{wikipedia|Arithmetic-geometric mean}} ;Task: Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as \mathrm{agm}(a,g), and is equal to the limit of the sequence: : a_0 = a; \qquad g_0 = g : a_{n+1} = \tfrac{1}{2}(a_n + g_n); \quad g_{n+1} = \sqrt{a_n g_n}. Since the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: :\mathrm{agm}(1,1/\sqrt{2}) ;Also see: * mathworld.wolfram.com/Arithmetic-Geometric Mean
/*Arithmetic Geometric Mean of 1 and 1/sqrt(2) Nigel_Galloway February 7th., 2012. */ #include "gmp.h" void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) { mpf_add (out1, in1, in2); mpf_div_ui (out1, out1, 2); mpf_mul (out2, in1, in2); mpf_sqrt (out2, out2); } int main (void) { mpf_set_default_prec (65568); mpf_t x0, y0, resA, resB; mpf_init_set_ui (y0, 1); mpf_init_set_d (x0, 0.5); mpf_sqrt (x0, x0); mpf_init (resA); mpf_init (resB); for(int i=0; i<7; i++){ agm(x0, y0, resA, resB); agm(resA, resB, x0, y0); } gmp_printf ("%.20000Ff\n", x0); gmp_printf ("%.20000Ff\n\n", y0); return 0; }
Arithmetic-geometric mean/Calculate Pi
C
Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate \pi. With the same notations used in [[Arithmetic-geometric mean]], we can summarize the paper by writing: \pi = \frac{4\; \mathrm{agm}(1, 1/\sqrt{2})^2} {1 - \sum\limits_{n=1}^{\infty} 2^{n+1}(a_n^2-g_n^2)} This allows you to make the approximation, for any large '''N''': \pi \approx \frac{4\; a_N^2} {1 - \sum\limits_{k=1}^N 2^{k+1}(a_k^2-g_k^2)} The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of \pi.
See [[Talk:Arithmetic-geometric mean]] <!-- Example by Nigel Galloway, Feb 8, 2012 -->
Arithmetic numbers
C
Definition A positive integer '''n''' is an arithmetic number if the average of its positive divisors is also an integer. Clearly all odd primes '''p''' must be arithmetic numbers because their only divisors are '''1''' and '''p''' whose sum is even and hence their average must be an integer. However, the prime number '''2''' is not an arithmetic number because the average of its divisors is 1.5. ;Example 30 is an arithmetic number because its 7 divisors are: [1, 2, 3, 5, 6, 10, 15, 30], their sum is 72 and average 9 which is an integer. ;Task Calculate and show here: 1. The first 100 arithmetic numbers. 2. The '''x'''th arithmetic number where '''x''' = 1,000 and '''x''' = 10,000. 3. How many of the first '''x''' arithmetic numbers are composite. Note that, technically, the arithmetic number '''1''' is neither prime nor composite. ;Stretch Carry out the same exercise in 2. and 3. above for '''x''' = 100,000 and '''x''' = 1,000,000. ;References * Wikipedia: Arithmetic number * OEIS:A003601 - Numbers n such that the average of the divisors of n is an integer
#include <stdio.h> void divisor_count_and_sum(unsigned int n, unsigned int* pcount, unsigned int* psum) { unsigned int divisor_count = 1; unsigned int divisor_sum = 1; unsigned int power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) { ++divisor_count; divisor_sum += power; } for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1, sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { ++count; sum += power; } divisor_count *= count; divisor_sum *= sum; } if (n > 1) { divisor_count *= 2; divisor_sum *= n + 1; } *pcount = divisor_count; *psum = divisor_sum; } int main() { unsigned int arithmetic_count = 0; unsigned int composite_count = 0; for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) { unsigned int divisor_count; unsigned int divisor_sum; divisor_count_and_sum(n, &divisor_count, &divisor_sum); if (divisor_sum % divisor_count != 0) continue; ++arithmetic_count; if (divisor_count > 2) ++composite_count; if (arithmetic_count <= 100) { printf("%3u ", n); if (arithmetic_count % 10 == 0) printf("\n"); } if (arithmetic_count == 1000 || arithmetic_count == 10000 || arithmetic_count == 100000 || arithmetic_count == 1000000) { printf("\n%uth arithmetic number is %u\n", arithmetic_count, n); printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count); } } return 0; }
Array length
C
Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'.
#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings #define _CRT_NONSTDC_NO_WARNINGS // enable old-gold POSIX names in MSVS #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> struct StringArray { size_t sizeOfArray; size_t numberOfElements; char** elements; }; typedef struct StringArray* StringArray; StringArray StringArray_new(size_t size) { StringArray this = calloc(1, sizeof(struct StringArray)); if (this) { this->elements = calloc(size, sizeof(int)); if (this->elements) this->sizeOfArray = size; else { free(this); this = NULL; } } return this; } void StringArray_delete(StringArray* ptr_to_this) { assert(ptr_to_this != NULL); StringArray this = (*ptr_to_this); if (this) { for (size_t i = 0; i < this->sizeOfArray; i++) free(this->elements[i]); free(this->elements); free(this); this = NULL; } } void StringArray_add(StringArray this, ...) { char* s; va_list args; va_start(args, this); while (this->numberOfElements < this->sizeOfArray && (s = va_arg(args, char*))) this->elements[this->numberOfElements++] = strdup(s); va_end(args); } int main(int argc, char* argv[]) { StringArray a = StringArray_new(10); StringArray_add(a, "apple", "orange", NULL); printf( "There are %d elements in an array with a capacity of %d elements:\n\n", a->numberOfElements, a->sizeOfArray); for (size_t i = 0; i < a->numberOfElements; i++) printf(" the element %d is the string \"%s\"\n", i, a->elements[i]); StringArray_delete(&a); return EXIT_SUCCESS; }
Average loop length
C
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence. ;Task: Write a program or a script that estimates, for each N, the average length until the first such repetition. Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one. This problem comes from the end of Donald Knuth's Christmas tree lecture 2011. Example of expected output: N average analytical (error) === ========= ============ ========= 1 1.0000 1.0000 ( 0.00%) 2 1.4992 1.5000 ( 0.05%) 3 1.8784 1.8889 ( 0.56%) 4 2.2316 2.2188 ( 0.58%) 5 2.4982 2.5104 ( 0.49%) 6 2.7897 2.7747 ( 0.54%) 7 3.0153 3.0181 ( 0.09%) 8 3.2429 3.2450 ( 0.07%) 9 3.4536 3.4583 ( 0.14%) 10 3.6649 3.6602 ( 0.13%) 11 3.8091 3.8524 ( 1.12%) 12 3.9986 4.0361 ( 0.93%) 13 4.2074 4.2123 ( 0.12%) 14 4.3711 4.3820 ( 0.25%) 15 4.5275 4.5458 ( 0.40%) 16 4.6755 4.7043 ( 0.61%) 17 4.8877 4.8579 ( 0.61%) 18 4.9951 5.0071 ( 0.24%) 19 5.1312 5.1522 ( 0.41%) 20 5.2699 5.2936 ( 0.45%)
#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; }
Averages/Mean angle
C
{{Related tasks/Statistical measures}}
#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; }
Averages/Pythagorean means
C
{{Related tasks/Statistical measures}}
#include <stdio.h> #include <stdlib.h> // atoi() #include <math.h> // pow() 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(" c:%d\n s:%f\n p:%f\n r:%f\n",count,sum,prod,resum); 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; }
Averages/Root mean square
C
Task Compute the Root mean square of the numbers 1..10. The ''root mean square'' is also known by its initials RMS (or rms), and as the '''quadratic mean'''. The RMS is calculated as the mean of the squares of the numbers, square-rooted: ::: x_{\mathrm{rms}} = \sqrt {{{x_1}^2 + {x_2}^2 + \cdots + {x_n}^2} \over n}. ;See also {{Related tasks/Statistical measures}}
#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; }
Babbage problem
C
Charles Babbage Charles Babbage's analytical engine. Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: {{quote | What is the smallest positive integer whose square ends in the digits 269,696? | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125. }} He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain. ;Task The task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred. For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L]. ;Motivation The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
// This code is the implementation of Babbage Problem #include <stdio.h> #include <stdlib.h> #include <limits.h> int main() { int current = 0, //the current number square; //the square of the current number //the strategy of take the rest of division by 1e06 is //to take the a number how 6 last digits are 269696 while (((square=current*current) % 1000000 != 269696) && (square<INT_MAX)) { current++; } //output 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); //the end return 0 ; }
Balanced brackets
C
'''Task''': * Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. * Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. ;Examples: (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#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; }
Barnsley fern
C
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). ;Task: Create this fractal fern, using the following transformations: * f1 (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn * f2 (chosen 85% of the time) xn + 1 = 0.85 xn + 0.04 yn yn + 1 = -0.04 xn + 0.85 yn + 1.6 * f3 (chosen 7% of the time) xn + 1 = 0.2 xn - 0.26 yn yn + 1 = 0.23 xn + 0.22 yn + 1.6 * f4 (chosen 7% of the time) xn + 1 = -0.15 xn + 0.28 yn yn + 1 = 0.26 xn + 0.24 yn + 0.44. Starting position: x = 0, y = 0
#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; }
Benford's law
C
{{Wikipedia|Benford's_law}} '''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d (d \in \{1, \ldots, 9\}) occurs with probability :::: P(d) = \log_{10}(d+1)-\log_{10}(d) = \log_{10}\left(1+\frac{1}{d}\right) For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. ''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. ;See also: * numberphile.com. * A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.
#include <stdio.h> #include <stdlib.h> #include <math.h> float *benford_distribution(void) { static float prob[9]; for (int i = 1; i < 10; i++) prob[i - 1] = log10f(1 + 1.0 / i); return prob; } float *get_actual_distribution(char *fn) { FILE *input = fopen(fn, "r"); if (!input) { perror("Can't open file"); exit(EXIT_FAILURE); } int tally[9] = { 0 }; char c; int total = 0; while ((c = getc(input)) != EOF) { /* get the first nonzero digit on the current line */ while (c < '1' || c > '9') c = getc(input); tally[c - '1']++; total++; /* discard rest of line */ while ((c = getc(input)) != '\n' && c != EOF) ; } fclose(input); static float freq[9]; for (int i = 0; i < 9; i++) freq[i] = tally[i] / (float) total; return freq; } int main(int argc, char **argv) { if (argc != 2) { printf("Usage: benford <file>\n"); return EXIT_FAILURE; } float *actual = get_actual_distribution(argv[1]); float *expected = benford_distribution(); puts("digit\tactual\texpected"); for (int i = 0; i < 9; i++) printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]); return EXIT_SUCCESS; }
Best shuffle
C
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Display the result as follows: original string, shuffled string, (score) The score gives the number of positions whose character value did ''not'' change. ;Example: tree, eetr, (0) ;Test cases: abracadabra seesaw elk grrrrrr up a ;Related tasks * [[Anagrams/Deranged anagrams]] * [[Permutations/Derangements]]
#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 // txt and result must have the same length assert(len == strlen(result)); #endif // how many of each character? 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); // all character positions, grouped by character 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++; } // regroup them for cycles 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; } } // how long can our cyclic groups be? const size_t grp = 1 + (len - 1) / fmax; assert(grp > 0 && grp <= len); // how many of them are full length? const size_t lng = 1 + (len - 1) % fmax; assert(lng > 0 && lng <= len); // rotate each group 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 is original permuted according to our cyclic groups 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; }
Bin given limits
C
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] ..'' bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] ;Task: The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will ''print the limit of each bin together with the count of items that fell in the range''. Assume the numbers to bin are too large to practically sort. ;Task examples: Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [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] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [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] Show output here, on this page.
#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; }
Bioinformatics/Sequence mutation
C
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: # Choosing a random base position in the sequence. # Mutate the sequence by doing one of either: ## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base) ## '''D'''elete the chosen base at the position. ## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position. # Randomly generate a test DNA sequence of at least 200 bases # "Pretty print" the sequence and a count of its size, and the count of each base in the sequence # Mutate the sequence ten times. # "Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence. ;Extra credit: * Give more information on the individual mutations applied. * Allow mutations to be weighted and/or chosen.
#include<stdlib.h> #include<stdio.h> #include<time.h> typedef struct genome{ char base; struct genome *next; }genome; typedef struct{ char mutation; int position; }genomeChange; typedef struct{ int adenineCount,thymineCount,cytosineCount,guanineCount; }baseCounts; genome *strand; baseCounts baseData; int genomeLength = 100, lineLength = 50; int numDigits(int num){ int len = 1; while(num>10){ num /= 10; len++; } return len; } void generateStrand(){ int baseChoice = rand()%4, i; genome *strandIterator, *newStrand; baseData.adenineCount = 0; baseData.thymineCount = 0; baseData.cytosineCount = 0; baseData.guanineCount = 0; strand = (genome*)malloc(sizeof(genome)); strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); strand->next = NULL; strandIterator = strand; for(i=1;i<genomeLength;i++){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = NULL; strandIterator->next = newStrand; strandIterator = newStrand; } } genomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){ int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight); genomeChange mutationCommand; mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D'); mutationCommand.position = rand()%genomeLength; return mutationCommand; } void printGenome(){ int rows, width = numDigits(genomeLength), len = 0,i,j; lineLength = (genomeLength<lineLength)?genomeLength:lineLength; rows = genomeLength/lineLength + (genomeLength%lineLength!=0); genome* strandIterator = strand; printf("\n\nGenome : \n--------\n"); for(i=0;i<rows;i++){ printf("\n%*d%3s",width,len,":"); for(j=0;j<lineLength && strandIterator!=NULL;j++){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } len += lineLength; } while(strandIterator!=NULL){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } printf("\n\nBase Counts\n-----------"); printf("\n%*c%3s%*d",width,'A',":",width,baseData.adenineCount); printf("\n%*c%3s%*d",width,'T',":",width,baseData.thymineCount); printf("\n%*c%3s%*d",width,'C',":",width,baseData.cytosineCount); printf("\n%*c%3s%*d",width,'G',":",width,baseData.guanineCount); printf("\n\nTotal:%*d",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount); printf("\n"); } void mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){ int i,j,width,baseChoice; genomeChange newMutation; genome *strandIterator, *strandFollower, *newStrand; for(i=0;i<numMutations;i++){ strandIterator = strand; strandFollower = strand; newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight); width = numDigits(genomeLength); for(j=0;j<newMutation.position;j++){ strandFollower = strandIterator; strandIterator = strandIterator->next; } if(newMutation.mutation=='S'){ if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='C'){ strandIterator->base='G'; printf("\nSwapping C at position : %*d with G",width,newMutation.position); } else{ strandIterator->base='C'; printf("\nSwapping G at position : %*d with C",width,newMutation.position); } } else if(newMutation.mutation=='I'){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); printf("\nInserting %c at position : %*d",newStrand->base,width,newMutation.position); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = strandIterator; strandFollower->next = newStrand; genomeLength++; } else{ strandFollower->next = strandIterator->next; strandIterator->next = NULL; printf("\nDeleting %c at position : %*d",strandIterator->base,width,newMutation.position); free(strandIterator); genomeLength--; } } } int main(int argc,char* argv[]) { int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10; if(argc==1||argc>6){ printf("Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\n",argv[0]); return 0; } switch(argc){ case 2: genomeLength = atoi(argv[1]); break; case 3: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); break; case 4: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); break; case 5: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); break; case 6: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); deleteWeight = atoi(argv[5]); break; }; srand(time(NULL)); generateStrand(); printf("\nOriginal:"); printGenome(); mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight); printf("\n\nMutated:"); printGenome(); return 0; }
Bioinformatics/base count
C
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT ;Task: :* "Pretty print" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence :* print the total count of each base in the string.
#include<string.h> #include<stdlib.h> #include<stdio.h> typedef struct genome{ char* strand; int length; struct genome* next; }genome; genome* genomeData; int totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0; int numDigits(int num){ int len = 1; while(num>10){ num = num/10; len++; } return len; } void buildGenome(char str[100]){ int len = strlen(str),i; genome *genomeIterator, *newGenome; totalLength += len; for(i=0;i<len;i++){ switch(str[i]){ case 'A': Adenine++; break; case 'T': Thymine++; break; case 'C': Cytosine++; break; case 'G': Guanine++; break; }; } if(genomeData==NULL){ genomeData = (genome*)malloc(sizeof(genome)); genomeData->strand = (char*)malloc(len*sizeof(char)); strcpy(genomeData->strand,str); genomeData->length = len; genomeData->next = NULL; } else{ genomeIterator = genomeData; while(genomeIterator->next!=NULL) genomeIterator = genomeIterator->next; newGenome = (genome*)malloc(sizeof(genome)); newGenome->strand = (char*)malloc(len*sizeof(char)); strcpy(newGenome->strand,str); newGenome->length = len; newGenome->next = NULL; genomeIterator->next = newGenome; } } void printGenome(){ genome* genomeIterator = genomeData; int width = numDigits(totalLength), len = 0; printf("Sequence:\n"); while(genomeIterator!=NULL){ printf("\n%*d%3s%3s",width+1,len,":",genomeIterator->strand); len += genomeIterator->length; genomeIterator = genomeIterator->next; } printf("\n\nBase Count\n----------\n\n"); printf("%3c%3s%*d\n",'A',":",width+1,Adenine); printf("%3c%3s%*d\n",'T',":",width+1,Thymine); printf("%3c%3s%*d\n",'C',":",width+1,Cytosine); printf("%3c%3s%*d\n",'G',":",width+1,Guanine); printf("\n%3s%*d\n","Total:",width+1,Adenine + Thymine + Cytosine + Guanine); free(genomeData); } int main(int argc,char** argv) { char str[100]; int counter = 0, len; if(argc!=2){ printf("Usage : %s <Gene file name>\n",argv[0]); return 0; } FILE *fp = fopen(argv[1],"r"); while(fscanf(fp,"%s",str)!=EOF) buildGenome(str); fclose(fp); printGenome(); return 0; }
Bitcoin/address validation
C
Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters: :::* 0 zero :::* O uppercase oh :::* I uppercase eye :::* l lowercase ell With this encoding, a bitcoin address encodes 25 bytes: * the first byte is the version number, which will be zero for this task ; * the next twenty bytes are a [[RIPEMD-160]] digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ; * the last four bytes are a checksum check. They are the first four bytes of a double [[SHA-256]] digest of the previous 21 bytes. To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes. The program can either return a boolean value or throw an exception when not valid. You can use a digest library for [[SHA-256]]. ;Example of a bitcoin address: 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i It doesn't belong to anyone and is part of the test suite of the bitcoin software. You can change a few characters in this string and check that it'll fail the test.
#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; }
Bitcoin/public point to address
C
elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: * take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed string ; * add one byte prefix equal to 4 (it is a convention for this way of encoding a public point) ; * compute the [[SHA-256]] of this string ; * compute the [[RIPEMD-160]] of this SHA-256 digest ; * compute the checksum of the concatenation of the version number digit (a single zero byte) and this RIPEMD-160 digest, as described in [[bitcoin/address validation]] ; * Base-58 encode (see below) the concatenation of the version number (zero in this case), the ripemd digest and the checksum The base-58 encoding is based on an alphabet of alphanumeric characters (numbers, upper case and lower case, in that order) but without the four characters 0, O, l and I. Here is an example public point: X = 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352 Y = 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6 The corresponding address should be: 16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM Nb. The leading '1' is not significant as 1 is zero in base-58. It is however often added to the bitcoin address for various reasons. There can actually be several of them. You can ignore this and output an address without the leading 1. ''Extra credit:'' add a verification procedure about the public point, making sure it belongs to the secp256k1 elliptic curve
#include <stdio.h> #include <string.h> #include <ctype.h> #include <openssl/sha.h> #include <openssl/ripemd.h> #define COIN_VER 0 const char *coin_err; typedef unsigned char byte; int is_hex(const char *s) { int i; for (i = 0; i < 64; i++) if (!isxdigit(s[i])) return 0; return 1; } void str_to_byte(const char *src, byte *dst, int n) { while (n--) sscanf(src + n * 2, "%2hhx", dst + n); } char* base58(byte *s, char *out) { static const char *tmpl = "123456789" "ABCDEFGHJKLMNPQRSTUVWXYZ" "abcdefghijkmnopqrstuvwxyz"; static char buf[40]; int c, i, n; if (!out) out = buf; out[n = 34] = 0; while (n--) { for (c = i = 0; i < 25; i++) { c = c * 256 + s[i]; s[i] = c / 58; c %= 58; } out[n] = tmpl[c]; } for (n = 0; out[n] == '1'; n++); memmove(out, out + n, 34 - n); return out; } char *coin_encode(const char *x, const char *y, char *out) { byte s[65]; byte rmd[5 + RIPEMD160_DIGEST_LENGTH]; if (!is_hex(x) || !(is_hex(y))) { coin_err = "bad public point string"; return 0; } s[0] = 4; str_to_byte(x, s + 1, 32); str_to_byte(y, s + 33, 32); rmd[0] = COIN_VER; RIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1); memcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4); return base58(rmd, out); } int main(void) { puts(coin_encode( "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352", "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6", 0)); return 0; }
Bitwise IO
C
The aim of this task is to write functions (or create a class if yourlanguage is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always ''quantized'' by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0'''000''' (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a '''rough''' (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see [[LZW compression]]) use fixed or variable ''words'' nine (or more) bits long. * Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. * Errors handling is not mandatory
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> typedef uint8_t byte; typedef struct { FILE *fp; uint32_t accu; int bits; } bit_io_t, *bit_filter; bit_filter b_attach(FILE *f) { bit_filter b = malloc(sizeof(bit_io_t)); b->bits = b->accu = 0; b->fp = f; return b; } void b_write(byte *buf, size_t n_bits, size_t shift, bit_filter bf) { uint32_t accu = bf->accu; int bits = bf->bits; buf += shift / 8; shift %= 8; while (n_bits || bits >= 8) { while (bits >= 8) { bits -= 8; fputc(accu >> bits, bf->fp); accu &= (1 << bits) - 1; } while (bits < 8 && n_bits) { accu = (accu << 1) | (((128 >> shift) & *buf) >> (7 - shift)); --n_bits; bits++; if (++shift == 8) { shift = 0; buf++; } } } bf->accu = accu; bf->bits = bits; } size_t b_read(byte *buf, size_t n_bits, size_t shift, bit_filter bf) { uint32_t accu = bf->accu; int bits = bf->bits; int mask, i = 0; buf += shift / 8; shift %= 8; while (n_bits) { while (bits && n_bits) { mask = 128 >> shift; if (accu & (1 << (bits - 1))) *buf |= mask; else *buf &= ~mask; n_bits--; bits--; if (++shift >= 8) { shift = 0; buf++; } } if (!n_bits) break; accu = (accu << 8) | fgetc(bf->fp); bits += 8; } bf->accu = accu; bf->bits = bits; return i; } void b_detach(bit_filter bf) { if (bf->bits) { bf->accu <<= 8 - bf->bits; fputc(bf->accu, bf->fp); } free(bf); } int main() { unsigned char s[] = "abcdefghijk"; unsigned char s2[11] = {0}; int i; FILE *f = fopen("test.bin", "wb"); bit_filter b = b_attach(f); /* for each byte in s, write 7 bits skipping 1 */ for (i = 0; i < 10; i++) b_write(s + i, 7, 1, b); b_detach(b); fclose(f); /* read 7 bits and expand to each byte of s2 skipping 1 bit */ f = fopen("test.bin", "rb"); b = b_attach(f); for (i = 0; i < 10; i++) b_read(s2 + i, 7, 1, b); b_detach(b); fclose(f); printf("%10s\n", s2); /* should be the same first 10 bytes as in s */ return 0; }
Box the compass
C
Avast me hearties! There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! ;Task description: # Create a function that takes a heading in degrees and returns the correct 32-point compass heading. # Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: :[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). ;Notes; * The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 * The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#include <stdio.h> int main() { int i, j; double degrees[] = { 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38 }; const char * names = "North " "North by east " "North-northeast " "Northeast by north " "Northeast " "Northeast by east " "East-northeast " "East by north " "East " "East by south " "East-southeast " "Southeast by east " "Southeast " "Southeast by south " "South-southeast " "South by east " "South " "South by west " "South-southwest " "Southwest by south " "Southwest " "Southwest by west " "West-southwest " "West by south " "West " "West by north " "West-northwest " "Northwest by west " "Northwest " "Northwest by north " "North-northwest " "North by west " "North "; for (i = 0; i < 33; i++) { j = .5 + degrees[i] * 32 / 360; printf("%2d %.22s %6.2f\n", (j % 32) + 1, names + (j % 32) * 22, degrees[i]); } return 0; }
CSV data manipulation
C
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. ;Task: Read a CSV file, change some values and save the changes back to a file. For this task we will use the following CSV file: C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 Suggestions Show how to add a column, headed 'SUM', of the sums of the rows. If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
#define TITLE "CSV data manipulation" #define URL "http://rosettacode.org/wiki/CSV_data_manipulation" #define _GNU_SOURCE #define bool int #include <stdio.h> #include <stdlib.h> /* malloc...*/ #include <string.h> /* strtok...*/ #include <ctype.h> #include <errno.h> /** * How to read a CSV file ? */ typedef struct { char * delim; unsigned int rows; unsigned int cols; char ** table; } CSV; /** * Utility function to trim whitespaces from left & right of a string */ int trim(char ** str) { int trimmed; int n; int len; len = strlen(*str); n = len - 1; /* from right */ while((n>=0) && isspace((*str)[n])) { (*str)[n] = '\0'; trimmed += 1; n--; } /* from left */ n = 0; while((n < len) && (isspace((*str)[0]))) { (*str)[0] = '\0'; *str = (*str)+1; trimmed += 1; n++; } return trimmed; } /** * De-allocate csv structure */ int csv_destroy(CSV * csv) { if (csv == NULL) { return 0; } if (csv->table != NULL) { free(csv->table); } if (csv->delim != NULL) { free(csv->delim); } free(csv); return 0; } /** * Allocate memory for a CSV structure */ CSV * csv_create(unsigned int cols, unsigned int rows) { CSV * csv; csv = malloc(sizeof(CSV)); csv->rows = rows; csv->cols = cols; csv->delim = strdup(","); csv->table = malloc(sizeof(char *) * cols * rows); if (csv->table == NULL) { goto error; } memset(csv->table, 0, sizeof(char *) * cols * rows); return csv; error: csv_destroy(csv); return NULL; } /** * Get value in CSV table at COL, ROW */ char * csv_get(CSV * csv, unsigned int col, unsigned int row) { unsigned int idx; idx = col + (row * csv->cols); return csv->table[idx]; } /** * Set value in CSV table at COL, ROW */ int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { unsigned int idx; idx = col + (row * csv->cols); csv->table[idx] = value; return 0; } void csv_display(CSV * csv) { int row, col; char * content; if ((csv->rows == 0) || (csv->cols==0)) { printf("[Empty table]\n"); return ; } printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); for (row=0; row<csv->rows; row++) { printf("[|"); for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); printf("%s\t|", content); } printf("]\n"); } printf("\n"); } /** * Resize CSV table */ int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { unsigned int cur_col, cur_row, max_cols, max_rows; CSV * new_csv; char * content; bool in_old, in_new; /* Build a new (fake) csv */ new_csv = csv_create(new_cols, new_rows); if (new_csv == NULL) { goto error; } new_csv->rows = new_rows; new_csv->cols = new_cols; max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; for (cur_col=0; cur_col<max_cols; cur_col++) { for (cur_row=0; cur_row<max_rows; cur_row++) { in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows); in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); if (in_old && in_new) { /* re-link data */ content = csv_get(old_csv, cur_col, cur_row); csv_set(new_csv, cur_col, cur_row, content); } else if (in_old) { /* destroy data */ content = csv_get(old_csv, cur_col, cur_row); free(content); } else { /* skip */ } } } /* on rows */ free(old_csv->table); old_csv->rows = new_rows; old_csv->cols = new_cols; old_csv->table = new_csv->table; new_csv->table = NULL; csv_destroy(new_csv); return 0; error: printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); return -1; } /** * Open CSV file and load its content into provided CSV structure **/ int csv_open(CSV * csv, char * filename) { FILE * fp; unsigned int m_rows; unsigned int m_cols, cols; char line[2048]; char * lineptr; char * token; fp = fopen(filename, "r"); if (fp == NULL) { goto error; } m_rows = 0; m_cols = 0; while(fgets(line, sizeof(line), fp) != NULL) { m_rows += 1; cols = 0; lineptr = line; while ((token = strtok(lineptr, csv->delim)) != NULL) { lineptr = NULL; trim(&token); cols += 1; if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } } fclose(fp); csv->rows = m_rows; csv->cols = m_cols; return 0; error: fclose(fp); printf("Unable to open %s for reading.", filename); return -1; } /** * Open CSV file and save CSV structure content into it **/ int csv_save(CSV * csv, char * filename) { FILE * fp; int row, col; char * content; fp = fopen(filename, "w"); for (row=0; row<csv->rows; row++) { for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); fprintf(fp, "%s%s", content, ((col == csv->cols-1) ? "" : csv->delim) ); } fprintf(fp, "\n"); } fclose(fp); return 0; } /** * Test */ int main(int argc, char ** argv) { CSV * csv; printf("%s\n%s\n\n",TITLE, URL); csv = csv_create(0, 0); csv_open(csv, "fixtures/csv-data-manipulation.csv"); csv_display(csv); csv_set(csv, 0, 0, "Column0"); csv_set(csv, 1, 1, "100"); csv_set(csv, 2, 2, "200"); csv_set(csv, 3, 3, "300"); csv_set(csv, 4, 4, "400"); csv_display(csv); csv_save(csv, "tmp/csv-data-manipulation.result.csv"); csv_destroy(csv); return 0; }
CSV to HTML translation
C
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be ''escaped'' when converted to HTML ;Task: Create a function that takes a string representation of the CSV data and returns a text string of an HTML table representing the CSV data. Use the following data as the CSV text to convert, and show your output. : Character,Speech : The multitude,The messiah! Show us the messiah! : Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! : The multitude,Who are you? : Brians mother,I'm his mother; that's who! : The multitude,Behold his mother! Behold his mother! ;Extra credit: ''Optionally'' allow special formatting for the first row of the table as if it is the tables header row (via preferably; CSS if you must).
#include <stdio.h> const char *input = "Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" "Brians mother,<angry>Now you listen here! He's not the messiah; " "he's a very naughty boy! Now go away!</angry>\n" "The multitude,Who are you?\n" "Brians mother,I'm his mother; that's who!\n" "The multitude,Behold his mother! Behold his mother!"; int main() { const char *s; printf("<table>\n<tr><td>"); for (s = input; *s; s++) { switch(*s) { case '\n': printf("</td></tr>\n<tr><td>"); break; case ',': printf("</td><td>"); break; case '<': printf("&lt;"); break; case '>': printf("&gt;"); break; case '&': printf("&amp;"); break; default: putchar(*s); } } puts("</td></tr>\n</table>"); return 0; }
Calculating the value of e
C
Calculate the value of ''e''. (''e'' is also known as ''Euler's number'' and ''Napier's constant''.) See details: Calculating the value of e
#include <stdio.h> #include <math.h> int main(void) { double e; puts("The double precision in C give about 15 significant digits.\n" "Values below are presented with 16 digits after the decimal point.\n"); // The most direct way to compute Euler constant. // e = exp(1); printf("Euler constant e = %.16lf\n", e); // The fast and independed method: e = lim (1 + 1/n)**n // e = 1.0 + 0x1p-26; for (int i = 0; i < 26; i++) e *= e; printf("Euler constant e = %.16lf\n", e); // Taylor expansion e = 1 + 1/1 + 1/2 + 1/2/3 + 1/2/3/4 + 1/2/3/4/5 + ... // Actually Kahan summation may improve the accuracy, but is not necessary. // const int N = 1000; double a[1000]; a[0] = 1.0; for (int i = 1; i < N; i++) { a[i] = a[i-1] / i; } e = 1.; for (int i = N - 1; i > 0; i--) e += a[i]; printf("Euler constant e = %.16lf\n", e); return 0; }
Call a function
C
Demonstrate the different syntax and semantics provided for calling a function. This may include: :* Calling a function that requires no arguments :* Calling a function with a fixed number of arguments :* Calling a function with optional arguments :* Calling a function with a variable number of arguments :* Calling a function with named arguments :* Using a function in statement context :* Using a function in first-class context within an expression :* Obtaining the return value of a function :* Distinguishing built-in functions and user-defined functions :* Distinguishing subroutines and functions ;* Stating whether arguments are passed by value or by reference ;* Is partial application possible and how This task is ''not'' about defining functions.
/* function with no argument */ f(); /* fix number of arguments */ g(1, 2, 3); /* Optional arguments: err... Feel free to make sense of the following. I can't. */ int op_arg(); int main() { op_arg(1); op_arg(1, 2); op_arg(1, 2, 3); return 0; } int op_arg(int a, int b) { printf("%d %d %d\n", a, b, (&b)[1]); return a; } /* end of sensible code */ /* Variadic function: how the args list is handled solely depends on the function */ void h(int a, ...) { va_list ap; va_start(ap); ... } /* call it as: (if you feed it something it doesn't expect, don't count on it working) */ h(1, 2, 3, 4, "abcd", (void*)0); /* named arguments: this is only possible through some pre-processor abuse */ struct v_args { int arg1; int arg2; char _sentinel; }; void _v(struct v_args args) { printf("%d, %d\n", args.arg1, args.arg2); } #define v(...) _v((struct v_args){__VA_ARGS__}) v(.arg2 = 5, .arg1 = 17); // prints "17,5" /* NOTE the above implementation gives us optional typesafe optional arguments as well (unspecified arguments are initialized to zero)*/ v(.arg2=1); // prints "0,1" v(); // prints "0,0" /* as a first-class object (i.e. function pointer) */ printf("%p", f); /* that's the f() above */ /* return value */ double a = asin(1); /* built-in functions: no such thing. Compiler may interally give special treatment to bread-and-butter functions such as memcpy(), but that's not a C built-in per se */ /* subroutines: no such thing. You can goto places, but I doubt that counts. */ /* Scalar values are passed by value by default. However, arrays are passed by reference. */ /* Pointers *sort of* work like references, though. */
Canonicalize CIDR
C
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. ;Example: Given '''87.70.141.1/22''', your code should output '''87.70.140.0/22''' ;Explanation: An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion. In general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry. The example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0. ;More examples for testing 36.18.154.103/12 - 36.16.0.0/12 62.62.197.11/29 - 62.62.197.8/29 67.137.119.181/4 - 64.0.0.0/4 161.214.74.21/24 - 161.214.74.0/24 184.232.176.184/18 - 184.232.128.0/18
#include <stdbool.h> #include <stdio.h> #include <stdint.h> typedef struct cidr_tag { uint32_t address; unsigned int mask_length; } cidr_t; // Convert a string in CIDR format to an IPv4 address and netmask, // if possible. Also performs CIDR canonicalization. bool cidr_parse(const char* str, cidr_t* cidr) { int a, b, c, d, m; if (sscanf(str, "%d.%d.%d.%d/%d", &a, &b, &c, &d, &m) != 5) return false; if (m < 1 || m > 32 || a < 0 || a > UINT8_MAX || b < 0 || b > UINT8_MAX || c < 0 || c > UINT8_MAX || d < 0 || d > UINT8_MAX) return false; uint32_t mask = ~((1 << (32 - m)) - 1); uint32_t address = (a << 24) + (b << 16) + (c << 8) + d; address &= mask; cidr->address = address; cidr->mask_length = m; return true; } // Write a string in CIDR notation into the supplied buffer. void cidr_format(const cidr_t* cidr, char* str, size_t size) { uint32_t address = cidr->address; unsigned int d = address & UINT8_MAX; address >>= 8; unsigned int c = address & UINT8_MAX; address >>= 8; unsigned int b = address & UINT8_MAX; address >>= 8; unsigned int a = address & UINT8_MAX; snprintf(str, size, "%u.%u.%u.%u/%u", a, b, c, d, cidr->mask_length); } int main(int argc, char** argv) { const char* tests[] = { "87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29", "67.137.119.181/4", "161.214.74.21/24", "184.232.176.184/18" }; for (int i = 0; i < sizeof(tests)/sizeof(tests[0]); ++i) { cidr_t cidr; if (cidr_parse(tests[i], &cidr)) { char out[32]; cidr_format(&cidr, out, sizeof(out)); printf("%-18s -> %s\n", tests[i], out); } else { fprintf(stderr, "%s: invalid CIDR\n", tests[i]); } } return 0; }
Cartesian product of two or more lists
C
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: ::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: ::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using your function/method, that the product of an empty list with any other list is empty. :: {1, 2} x {} = {} :: {} x {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: :: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1} :: {1, 2, 3} x {30} x {500, 100} :: {1, 2, 3} x {} x {500, 100}
#include<string.h> #include<stdlib.h> #include<stdio.h> void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){ int i,j; if(times==numSets){ printf("("); for(i=0;i<times;i++){ printf("%d,",currentSet[i]); } printf("\b),"); } else{ for(j=0;j<setLengths[times];j++){ currentSet[times] = sets[times][j]; cartesianProduct(sets,setLengths,currentSet,numSets,times+1); } } } void printSets(int** sets, int* setLengths, int numSets){ int i,j; printf("\nNumber of sets : %d",numSets); for(i=0;i<numSets+1;i++){ printf("\nSet %d : ",i+1); for(j=0;j<setLengths[i];j++){ printf(" %d ",sets[i][j]); } } } void processInputString(char* str){ int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0; char *token,*holder,*holderToken; for(i=0;str[i]!=00;i++) if(str[i]=='x') numSets++; if(numSets==0){ printf("\n%s",str); return; } currentSet = (int*)calloc(sizeof(int),numSets + 1); setLengths = (int*)calloc(sizeof(int),numSets + 1); sets = (int**)malloc((numSets + 1)*sizeof(int*)); token = strtok(str,"x"); while(token!=NULL){ holder = (char*)malloc(strlen(token)*sizeof(char)); j = 0; for(i=0;token[i]!=00;i++){ if(token[i]>='0' && token[i]<='9') holder[j++] = token[i]; else if(token[i]==',') holder[j++] = ' '; } holder[j] = 00; setLength = 0; for(i=0;holder[i]!=00;i++) if(holder[i]==' ') setLength++; if(setLength==0 && strlen(holder)==0){ printf("\n{}"); return; } setLengths[counter] = setLength+1; sets[counter] = (int*)malloc((1+setLength)*sizeof(int)); k = 0; start = 0; for(l=0;holder[l]!=00;l++){ if(holder[l+1]==' '||holder[l+1]==00){ holderToken = (char*)malloc((l+1-start)*sizeof(char)); strncpy(holderToken,holder + start,l+1-start); sets[counter][k++] = atoi(holderToken); start = l+2; } } counter++; token = strtok(NULL,"x"); } printf("\n{"); cartesianProduct(sets,setLengths,currentSet,numSets + 1,0); printf("\b}"); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]); else processInputString(argV[1]); return 0; }
Catalan numbers/Pascal's triangle
C
Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle. ;See: * Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction. * Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition. * Sequence A000108 on OEIS has a lot of information on Catalan Numbers. ;Related Tasks: [[Pascal's triangle]]
//This code implements the print of 15 first Catalan's Numbers //Formula used: // __n__ // | | (n + k) / k n>0 // k=2 #include <stdio.h> #include <stdlib.h> //the number of Catalan's Numbers to be printed const int N = 15; int main() { //loop variables (in registers) register int k, n; //necessarily ull for reach big values unsigned long long int num, den; //the nmmber int catalan; //the first is not calculated for the formula printf("1 "); //iterating from 2 to 15 for (n=2; n<=N; ++n) { //initializaing for products num = den = 1; //applying the formula for (k=2; k<=n; ++k) { num *= (n+k); den *= k; catalan = num /den; } //output printf("%d ", catalan); } //the end printf("\n"); return 0; }
Catamorphism
C
''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. ;Task: Show how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language. ;See also: * Wikipedia article: Fold * Wikipedia article: Catamorphism
#include <stdio.h> typedef int (*intFn)(int, int); int reduce(intFn fn, int size, int *elms) { int i, val = *elms; for (i = 1; i < size; ++i) val = fn(val, elms[i]); return val; } int add(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; } int mul(int a, int b) { return a * b; } int main(void) { int nums[] = {1, 2, 3, 4, 5}; printf("%d\n", reduce(add, 5, nums)); printf("%d\n", reduce(sub, 5, nums)); printf("%d\n", reduce(mul, 5, nums)); return 0; }
Chaos game
C
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. ;Task Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. ;See also * The Game of Chaos
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<math.h> #include<time.h> #define pi M_PI int main(){ time_t t; double side, vertices[3][3],seedX,seedY,windowSide; int i,iter,choice; printf("Enter triangle side length : "); scanf("%lf",&side); printf("Enter number of iterations : "); scanf("%d",&iter); windowSide = 10 + 2*side; initwindow(windowSide,windowSide,"Sierpinski Chaos"); for(i=0;i<3;i++){ vertices[i][0] = windowSide/2 + side*cos(i*2*pi/3); vertices[i][1] = windowSide/2 + side*sin(i*2*pi/3); putpixel(vertices[i][0],vertices[i][1],15); } srand((unsigned)time(&t)); seedX = rand()%(int)(vertices[0][0]/2 + (vertices[1][0] + vertices[2][0])/4); seedY = rand()%(int)(vertices[0][1]/2 + (vertices[1][1] + vertices[2][1])/4); putpixel(seedX,seedY,15); for(i=0;i<iter;i++){ choice = rand()%3; seedX = (seedX + vertices[choice][0])/2; seedY = (seedY + vertices[choice][1])/2; putpixel(seedX,seedY,15); } getch(); closegraph(); return 0; }
Check input device is a terminal
C
Demonstrate how to check whether the input device is a terminal or not. ;Related task: * [[Check output device is a terminal]]
#include <unistd.h> //for isatty() #include <stdio.h> //for fileno() int main(void) { puts(isatty(fileno(stdin)) ? "stdin is tty" : "stdin is not tty"); return 0; }
Check output device is a terminal
C
Demonstrate how to check whether the output device is a terminal or not. ;Related task: * [[Check input device is a terminal]]
#include <unistd.h> // for isatty() #include <stdio.h> // for fileno() int main() { puts(isatty(fileno(stdout)) ? "stdout is tty" : "stdout is not tty"); return 0; }
Chinese remainder theorem
C
Suppose n_1, n_2, \ldots, n_k are positive [[integer]]s that are pairwise co-prime. Then, for any given sequence of integers a_1, a_2, \dots, a_k, there exists an integer x solving the following system of simultaneous congruences: ::: \begin{align} x &\equiv a_1 \pmod{n_1} \\ x &\equiv a_2 \pmod{n_2} \\ &{}\ \ \vdots \\ x &\equiv a_k \pmod{n_k} \end{align} Furthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\ldots n_k. ;Task: Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution s where 0 \leq s \leq n_1n_2\ldots n_k. ''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2]. '''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: ::: x \equiv a_i \pmod{n_i} \quad\mathrm{for}\; i = 1, \ldots, k Again, to begin, the product N = n_1n_2 \ldots n_k is defined. Then a solution x can be found as follows: For each i, the integers n_i and N/n_i are co-prime. Using the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. Then, one solution to the system of simultaneous congruences is: ::: x = \sum_{i=1}^k a_i s_i N/n_i and the minimal solution, ::: x \pmod{N}.
#include <stdio.h> // returns x where (a * x) % b == 1 int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Circles of given radius through two points
C
2 circles with a given radius through 2 points in 2D space. Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. ;Exceptions: # r==0.0 should be treated as never describing circles (except in the case where the points are coincident). # If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. # If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language. # If the points are too far apart then no circles can be drawn. ;Task detail: * Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''. * Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 ;Related task: * [[Total circles area]]. ;See also: * Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
#include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double distance(point p1,point p2) { return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); } void findCircles(point p1,point p2,double radius) { double separation = distance(p1,p2),mirrorDistance; if(separation == 0.0) { radius == 0.0 ? printf("\nNo circles can be drawn through (%.4f,%.4f)",p1.x,p1.y): printf("\nInfinitely many circles can be drawn through (%.4f,%.4f)",p1.x,p1.y); } else if(separation == 2*radius) { printf("\nGiven points are opposite ends of a diameter of the circle with center (%.4f,%.4f) and radius %.4f",(p1.x+p2.x)/2,(p1.y+p2.y)/2,radius); } else if(separation > 2*radius) { printf("\nGiven points are farther away from each other than a diameter of a circle with radius %.4f",radius); } else { mirrorDistance =sqrt(pow(radius,2) - pow(separation/2,2)); printf("\nTwo circles are possible."); printf("\nCircle C1 with center (%.4f,%.4f), radius %.4f and Circle C2 with center (%.4f,%.4f), radius %.4f",(p1.x+p2.x)/2 + mirrorDistance*(p1.y-p2.y)/separation,(p1.y+p2.y)/2 + mirrorDistance*(p2.x-p1.x)/separation,radius,(p1.x+p2.x)/2 - mirrorDistance*(p1.y-p2.y)/separation,(p1.y+p2.y)/2 - mirrorDistance*(p2.x-p1.x)/separation,radius); } } int main() { int i; point cases[] = { {0.1234, 0.9876}, {0.8765, 0.2345}, {0.0000, 2.0000}, {0.0000, 0.0000}, {0.1234, 0.9876}, {0.1234, 0.9876}, {0.1234, 0.9876}, {0.8765, 0.2345}, {0.1234, 0.9876}, {0.1234, 0.9876} }; double radii[] = {2.0,1.0,2.0,0.5,0.0}; for(i=0;i<5;i++) { printf("\nCase %d)",i+1); findCircles(cases[2*i],cases[2*i+1],radii[i]); } return 0; }
Closures/Value capture
C
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. ;Goal: Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: [[Multiple distinct objects]]
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> typedef int (*f_int)(); #define TAG 0xdeadbeef int _tmpl() { volatile int x = TAG; return x * x; } #define PROT (PROT_EXEC | PROT_WRITE) #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) f_int dupf(int v) { size_t len = (void*)dupf - (void*)_tmpl; f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0); char *p; if(ret == MAP_FAILED) { perror("mmap"); exit(-1); } memcpy(ret, _tmpl, len); for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++) if (*(int *)p == TAG) *(int *)p = v; return ret; } int main() { f_int funcs[10]; int i; for (i = 0; i < 10; i++) funcs[i] = dupf(i); for (i = 0; i < 9; i++) printf("func[%d]: %d\n", i, funcs[i]()); return 0; }
Colorful numbers
C
A '''colorful number''' is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique. ;E.G. 24753 is a colorful number. 2, 4, 7, 5, 3, (2x4)8, (4x7)28, (7x5)35, (5x3)15, (2x4x7)56, (4x7x5)140, (7x5x3)105, (2x4x7x5)280, (4x7x5x3)420, (2x4x7x5x3)840 Every product is unique. 2346 is '''not''' a colorful number. 2, 3, 4, '''6''', (2x3)'''6''', (3x4)12, (4x6)24, (2x3x4)48, (3x4x6)72, (2x3x4x6)144 The product '''6''' is repeated. Single digit numbers '''are''' considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits. ;Task * Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not. * Use that routine to find all of the colorful numbers less than 100. * Use that routine to find the largest possible colorful number. ;Stretch * Find and display the count of colorful numbers in each order of magnitude. * Find and show the total count of '''all''' colorful numbers. ''Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.''
#include <locale.h> #include <stdbool.h> #include <stdio.h> #include <time.h> bool colorful(int n) { // A colorful number cannot be greater than 98765432. if (n < 0 || n > 98765432) return false; int digit_count[10] = {}; int digits[8] = {}; int num_digits = 0; for (int m = n; m > 0; m /= 10) { int d = m % 10; if (n > 9 && (d == 0 || d == 1)) return false; if (++digit_count[d] > 1) return false; digits[num_digits++] = d; } // Maximum number of products is (8 x 9) / 2. int products[36] = {}; for (int i = 0, product_count = 0; i < num_digits; ++i) { for (int j = i, p = 1; j < num_digits; ++j) { p *= digits[j]; for (int k = 0; k < product_count; ++k) { if (products[k] == p) return false; } products[product_count++] = p; } } return true; } static int count[8]; static bool used[10]; static int largest = 0; void count_colorful(int taken, int n, int digits) { if (taken == 0) { for (int d = 0; d < 10; ++d) { used[d] = true; count_colorful(d < 2 ? 9 : 1, d, 1); used[d] = false; } } else { if (colorful(n)) { ++count[digits - 1]; if (n > largest) largest = n; } if (taken < 9) { for (int d = 2; d < 10; ++d) { if (!used[d]) { used[d] = true; count_colorful(taken + 1, n * 10 + d, digits + 1); used[d] = false; } } } } } int main() { setlocale(LC_ALL, ""); clock_t start = clock(); printf("Colorful numbers less than 100:\n"); for (int n = 0, count = 0; n < 100; ++n) { if (colorful(n)) printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' '); } count_colorful(0, 0, 0); printf("\n\nLargest colorful number: %'d\n", largest); printf("\nCount of colorful numbers by number of digits:\n"); int total = 0; for (int d = 0; d < 8; ++d) { printf("%d %'d\n", d + 1, count[d]); total += count[d]; } printf("\nTotal: %'d\n", total); clock_t end = clock(); printf("\nElapsed time: %f seconds\n", (end - start + 0.0) / CLOCKS_PER_SEC); return 0; }
Colour bars/Display
C
Display a series of vertical color bars across the width of the display. The color bars should either use: :::* the system palette, or :::* the sequence of colors: ::::::* black ::::::* red ::::::* green ::::::* blue ::::::* magenta ::::::* cyan ::::::* yellow ::::::* white
#include<conio.h> #define COLOURS 8 int main() { int colour=0,i,j,MAXROW,MAXCOL; struct text_info tInfo; gettextinfo(&tInfo); MAXROW = tInfo.screenheight; MAXCOL = tInfo.screenwidth; textbackground(BLACK); //8 colour constants are defined clrscr(); for(colour=0;colour<COLOURS;colour++) { getch(); //waits for a key hit gotoxy(1+colour*MAXCOL/COLOURS,1); textbackground(colour); for(j=0;j<MAXROW;j++){ for(i=0;i<MAXCOL/COLOURS;i++){ cprintf(" "); } gotoxy(1+colour*MAXCOL/COLOURS,1+j); } } getch(); textbackground(BLACK); return 0; }
Comma quibbling
C
Comma quibbling is a task originally set by Eric Lippert in his blog. ;Task: Write a function to generate a string output which is the concatenation of input words from a list/sequence where: # An input of no words produces the output string of just the two brace characters "{}". # An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". # An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". # An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: * [] # (No input words). * ["ABC"] * ["ABC", "DEF"] * ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#include <stdio.h> #include <string.h> #include <stdlib.h> char *quib(const char **strs, size_t size) { size_t len = 3 + ((size > 1) ? (2 * size + 1) : 0); size_t i; for (i = 0; i < size; i++) len += strlen(strs[i]); char *s = malloc(len * sizeof(*s)); if (!s) { perror("Can't allocate memory!\n"); exit(EXIT_FAILURE); } strcpy(s, "{"); switch (size) { case 0: break; case 1: strcat(s, strs[0]); break; default: for (i = 0; i < size - 1; i++) { strcat(s, strs[i]); if (i < size - 2) strcat(s, ", "); else strcat(s, " and "); } strcat(s, strs[i]); break; } strcat(s, "}"); return s; } int main(void) { const char *test[] = {"ABC", "DEF", "G", "H"}; char *s; for (size_t i = 0; i < 5; i++) { s = quib(test, i); printf("%s\n", s); free(s); } return EXIT_SUCCESS; }
Command-line arguments
C
{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]]. See also [[Program name]]. For parsing command line arguments intelligently, see [[Parsing command-line arguments]]. Example command line: myprogram -c "alpha beta" -h "gamma"
#include <stdlib.h> #include <stdio.h> int main(int argc, char* argv[]) { int i; (void) printf("This program is named %s.\n", argv[0]); for (i = 1; i < argc; ++i) (void) printf("the argument #%d is %s\n", i, argv[i]); return EXIT_SUCCESS; }
Compare a list of strings
C
Given a list of arbitrarily many strings, show how to: * test if they are all lexically '''equal''' * test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)'' Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. If the input list has less than two elements, the tests should always return true. There is ''no'' need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible. Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers. If you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature.
#include <stdbool.h> #include <string.h> static bool strings_are_equal(const char **strings, size_t nstrings) { for (size_t i = 1; i < nstrings; i++) if (strcmp(strings[0], strings[i]) != 0) return false; return true; } static bool strings_are_in_ascending_order(const char **strings, size_t nstrings) { for (size_t i = 1; i < nstrings; i++) if (strcmp(strings[i - 1], strings[i]) >= 0) return false; return true; }
Compile-time calculation
C
Some programming languages allow calculation of values at compile time. ;Task: Calculate 10! (ten factorial) at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
#include <stdio.h> #include <order/interpreter.h> #define ORDER_PP_DEF_8fac ORDER_PP_FN( \ 8fn(8X, 8seq_fold(8times, 1, 8seq_iota(1, 8inc(8X)))) ) int main(void) { printf("10! = %d\n", ORDER_PP( 8to_lit( 8fac(10) ) ) ); return 0; }
Compiler/AST interpreter
C
The C and Python versions can be considered reference implementations. ;Related Tasks * Lexical Analyzer task * Syntax Analyzer task * Code Generator task * Virtual Machine Interpreter task __TOC__
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <ctype.h> #define da_dim(name, type) type *name = NULL; \ int _qy_ ## name ## _p = 0; \ int _qy_ ## name ## _max = 0 #define da_rewind(name) _qy_ ## name ## _p = 0 #define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \ name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0) #define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0) #define da_len(name) _qy_ ## name ## _p #define da_add(name) do {da_redim(name); _qy_ ## name ## _p++;} while (0) typedef enum { nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or } NodeType; typedef struct Tree Tree; struct Tree { NodeType node_type; Tree *left; Tree *right; int value; }; // dependency: Ordered by NodeType, must remain in same order as NodeType enum struct { char *enum_text; NodeType node_type; } atr[] = { {"Identifier" , nd_Ident, }, {"String" , nd_String, }, {"Integer" , nd_Integer,}, {"Sequence" , nd_Sequence,}, {"If" , nd_If, }, {"Prtc" , nd_Prtc, }, {"Prts" , nd_Prts, }, {"Prti" , nd_Prti, }, {"While" , nd_While, }, {"Assign" , nd_Assign, }, {"Negate" , nd_Negate, }, {"Not" , nd_Not, }, {"Multiply" , nd_Mul, }, {"Divide" , nd_Div, }, {"Mod" , nd_Mod, }, {"Add" , nd_Add, }, {"Subtract" , nd_Sub, }, {"Less" , nd_Lss, }, {"LessEqual" , nd_Leq, }, {"Greater" , nd_Gtr, }, {"GreaterEqual", nd_Geq, }, {"Equal" , nd_Eql, }, {"NotEqual" , nd_Neq, }, {"And" , nd_And, }, {"Or" , nd_Or, }, }; FILE *source_fp; da_dim(string_pool, const char *); da_dim(global_names, const char *); da_dim(global_values, int); void error(const char *fmt, ... ) { va_list ap; char buf[1000]; va_start(ap, fmt); vsprintf(buf, fmt, ap); printf("error: %s\n", buf); exit(1); } Tree *make_node(NodeType node_type, Tree *left, Tree *right) { Tree *t = calloc(sizeof(Tree), 1); t->node_type = node_type; t->left = left; t->right = right; return t; } Tree *make_leaf(NodeType node_type, int value) { Tree *t = calloc(sizeof(Tree), 1); t->node_type = node_type; t->value = value; return t; } int interp(Tree *x) { /* interpret the parse tree */ if (!x) return 0; switch(x->node_type) { case nd_Integer: return x->value; case nd_Ident: return global_values[x->value]; case nd_String: return x->value; case nd_Assign: return global_values[x->left->value] = interp(x->right); case nd_Add: return interp(x->left) + interp(x->right); case nd_Sub: return interp(x->left) - interp(x->right); case nd_Mul: return interp(x->left) * interp(x->right); case nd_Div: return interp(x->left) / interp(x->right); case nd_Mod: return interp(x->left) % interp(x->right); case nd_Lss: return interp(x->left) < interp(x->right); case nd_Gtr: return interp(x->left) > interp(x->right); case nd_Leq: return interp(x->left) <= interp(x->right); case nd_Eql: return interp(x->left) == interp(x->right); case nd_Neq: return interp(x->left) != interp(x->right); case nd_And: return interp(x->left) && interp(x->right); case nd_Or: return interp(x->left) || interp(x->right); case nd_Negate: return -interp(x->left); case nd_Not: return !interp(x->left); case nd_If: if (interp(x->left)) interp(x->right->left); else interp(x->right->right); return 0; case nd_While: while (interp(x->left)) interp(x->right); return 0; case nd_Prtc: printf("%c", interp(x->left)); return 0; case nd_Prti: printf("%d", interp(x->left)); return 0; case nd_Prts: printf("%s", string_pool[interp(x->left)]); return 0; case nd_Sequence: interp(x->left); interp(x->right); return 0; default: error("interp: unknown tree type %d\n", x->node_type); } return 0; } void init_in(const char fn[]) { if (fn[0] == '\0') source_fp = stdin; else { source_fp = fopen(fn, "r"); if (source_fp == NULL) error("Can't open %s\n", fn); } } NodeType get_enum_value(const char name[]) { for (size_t i = 0; i < sizeof(atr) / sizeof(atr[0]); i++) { if (strcmp(atr[i].enum_text, name) == 0) { return atr[i].node_type; } } error("Unknown token %s\n", name); return -1; } char *read_line(int *len) { static char *text = NULL; static int textmax = 0; for (*len = 0; ; (*len)++) { int ch = fgetc(source_fp); if (ch == EOF || ch == '\n') { if (*len == 0) return NULL; break; } if (*len + 1 >= textmax) { textmax = (textmax == 0 ? 128 : textmax * 2); text = realloc(text, textmax); } text[*len] = ch; } text[*len] = '\0'; return text; } char *rtrim(char *text, int *len) { // remove trailing spaces for (; *len > 0 && isspace(text[*len - 1]); --(*len)) ; text[*len] = '\0'; return text; } int fetch_string_offset(char *st) { int len = strlen(st); st[len - 1] = '\0'; ++st; char *p, *q; p = q = st; while ((*p++ = *q++) != '\0') { if (q[-1] == '\\') { if (q[0] == 'n') { p[-1] = '\n'; ++q; } else if (q[0] == '\\') { ++q; } } } for (int i = 0; i < da_len(string_pool); ++i) { if (strcmp(st, string_pool[i]) == 0) { return i; } } da_add(string_pool); int n = da_len(string_pool) - 1; string_pool[n] = strdup(st); return da_len(string_pool) - 1; } int fetch_var_offset(const char *name) { for (int i = 0; i < da_len(global_names); ++i) { if (strcmp(name, global_names[i]) == 0) return i; } da_add(global_names); int n = da_len(global_names) - 1; global_names[n] = strdup(name); da_append(global_values, 0); return n; } Tree *load_ast() { int len; char *yytext = read_line(&len); yytext = rtrim(yytext, &len); // get first token char *tok = strtok(yytext, " "); if (tok[0] == ';') { return NULL; } NodeType node_type = get_enum_value(tok); // if there is extra data, get it char *p = tok + strlen(tok); if (p != &yytext[len]) { int n; for (++p; isspace(*p); ++p) ; switch (node_type) { case nd_Ident: n = fetch_var_offset(p); break; case nd_Integer: n = strtol(p, NULL, 0); break; case nd_String: n = fetch_string_offset(p); break; default: error("Unknown node type: %s\n", p); } return make_leaf(node_type, n); } Tree *left = load_ast(); Tree *right = load_ast(); return make_node(node_type, left, right); } int main(int argc, char *argv[]) { init_in(argc > 1 ? argv[1] : ""); Tree *x = load_ast(); interp(x); return 0; }
Compiler/code generator
C
The C and Python versions can be considered reference implementations. ;Related Tasks * Lexical Analyzer task * Syntax Analyzer task * Virtual Machine Interpreter task * AST Interpreter task __TOC__
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <stdint.h> #include <ctype.h> typedef unsigned char uchar; typedef enum { nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or } NodeType; typedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT } Code_t; typedef uchar code; typedef struct Tree { NodeType node_type; struct Tree *left; struct Tree *right; char *value; } Tree; #define da_dim(name, type) type *name = NULL; \ int _qy_ ## name ## _p = 0; \ int _qy_ ## name ## _max = 0 #define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \ name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0) #define da_rewind(name) _qy_ ## name ## _p = 0 #define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0) #define da_len(name) _qy_ ## name ## _p #define da_add(name) do {da_redim(name); _qy_ ## name ## _p++;} while (0) FILE *source_fp, *dest_fp; static int here; da_dim(object, code); da_dim(globals, const char *); da_dim(string_pool, const char *); // dependency: Ordered by NodeType, must remain in same order as NodeType enum struct { char *enum_text; NodeType node_type; Code_t opcode; } atr[] = { {"Identifier" , nd_Ident, -1 }, {"String" , nd_String, -1 }, {"Integer" , nd_Integer, -1 }, {"Sequence" , nd_Sequence, -1 }, {"If" , nd_If, -1 }, {"Prtc" , nd_Prtc, -1 }, {"Prts" , nd_Prts, -1 }, {"Prti" , nd_Prti, -1 }, {"While" , nd_While, -1 }, {"Assign" , nd_Assign, -1 }, {"Negate" , nd_Negate, NEG}, {"Not" , nd_Not, NOT}, {"Multiply" , nd_Mul, MUL}, {"Divide" , nd_Div, DIV}, {"Mod" , nd_Mod, MOD}, {"Add" , nd_Add, ADD}, {"Subtract" , nd_Sub, SUB}, {"Less" , nd_Lss, LT }, {"LessEqual" , nd_Leq, LE }, {"Greater" , nd_Gtr, GT }, {"GreaterEqual", nd_Geq, GE }, {"Equal" , nd_Eql, EQ }, {"NotEqual" , nd_Neq, NE }, {"And" , nd_And, AND}, {"Or" , nd_Or, OR }, }; void error(const char *fmt, ... ) { va_list ap; char buf[1000]; va_start(ap, fmt); vsprintf(buf, fmt, ap); va_end(ap); printf("error: %s\n", buf); exit(1); } Code_t type_to_op(NodeType type) { return atr[type].opcode; } Tree *make_node(NodeType node_type, Tree *left, Tree *right) { Tree *t = calloc(sizeof(Tree), 1); t->node_type = node_type; t->left = left; t->right = right; return t; } Tree *make_leaf(NodeType node_type, char *value) { Tree *t = calloc(sizeof(Tree), 1); t->node_type = node_type; t->value = strdup(value); return t; } /*** Code generator ***/ void emit_byte(int c) { da_append(object, (uchar)c); ++here; } void emit_int(int32_t n) { union { int32_t n; unsigned char c[sizeof(int32_t)]; } x; x.n = n; for (size_t i = 0; i < sizeof(x.n); ++i) { emit_byte(x.c[i]); } } int hole() { int t = here; emit_int(0); return t; } void fix(int src, int dst) { *(int32_t *)(object + src) = dst-src; } int fetch_var_offset(const char *id) { for (int i = 0; i < da_len(globals); ++i) { if (strcmp(id, globals[i]) == 0) return i; } da_add(globals); int n = da_len(globals) - 1; globals[n] = strdup(id); return n; } int fetch_string_offset(const char *st) { for (int i = 0; i < da_len(string_pool); ++i) { if (strcmp(st, string_pool[i]) == 0) return i; } da_add(string_pool); int n = da_len(string_pool) - 1; string_pool[n] = strdup(st); return n; } void code_gen(Tree *x) { int p1, p2, n; if (x == NULL) return; switch (x->node_type) { case nd_Ident: emit_byte(FETCH); n = fetch_var_offset(x->value); emit_int(n); break; case nd_Integer: emit_byte(PUSH); emit_int(atoi(x->value)); break; case nd_String: emit_byte(PUSH); n = fetch_string_offset(x->value); emit_int(n); break; case nd_Assign: n = fetch_var_offset(x->left->value); code_gen(x->right); emit_byte(STORE); emit_int(n); break; case nd_If: code_gen(x->left); // if expr emit_byte(JZ); // if false, jump p1 = hole(); // make room for jump dest code_gen(x->right->left); // if true statements if (x->right->right != NULL) { emit_byte(JMP); p2 = hole(); } fix(p1, here); if (x->right->right != NULL) { code_gen(x->right->right); fix(p2, here); } break; case nd_While: p1 = here; code_gen(x->left); // while expr emit_byte(JZ); // if false, jump p2 = hole(); // make room for jump dest code_gen(x->right); // statements emit_byte(JMP); // back to the top fix(hole(), p1); // plug the top fix(p2, here); // plug the 'if false, jump' break; case nd_Sequence: code_gen(x->left); code_gen(x->right); break; case nd_Prtc: code_gen(x->left); emit_byte(PRTC); break; case nd_Prti: code_gen(x->left); emit_byte(PRTI); break; case nd_Prts: code_gen(x->left); emit_byte(PRTS); break; case nd_Lss: case nd_Gtr: case nd_Leq: case nd_Geq: case nd_Eql: case nd_Neq: case nd_And: case nd_Or: case nd_Sub: case nd_Add: case nd_Div: case nd_Mul: case nd_Mod: code_gen(x->left); code_gen(x->right); emit_byte(type_to_op(x->node_type)); break; case nd_Negate: case nd_Not: code_gen(x->left); emit_byte(type_to_op(x->node_type)); break; default: error("error in code generator - found %d, expecting operator\n", x->node_type); } } void code_finish() { emit_byte(HALT); } void list_code() { fprintf(dest_fp, "Datasize: %d Strings: %d\n", da_len(globals), da_len(string_pool)); for (int i = 0; i < da_len(string_pool); ++i) fprintf(dest_fp, "%s\n", string_pool[i]); code *pc = object; again: fprintf(dest_fp, "%5d ", (int)(pc - object)); switch (*pc++) { case FETCH: fprintf(dest_fp, "fetch [%d]\n", *(int32_t *)pc); pc += sizeof(int32_t); goto again; case STORE: fprintf(dest_fp, "store [%d]\n", *(int32_t *)pc); pc += sizeof(int32_t); goto again; case PUSH : fprintf(dest_fp, "push %d\n", *(int32_t *)pc); pc += sizeof(int32_t); goto again; case ADD : fprintf(dest_fp, "add\n"); goto again; case SUB : fprintf(dest_fp, "sub\n"); goto again; case MUL : fprintf(dest_fp, "mul\n"); goto again; case DIV : fprintf(dest_fp, "div\n"); goto again; case MOD : fprintf(dest_fp, "mod\n"); goto again; case LT : fprintf(dest_fp, "lt\n"); goto again; case GT : fprintf(dest_fp, "gt\n"); goto again; case LE : fprintf(dest_fp, "le\n"); goto again; case GE : fprintf(dest_fp, "ge\n"); goto again; case EQ : fprintf(dest_fp, "eq\n"); goto again; case NE : fprintf(dest_fp, "ne\n"); goto again; case AND : fprintf(dest_fp, "and\n"); goto again; case OR : fprintf(dest_fp, "or\n"); goto again; case NOT : fprintf(dest_fp, "not\n"); goto again; case NEG : fprintf(dest_fp, "neg\n"); goto again; case JMP : fprintf(dest_fp, "jmp (%d) %d\n", *(int32_t *)pc, (int32_t)(pc + *(int32_t *)pc - object)); pc += sizeof(int32_t); goto again; case JZ : fprintf(dest_fp, "jz (%d) %d\n", *(int32_t *)pc, (int32_t)(pc + *(int32_t *)pc - object)); pc += sizeof(int32_t); goto again; case PRTC : fprintf(dest_fp, "prtc\n"); goto again; case PRTI : fprintf(dest_fp, "prti\n"); goto again; case PRTS : fprintf(dest_fp, "prts\n"); goto again; case HALT : fprintf(dest_fp, "halt\n"); break; default:error("listcode:Unknown opcode %d\n", *(pc - 1)); } } void init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) { if (fn[0] == '\0') *fp = std; else if ((*fp = fopen(fn, mode)) == NULL) error(0, 0, "Can't open %s\n", fn); } NodeType get_enum_value(const char name[]) { for (size_t i = 0; i < sizeof(atr) / sizeof(atr[0]); i++) { if (strcmp(atr[i].enum_text, name) == 0) { return atr[i].node_type; } } error("Unknown token %s\n", name); return -1; } char *read_line(int *len) { static char *text = NULL; static int textmax = 0; for (*len = 0; ; (*len)++) { int ch = fgetc(source_fp); if (ch == EOF || ch == '\n') { if (*len == 0) return NULL; break; } if (*len + 1 >= textmax) { textmax = (textmax == 0 ? 128 : textmax * 2); text = realloc(text, textmax); } text[*len] = ch; } text[*len] = '\0'; return text; } char *rtrim(char *text, int *len) { // remove trailing spaces for (; *len > 0 && isspace(text[*len - 1]); --(*len)) ; text[*len] = '\0'; return text; } Tree *load_ast() { int len; char *yytext = read_line(&len); yytext = rtrim(yytext, &len); // get first token char *tok = strtok(yytext, " "); if (tok[0] == ';') { return NULL; } NodeType node_type = get_enum_value(tok); // if there is extra data, get it char *p = tok + strlen(tok); if (p != &yytext[len]) { for (++p; isspace(*p); ++p) ; return make_leaf(node_type, p); } Tree *left = load_ast(); Tree *right = load_ast(); return make_node(node_type, left, right); } int main(int argc, char *argv[]) { init_io(&source_fp, stdin, "r", argc > 1 ? argv[1] : ""); init_io(&dest_fp, stdout, "wb", argc > 2 ? argv[2] : ""); code_gen(load_ast()); code_finish(); list_code(); return 0; }
Compiler/lexical analyzer
C
The C and Python versions can be considered reference implementations. ;Related Tasks * Syntax Analyzer task * Code Generator task * Virtual Machine Interpreter task * AST Interpreter task
#include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <ctype.h> #include <string.h> #include <errno.h> #include <stdbool.h> #include <limits.h> #define NELEMS(arr) (sizeof(arr) / sizeof(arr[0])) #define da_dim(name, type) type *name = NULL; \ int _qy_ ## name ## _p = 0; \ int _qy_ ## name ## _max = 0 #define da_rewind(name) _qy_ ## name ## _p = 0 #define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \ name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0) #define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0) #define da_len(name) _qy_ ## name ## _p typedef enum { tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, tk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print, tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident, tk_Integer, tk_String } TokenType; typedef struct { TokenType tok; int err_ln, err_col; union { int n; /* value for constants */ char *text; /* text for idents */ }; } tok_s; static FILE *source_fp, *dest_fp; static int line = 1, col = 0, the_ch = ' '; da_dim(text, char); tok_s gettok(void); static void error(int err_line, int err_col, const char *fmt, ... ) { char buf[1000]; va_list ap; va_start(ap, fmt); vsprintf(buf, fmt, ap); va_end(ap); printf("(%d,%d) error: %s\n", err_line, err_col, buf); exit(1); } static int next_ch(void) { /* get next char from input */ the_ch = getc(source_fp); ++col; if (the_ch == '\n') { ++line; col = 0; } return the_ch; } static tok_s char_lit(int n, int err_line, int err_col) { /* 'x' */ if (the_ch == '\'') error(err_line, err_col, "gettok: empty character constant"); if (the_ch == '\\') { next_ch(); if (the_ch == 'n') n = 10; else if (the_ch == '\\') n = '\\'; else error(err_line, err_col, "gettok: unknown escape sequence \\%c", the_ch); } if (next_ch() != '\'') error(err_line, err_col, "multi-character constant"); next_ch(); return (tok_s){tk_Integer, err_line, err_col, {n}}; } static tok_s div_or_cmt(int err_line, int err_col) { /* process divide or comments */ if (the_ch != '*') return (tok_s){tk_Div, err_line, err_col, {0}}; /* comment found */ next_ch(); for (;;) { if (the_ch == '*') { if (next_ch() == '/') { next_ch(); return gettok(); } } else if (the_ch == EOF) error(err_line, err_col, "EOF in comment"); else next_ch(); } } static tok_s string_lit(int start, int err_line, int err_col) { /* "st" */ da_rewind(text); while (next_ch() != start) { if (the_ch == '\n') error(err_line, err_col, "EOL in string"); if (the_ch == EOF) error(err_line, err_col, "EOF in string"); da_append(text, (char)the_ch); } da_append(text, '\0'); next_ch(); return (tok_s){tk_String, err_line, err_col, {.text=text}}; } static int kwd_cmp(const void *p1, const void *p2) { return strcmp(*(char **)p1, *(char **)p2); } static TokenType get_ident_type(const char *ident) { static struct { const char *s; TokenType sym; } kwds[] = { {"else", tk_Else}, {"if", tk_If}, {"print", tk_Print}, {"putc", tk_Putc}, {"while", tk_While}, }, *kwp; return (kwp = bsearch(&ident, kwds, NELEMS(kwds), sizeof(kwds[0]), kwd_cmp)) == NULL ? tk_Ident : kwp->sym; } static tok_s ident_or_int(int err_line, int err_col) { int n, is_number = true; da_rewind(text); while (isalnum(the_ch) || the_ch == '_') { da_append(text, (char)the_ch); if (!isdigit(the_ch)) is_number = false; next_ch(); } if (da_len(text) == 0) error(err_line, err_col, "gettok: unrecognized character (%d) '%c'\n", the_ch, the_ch); da_append(text, '\0'); if (isdigit(text[0])) { if (!is_number) error(err_line, err_col, "invalid number: %s\n", text); n = strtol(text, NULL, 0); if (n == LONG_MAX && errno == ERANGE) error(err_line, err_col, "Number exceeds maximum value"); return (tok_s){tk_Integer, err_line, err_col, {n}}; } return (tok_s){get_ident_type(text), err_line, err_col, {.text=text}}; } static tok_s follow(int expect, TokenType ifyes, TokenType ifno, int err_line, int err_col) { /* look ahead for '>=', etc. */ if (the_ch == expect) { next_ch(); return (tok_s){ifyes, err_line, err_col, {0}}; } if (ifno == tk_EOI) error(err_line, err_col, "follow: unrecognized character '%c' (%d)\n", the_ch, the_ch); return (tok_s){ifno, err_line, err_col, {0}}; } tok_s gettok(void) { /* return the token type */ /* skip white space */ while (isspace(the_ch)) next_ch(); int err_line = line; int err_col = col; switch (the_ch) { case '{': next_ch(); return (tok_s){tk_Lbrace, err_line, err_col, {0}}; case '}': next_ch(); return (tok_s){tk_Rbrace, err_line, err_col, {0}}; case '(': next_ch(); return (tok_s){tk_Lparen, err_line, err_col, {0}}; case ')': next_ch(); return (tok_s){tk_Rparen, err_line, err_col, {0}}; case '+': next_ch(); return (tok_s){tk_Add, err_line, err_col, {0}}; case '-': next_ch(); return (tok_s){tk_Sub, err_line, err_col, {0}}; case '*': next_ch(); return (tok_s){tk_Mul, err_line, err_col, {0}}; case '%': next_ch(); return (tok_s){tk_Mod, err_line, err_col, {0}}; case ';': next_ch(); return (tok_s){tk_Semi, err_line, err_col, {0}}; case ',': next_ch(); return (tok_s){tk_Comma,err_line, err_col, {0}}; case '/': next_ch(); return div_or_cmt(err_line, err_col); case '\'': next_ch(); return char_lit(the_ch, err_line, err_col); case '<': next_ch(); return follow('=', tk_Leq, tk_Lss, err_line, err_col); case '>': next_ch(); return follow('=', tk_Geq, tk_Gtr, err_line, err_col); case '=': next_ch(); return follow('=', tk_Eq, tk_Assign, err_line, err_col); case '!': next_ch(); return follow('=', tk_Neq, tk_Not, err_line, err_col); case '&': next_ch(); return follow('&', tk_And, tk_EOI, err_line, err_col); case '|': next_ch(); return follow('|', tk_Or, tk_EOI, err_line, err_col); case '"' : return string_lit(the_ch, err_line, err_col); default: return ident_or_int(err_line, err_col); case EOF: return (tok_s){tk_EOI, err_line, err_col, {0}}; } } void run(void) { /* tokenize the given input */ tok_s tok; do { tok = gettok(); fprintf(dest_fp, "%5d %5d %.15s", tok.err_ln, tok.err_col, &"End_of_input Op_multiply Op_divide Op_mod Op_add " "Op_subtract Op_negate Op_not Op_less Op_lessequal " "Op_greater Op_greaterequal Op_equal Op_notequal Op_assign " "Op_and Op_or Keyword_if Keyword_else Keyword_while " "Keyword_print Keyword_putc LeftParen RightParen LeftBrace " "RightBrace Semicolon Comma Identifier Integer " "String " [tok.tok * 16]); if (tok.tok == tk_Integer) fprintf(dest_fp, " %4d", tok.n); else if (tok.tok == tk_Ident) fprintf(dest_fp, " %s", tok.text); else if (tok.tok == tk_String) fprintf(dest_fp, " \"%s\"", tok.text); fprintf(dest_fp, "\n"); } while (tok.tok != tk_EOI); if (dest_fp != stdout) fclose(dest_fp); } void init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) { if (fn[0] == '\0') *fp = std; else if ((*fp = fopen(fn, mode)) == NULL) error(0, 0, "Can't open %s\n", fn); } int main(int argc, char *argv[]) { init_io(&source_fp, stdin, "r", argc > 1 ? argv[1] : ""); init_io(&dest_fp, stdout, "wb", argc > 2 ? argv[2] : ""); run(); return 0; }
Compiler/syntax analyzer
C
The C and Python versions can be considered reference implementations. ;Related Tasks * Lexical Analyzer task * Code Generator task * Virtual Machine Interpreter task * AST Interpreter task __TOC__
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <stdbool.h> #include <ctype.h> #define NELEMS(arr) (sizeof(arr) / sizeof(arr[0])) typedef enum { tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, tk_Geq, tk_Eql, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print, tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident, tk_Integer, tk_String } TokenType; typedef enum { nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or } NodeType; typedef struct { TokenType tok; int err_ln; int err_col; char *text; /* ident or string literal or integer value */ } tok_s; typedef struct Tree { NodeType node_type; struct Tree *left; struct Tree *right; char *value; } Tree; // dependency: Ordered by tok, must remain in same order as TokenType enum struct { char *text, *enum_text; TokenType tok; bool right_associative, is_binary, is_unary; int precedence; NodeType node_type; } atr[] = { {"EOI", "End_of_input" , tk_EOI, false, false, false, -1, -1 }, {"*", "Op_multiply" , tk_Mul, false, true, false, 13, nd_Mul }, {"/", "Op_divide" , tk_Div, false, true, false, 13, nd_Div }, {"%", "Op_mod" , tk_Mod, false, true, false, 13, nd_Mod }, {"+", "Op_add" , tk_Add, false, true, false, 12, nd_Add }, {"-", "Op_subtract" , tk_Sub, false, true, false, 12, nd_Sub }, {"-", "Op_negate" , tk_Negate, false, false, true, 14, nd_Negate }, {"!", "Op_not" , tk_Not, false, false, true, 14, nd_Not }, {"<", "Op_less" , tk_Lss, false, true, false, 10, nd_Lss }, {"<=", "Op_lessequal" , tk_Leq, false, true, false, 10, nd_Leq }, {">", "Op_greater" , tk_Gtr, false, true, false, 10, nd_Gtr }, {">=", "Op_greaterequal", tk_Geq, false, true, false, 10, nd_Geq }, {"==", "Op_equal" , tk_Eql, false, true, false, 9, nd_Eql }, {"!=", "Op_notequal" , tk_Neq, false, true, false, 9, nd_Neq }, {"=", "Op_assign" , tk_Assign, false, false, false, -1, nd_Assign }, {"&&", "Op_and" , tk_And, false, true, false, 5, nd_And }, {"||", "Op_or" , tk_Or, false, true, false, 4, nd_Or }, {"if", "Keyword_if" , tk_If, false, false, false, -1, nd_If }, {"else", "Keyword_else" , tk_Else, false, false, false, -1, -1 }, {"while", "Keyword_while" , tk_While, false, false, false, -1, nd_While }, {"print", "Keyword_print" , tk_Print, false, false, false, -1, -1 }, {"putc", "Keyword_putc" , tk_Putc, false, false, false, -1, -1 }, {"(", "LeftParen" , tk_Lparen, false, false, false, -1, -1 }, {")", "RightParen" , tk_Rparen, false, false, false, -1, -1 }, {"{", "LeftBrace" , tk_Lbrace, false, false, false, -1, -1 }, {"}", "RightBrace" , tk_Rbrace, false, false, false, -1, -1 }, {";", "Semicolon" , tk_Semi, false, false, false, -1, -1 }, {",", "Comma" , tk_Comma, false, false, false, -1, -1 }, {"Ident", "Identifier" , tk_Ident, false, false, false, -1, nd_Ident }, {"Integer literal", "Integer" , tk_Integer, false, false, false, -1, nd_Integer}, {"String literal", "String" , tk_String, false, false, false, -1, nd_String }, }; char *Display_nodes[] = {"Identifier", "String", "Integer", "Sequence", "If", "Prtc", "Prts", "Prti", "While", "Assign", "Negate", "Not", "Multiply", "Divide", "Mod", "Add", "Subtract", "Less", "LessEqual", "Greater", "GreaterEqual", "Equal", "NotEqual", "And", "Or"}; static tok_s tok; static FILE *source_fp, *dest_fp; Tree *paren_expr(); void error(int err_line, int err_col, const char *fmt, ... ) { va_list ap; char buf[1000]; va_start(ap, fmt); vsprintf(buf, fmt, ap); va_end(ap); printf("(%d, %d) error: %s\n", err_line, err_col, buf); exit(1); } char *read_line(int *len) { static char *text = NULL; static int textmax = 0; for (*len = 0; ; (*len)++) { int ch = fgetc(source_fp); if (ch == EOF || ch == '\n') { if (*len == 0) return NULL; break; } if (*len + 1 >= textmax) { textmax = (textmax == 0 ? 128 : textmax * 2); text = realloc(text, textmax); } text[*len] = ch; } text[*len] = '\0'; return text; } char *rtrim(char *text, int *len) { // remove trailing spaces for (; *len > 0 && isspace(text[*len - 1]); --(*len)) ; text[*len] = '\0'; return text; } TokenType get_enum(const char *name) { // return internal version of name for (size_t i = 0; i < NELEMS(atr); i++) { if (strcmp(atr[i].enum_text, name) == 0) return atr[i].tok; } error(0, 0, "Unknown token %s\n", name); return 0; } tok_s gettok() { int len; tok_s tok; char *yytext = read_line(&len); yytext = rtrim(yytext, &len); // [ ]*{lineno}[ ]+{colno}[ ]+token[ ]+optional // get line and column tok.err_ln = atoi(strtok(yytext, " ")); tok.err_col = atoi(strtok(NULL, " ")); // get the token name char *name = strtok(NULL, " "); tok.tok = get_enum(name); // if there is extra data, get it char *p = name + strlen(name); if (p != &yytext[len]) { for (++p; isspace(*p); ++p) ; tok.text = strdup(p); } return tok; } Tree *make_node(NodeType node_type, Tree *left, Tree *right) { Tree *t = calloc(sizeof(Tree), 1); t->node_type = node_type; t->left = left; t->right = right; return t; } Tree *make_leaf(NodeType node_type, char *value) { Tree *t = calloc(sizeof(Tree), 1); t->node_type = node_type; t->value = strdup(value); return t; } void expect(const char msg[], TokenType s) { if (tok.tok == s) { tok = gettok(); return; } error(tok.err_ln, tok.err_col, "%s: Expecting '%s', found '%s'\n", msg, atr[s].text, atr[tok.tok].text); } Tree *expr(int p) { Tree *x = NULL, *node; TokenType op; switch (tok.tok) { case tk_Lparen: x = paren_expr(); break; case tk_Sub: case tk_Add: op = tok.tok; tok = gettok(); node = expr(atr[tk_Negate].precedence); x = (op == tk_Sub) ? make_node(nd_Negate, node, NULL) : node; break; case tk_Not: tok = gettok(); x = make_node(nd_Not, expr(atr[tk_Not].precedence), NULL); break; case tk_Ident: x = make_leaf(nd_Ident, tok.text); tok = gettok(); break; case tk_Integer: x = make_leaf(nd_Integer, tok.text); tok = gettok(); break; default: error(tok.err_ln, tok.err_col, "Expecting a primary, found: %s\n", atr[tok.tok].text); } while (atr[tok.tok].is_binary && atr[tok.tok].precedence >= p) { TokenType op = tok.tok; tok = gettok(); int q = atr[op].precedence; if (!atr[op].right_associative) q++; node = expr(q); x = make_node(atr[op].node_type, x, node); } return x; } Tree *paren_expr() { expect("paren_expr", tk_Lparen); Tree *t = expr(0); expect("paren_expr", tk_Rparen); return t; } Tree *stmt() { Tree *t = NULL, *v, *e, *s, *s2; switch (tok.tok) { case tk_If: tok = gettok(); e = paren_expr(); s = stmt(); s2 = NULL; if (tok.tok == tk_Else) { tok = gettok(); s2 = stmt(); } t = make_node(nd_If, e, make_node(nd_If, s, s2)); break; case tk_Putc: tok = gettok(); e = paren_expr(); t = make_node(nd_Prtc, e, NULL); expect("Putc", tk_Semi); break; case tk_Print: /* print '(' expr {',' expr} ')' */ tok = gettok(); for (expect("Print", tk_Lparen); ; expect("Print", tk_Comma)) { if (tok.tok == tk_String) { e = make_node(nd_Prts, make_leaf(nd_String, tok.text), NULL); tok = gettok(); } else e = make_node(nd_Prti, expr(0), NULL); t = make_node(nd_Sequence, t, e); if (tok.tok != tk_Comma) break; } expect("Print", tk_Rparen); expect("Print", tk_Semi); break; case tk_Semi: tok = gettok(); break; case tk_Ident: v = make_leaf(nd_Ident, tok.text); tok = gettok(); expect("assign", tk_Assign); e = expr(0); t = make_node(nd_Assign, v, e); expect("assign", tk_Semi); break; case tk_While: tok = gettok(); e = paren_expr(); s = stmt(); t = make_node(nd_While, e, s); break; case tk_Lbrace: /* {stmt} */ for (expect("Lbrace", tk_Lbrace); tok.tok != tk_Rbrace && tok.tok != tk_EOI;) t = make_node(nd_Sequence, t, stmt()); expect("Lbrace", tk_Rbrace); break; case tk_EOI: break; default: error(tok.err_ln, tok.err_col, "expecting start of statement, found '%s'\n", atr[tok.tok].text); } return t; } Tree *parse() { Tree *t = NULL; tok = gettok(); do { t = make_node(nd_Sequence, t, stmt()); } while (t != NULL && tok.tok != tk_EOI); return t; } void prt_ast(Tree *t) { if (t == NULL) printf(";\n"); else { printf("%-14s ", Display_nodes[t->node_type]); if (t->node_type == nd_Ident || t->node_type == nd_Integer || t->node_type == nd_String) { printf("%s\n", t->value); } else { printf("\n"); prt_ast(t->left); prt_ast(t->right); } } } void init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) { if (fn[0] == '\0') *fp = std; else if ((*fp = fopen(fn, mode)) == NULL) error(0, 0, "Can't open %s\n", fn); } int main(int argc, char *argv[]) { init_io(&source_fp, stdin, "r", argc > 1 ? argv[1] : ""); init_io(&dest_fp, stdout, "wb", argc > 2 ? argv[2] : ""); prt_ast(parse()); }
Compiler/virtual machine interpreter
C
The C and Python versions can be considered reference implementations. ;Related Tasks * Lexical Analyzer task * Syntax Analyzer task * Code Generator task * AST Interpreter task __TOC__
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <stdint.h> #include <ctype.h> #define NELEMS(arr) (sizeof(arr) / sizeof(arr[0])) #define da_dim(name, type) type *name = NULL; \ int _qy_ ## name ## _p = 0; \ int _qy_ ## name ## _max = 0 #define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \ name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0) #define da_rewind(name) _qy_ ## name ## _p = 0 #define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0) typedef unsigned char uchar; typedef uchar code; typedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT } Code_t; typedef struct Code_map { char *text; Code_t op; } Code_map; Code_map code_map[] = { {"fetch", FETCH}, {"store", STORE}, {"push", PUSH }, {"add", ADD }, {"sub", SUB }, {"mul", MUL }, {"div", DIV }, {"mod", MOD }, {"lt", LT }, {"gt", GT }, {"le", LE }, {"ge", GE }, {"eq", EQ }, {"ne", NE }, {"and", AND }, {"or", OR }, {"neg", NEG }, {"not", NOT }, {"jmp", JMP }, {"jz", JZ }, {"prtc", PRTC }, {"prts", PRTS }, {"prti", PRTI }, {"halt", HALT }, }; FILE *source_fp; da_dim(object, code); void error(const char *fmt, ... ) { va_list ap; char buf[1000]; va_start(ap, fmt); vsprintf(buf, fmt, ap); va_end(ap); printf("error: %s\n", buf); exit(1); } /*** Virtual Machine interpreter ***/ void run_vm(const code obj[], int32_t data[], int g_size, char **string_pool) { int32_t *sp = &data[g_size + 1]; const code *pc = obj; again: switch (*pc++) { case FETCH: *sp++ = data[*(int32_t *)pc]; pc += sizeof(int32_t); goto again; case STORE: data[*(int32_t *)pc] = *--sp; pc += sizeof(int32_t); goto again; case PUSH: *sp++ = *(int32_t *)pc; pc += sizeof(int32_t); goto again; case ADD: sp[-2] += sp[-1]; --sp; goto again; case SUB: sp[-2] -= sp[-1]; --sp; goto again; case MUL: sp[-2] *= sp[-1]; --sp; goto again; case DIV: sp[-2] /= sp[-1]; --sp; goto again; case MOD: sp[-2] %= sp[-1]; --sp; goto again; case LT: sp[-2] = sp[-2] < sp[-1]; --sp; goto again; case GT: sp[-2] = sp[-2] > sp[-1]; --sp; goto again; case LE: sp[-2] = sp[-2] <= sp[-1]; --sp; goto again; case GE: sp[-2] = sp[-2] >= sp[-1]; --sp; goto again; case EQ: sp[-2] = sp[-2] == sp[-1]; --sp; goto again; case NE: sp[-2] = sp[-2] != sp[-1]; --sp; goto again; case AND: sp[-2] = sp[-2] && sp[-1]; --sp; goto again; case OR: sp[-2] = sp[-2] || sp[-1]; --sp; goto again; case NEG: sp[-1] = -sp[-1]; goto again; case NOT: sp[-1] = !sp[-1]; goto again; case JMP: pc += *(int32_t *)pc; goto again; case JZ: pc += (*--sp == 0) ? *(int32_t *)pc : (int32_t)sizeof(int32_t); goto again; case PRTC: printf("%c", sp[-1]); --sp; goto again; case PRTS: printf("%s", string_pool[sp[-1]]); --sp; goto again; case PRTI: printf("%d", sp[-1]); --sp; goto again; case HALT: break; default: error("Unknown opcode %d\n", *(pc - 1)); } } char *read_line(int *len) { static char *text = NULL; static int textmax = 0; for (*len = 0; ; (*len)++) { int ch = fgetc(source_fp); if (ch == EOF || ch == '\n') { if (*len == 0) return NULL; break; } if (*len + 1 >= textmax) { textmax = (textmax == 0 ? 128 : textmax * 2); text = realloc(text, textmax); } text[*len] = ch; } text[*len] = '\0'; return text; } char *rtrim(char *text, int *len) { // remove trailing spaces for (; *len > 0 && isspace(text[*len - 1]); --(*len)) ; text[*len] = '\0'; return text; } char *translate(char *st) { char *p, *q; if (st[0] == '"') // skip leading " if there ++st; p = q = st; while ((*p++ = *q++) != '\0') { if (q[-1] == '\\') { if (q[0] == 'n') { p[-1] = '\n'; ++q; } else if (q[0] == '\\') { ++q; } } if (q[0] == '"' && q[1] == '\0') // skip trialing " if there ++q; } return st; } /* convert an opcode string into its byte value */ int findit(const char text[], int offset) { for (size_t i = 0; i < sizeof(code_map) / sizeof(code_map[0]); i++) { if (strcmp(code_map[i].text, text) == 0) return code_map[i].op; } error("Unknown instruction %s at %d\n", text, offset); return -1; } void emit_byte(int c) { da_append(object, (uchar)c); } void emit_int(int32_t n) { union { int32_t n; unsigned char c[sizeof(int32_t)]; } x; x.n = n; for (size_t i = 0; i < sizeof(x.n); ++i) { emit_byte(x.c[i]); } } /* Datasize: 5 Strings: 3 " is prime\n" "Total primes found: " "\n" 154 jmp (-73) 82 164 jz (32) 197 175 push 0 159 fetch [4] 149 store [3] */ /* Load code into global array object, return the string pool and data size */ char **load_code(int *ds) { int line_len, n_strings; char **string_pool; char *text = read_line(&line_len); text = rtrim(text, &line_len); strtok(text, " "); // skip "Datasize:" *ds = atoi(strtok(NULL, " ")); // get actual data_size strtok(NULL, " "); // skip "Strings:" n_strings = atoi(strtok(NULL, " ")); // get number of strings string_pool = malloc(n_strings * sizeof(char *)); for (int i = 0; i < n_strings; ++i) { text = read_line(&line_len); text = rtrim(text, &line_len); text = translate(text); string_pool[i] = strdup(text); } for (;;) { int len; text = read_line(&line_len); if (text == NULL) break; text = rtrim(text, &line_len); int offset = atoi(strtok(text, " ")); // get the offset char *instr = strtok(NULL, " "); // get the instruction int opcode = findit(instr, offset); emit_byte(opcode); char *operand = strtok(NULL, " "); switch (opcode) { case JMP: case JZ: operand++; // skip the '(' len = strlen(operand); operand[len - 1] = '\0'; // remove the ')' emit_int(atoi(operand)); break; case PUSH: emit_int(atoi(operand)); break; case FETCH: case STORE: operand++; // skip the '[' len = strlen(operand); operand[len - 1] = '\0'; // remove the ']' emit_int(atoi(operand)); break; } } return string_pool; } void init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) { if (fn[0] == '\0') *fp = std; else if ((*fp = fopen(fn, mode)) == NULL) error(0, 0, "Can't open %s\n", fn); } int main(int argc, char *argv[]) { init_io(&source_fp, stdin, "r", argc > 1 ? argv[1] : ""); int data_size; char **string_pool = load_code(&data_size); int data[1000 + data_size]; run_vm(object, data, data_size, string_pool); }
Conjugate transpose
C
Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M. ::: (M^H)_{ji} = \overline{M_{ij}} This means that row j, column i of the conjugate transpose equals the complex conjugate of row i, column j of the original matrix. In the next list, M must also be a square matrix. * A Hermitian matrix equals its own conjugate transpose: M^H = M. * A multiplication with its conjugate transpose: M^HM = MM^H. * A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix. ;Task: Given some matrix of complex numbers, find its conjugate transpose. Also determine if the matrix is a: ::* Hermitian matrix, ::* normal matrix, or ::* unitary matrix. ;See also: * MathWorld entry: conjugate transpose * MathWorld entry: Hermitian matrix * MathWorld entry: normal matrix * MathWorld entry: unitary matrix
/* Uses C99 specified complex.h, complex datatype has to be defined and operation provided if used on non-C99 compilers */ #include<stdlib.h> #include<stdio.h> #include<complex.h> typedef struct { int rows, cols; complex **z; } matrix; matrix transpose (matrix a) { int i, j; matrix b; b.rows = a.cols; b.cols = a.rows; b.z = malloc (b.rows * sizeof (complex *)); for (i = 0; i < b.rows; i++) { b.z[i] = malloc (b.cols * sizeof (complex)); for (j = 0; j < b.cols; j++) { b.z[i][j] = conj (a.z[j][i]); } } return b; } int isHermitian (matrix a) { int i, j; matrix b = transpose (a); if (b.rows == a.rows && b.cols == a.cols) { for (i = 0; i < b.rows; i++) { for (j = 0; j < b.cols; j++) { if (b.z[i][j] != a.z[i][j]) return 0; } } } else return 0; return 1; } matrix multiply (matrix a, matrix b) { matrix c; int i, j; if (a.cols == b.rows) { c.rows = a.rows; c.cols = b.cols; c.z = malloc (c.rows * (sizeof (complex *))); for (i = 0; i < c.rows; i++) { c.z[i] = malloc (c.cols * sizeof (complex)); c.z[i][j] = 0 + 0 * I; for (j = 0; j < b.cols; j++) { c.z[i][j] += a.z[i][j] * b.z[j][i]; } } } return c; } int isNormal (matrix a) { int i, j; matrix a_ah, ah_a; if (a.rows != a.cols) return 0; a_ah = multiply (a, transpose (a)); ah_a = multiply (transpose (a), a); for (i = 0; i < a.rows; i++) { for (j = 0; j < a.cols; j++) { if (a_ah.z[i][j] != ah_a.z[i][j]) return 0; } } return 1; } int isUnitary (matrix a) { matrix b; int i, j; if (isNormal (a) == 1) { b = multiply (a, transpose(a)); for (i = 0; i < b.rows; i++) { for (j = 0; j < b.cols; j++) { if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0)) return 0; } } return 1; } return 0; } int main () { complex z = 3 + 4 * I; matrix a, aT; int i, j; printf ("Enter rows and columns :"); scanf ("%d%d", &a.rows, &a.cols); a.z = malloc (a.rows * sizeof (complex *)); printf ("Randomly Generated Complex Matrix A is : "); for (i = 0; i < a.rows; i++) { printf ("\n"); a.z[i] = malloc (a.cols * sizeof (complex)); for (j = 0; j < a.cols; j++) { a.z[i][j] = rand () % 10 + rand () % 10 * I; printf ("\t%f + %fi", creal (a.z[i][j]), cimag (a.z[i][j])); } } aT = transpose (a); printf ("\n\nTranspose of Complex Matrix A is : "); for (i = 0; i < aT.rows; i++) { printf ("\n"); aT.z[i] = malloc (aT.cols * sizeof (complex)); for (j = 0; j < aT.cols; j++) { aT.z[i][j] = rand () % 10 + rand () % 10 * I; printf ("\t%f + %fi", creal (aT.z[i][j]), cimag (aT.z[i][j])); } } printf ("\n\nComplex Matrix A %s hermitian", isHermitian (a) == 1 ? "is" : "is not"); printf ("\n\nComplex Matrix A %s unitary", isUnitary (a) == 1 ? "is" : "is not"); printf ("\n\nComplex Matrix A %s normal", isNormal (a) == 1 ? "is" : "is not"); return 0; }
Continued fraction/Arithmetic/Construct from rational number
C
To understand this task in context please see [[Continued fraction arithmetic]] The purpose of this task is to write a function \mathit{r2cf}(\mathrm{int} N_1, \mathrm{int} N_2), or \mathit{r2cf}(\mathrm{Fraction} N), which will output a continued fraction assuming: :N_1 is the numerator :N_2 is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \mathrm{abs}(N_2) is zero. Demonstrate the function by outputing the continued fraction for: : 1/2 : 3 : 23/8 : 13/11 : 22/7 : -151/77 \sqrt 2 should approach [1; 2, 2, 2, 2, \ldots] try ever closer rational approximations until boredom gets the better of you: : 14142,10000 : 141421,100000 : 1414214,1000000 : 14142136,10000000 Try : : 31,10 : 314,100 : 3142,1000 : 31428,10000 : 314285,100000 : 3142857,1000000 : 31428571,10000000 : 314285714,100000000 Observe how this rational number behaves differently to \sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\infty] when an extra term is required.
#include<stdio.h> typedef struct{ int num,den; }fraction; fraction examples[] = {{1,2}, {3,1}, {23,8}, {13,11}, {22,7}, {-151,77}}; fraction sqrt2[] = {{14142,10000}, {141421,100000}, {1414214,1000000}, {14142136,10000000}}; fraction pi[] = {{31,10}, {314,100}, {3142,1000}, {31428,10000}, {314285,100000}, {3142857,1000000}, {31428571,10000000}, {314285714,100000000}}; int r2cf(int *numerator,int *denominator) { int quotient=0,temp; if(denominator != 0) { quotient = *numerator / *denominator; temp = *numerator; *numerator = *denominator; *denominator = temp % *denominator; } return quotient; } int main() { int i; printf("Running the examples :"); for(i=0;i<sizeof(examples)/sizeof(fraction);i++) { printf("\nFor N = %d, D = %d :",examples[i].num,examples[i].den); while(examples[i].den != 0){ printf(" %d ",r2cf(&examples[i].num,&examples[i].den)); } } printf("\n\nRunning for %c2 :",251); /* 251 is the ASCII code for the square root symbol */ for(i=0;i<sizeof(sqrt2)/sizeof(fraction);i++) { printf("\nFor N = %d, D = %d :",sqrt2[i].num,sqrt2[i].den); while(sqrt2[i].den != 0){ printf(" %d ",r2cf(&sqrt2[i].num,&sqrt2[i].den)); } } printf("\n\nRunning for %c :",227); /* 227 is the ASCII code for Pi's symbol */ for(i=0;i<sizeof(pi)/sizeof(fraction);i++) { printf("\nFor N = %d, D = %d :",pi[i].num,pi[i].den); while(pi[i].den != 0){ printf(" %d ",r2cf(&pi[i].num,&pi[i].den)); } } return 0; }
Convert decimal number to rational
C
The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: * 67 / 74 = 0.9(054) = 0.9054054... * 14 / 27 = 0.(518) = 0.518518... Acceptable output: * 0.9054054 - 4527027 / 5000000 * 0.518518 - 259259 / 500000 Finite decimals are of course no problem: * 0.75 - 3 / 4
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <stdint.h> /* f : number to convert. * num, denom: returned parts of the rational. * md: max denominator value. Note that machine floating point number * has a finite resolution (10e-16 ish for 64 bit double), so specifying * a "best match with minimal error" is often wrong, because one can * always just retrieve the significand and return that divided by * 2**52, which is in a sense accurate, but generally not very useful: * 1.0/7.0 would be "2573485501354569/18014398509481984", for example. */ void rat_approx(double f, int64_t md, int64_t *num, int64_t *denom) { /* a: continued fraction coefficients. */ int64_t a, h[3] = { 0, 1, 0 }, k[3] = { 1, 0, 0 }; int64_t x, d, n = 1; int i, neg = 0; if (md <= 1) { *denom = 1; *num = (int64_t) f; return; } if (f < 0) { neg = 1; f = -f; } while (f != floor(f)) { n <<= 1; f *= 2; } d = f; /* continued fraction and check denominator each step */ for (i = 0; i < 64; i++) { a = n ? d / n : 0; if (i && !a) break; x = d; d = n; n = x % n; x = a; if (k[1] * a + k[0] >= md) { x = (md - k[0]) / k[1]; if (x * 2 >= a || k[1] >= md) i = 65; else break; } h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2]; k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2]; } *denom = k[1]; *num = neg ? -h[1] : h[1]; } int main() { int i; int64_t d, n; double f; printf("f = %16.14f\n", f = 1.0/7); for (i = 1; i <= 20000000; i *= 16) { printf("denom <= %d: ", i); rat_approx(f, i, &n, &d); printf("%lld/%lld\n", n, d); } printf("\nf = %16.14f\n", f = atan2(1,1) * 4); for (i = 1; i <= 20000000; i *= 16) { printf("denom <= %d: ", i); rat_approx(f, i, &n, &d); printf("%lld/%lld\n", n, d); } return 0; }
Convert seconds to compound duration
C
Write a function or program which: * takes a positive integer representing a duration in seconds as input (e.g., 100), and * returns a string which shows the same duration decomposed into: :::* weeks, :::* days, :::* hours, :::* minutes, and :::* seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrate that it passes the following three test-cases: '''''Test Cases''''' :::::{| class="wikitable" |- ! input number ! output string |- | 7259 | 2 hr, 59 sec |- | 86400 | 1 d |- | 6000000 | 9 wk, 6 d, 10 hr, 40 min |} '''''Details''''' The following five units should be used: :::::{| class="wikitable" |- ! unit ! suffix used in output ! conversion |- | week | wk | 1 week = 7 days |- | day | d | 1 day = 24 hours |- | hour | hr | 1 hour = 60 minutes |- | minute | min | 1 minute = 60 seconds |- | second | sec | |} However, '''only''' include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec"). Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec) Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
#include <inttypes.h> /* requires c99 */ #include <stdbool.h> /* requires c99 */ #include <stdio.h> #include <stdlib.h> #define N_EL 5 uintmax_t sec_to_week(uintmax_t); uintmax_t sec_to_day(uintmax_t); uintmax_t sec_to_hour(uintmax_t); uintmax_t sec_to_min(uintmax_t); uintmax_t week_to_sec(uintmax_t); uintmax_t day_to_sec(uintmax_t); uintmax_t hour_to_sec(uintmax_t); uintmax_t min_to_sec(uintmax_t); char *format_sec(uintmax_t); /* the primary function */ int main(int argc, char *argv[]) { uintmax_t input; char *a; if(argc<2) { printf("usage: %s #seconds\n", argv[0]); return 1; } input = strtoumax(argv[1],(void *)0, 10 /*base 10*/); if(input<1) { printf("Bad input: %s\n", argv[1]); printf("usage: %s #seconds\n", argv[0]); return 1; } printf("Number entered: %" PRIuMAX "\n", input); a = format_sec(input); printf(a); free(a); return 0; } /* note: must free memory * after using this function */ char *format_sec(uintmax_t input) { int i; bool first; uintmax_t weeks, days, hours, mins; /*seconds kept in input*/ char *retval; FILE *stream; size_t size; uintmax_t *traverse[N_EL]={&weeks,&days, &hours,&mins,&input}; char *labels[N_EL]={"wk","d","hr","min","sec"}; weeks = sec_to_week(input); input = input - week_to_sec(weeks); days = sec_to_day(input); input = input - day_to_sec(days); hours = sec_to_hour(input); input = input - hour_to_sec(hours); mins = sec_to_min(input); input = input - min_to_sec(mins); /* input now has the remaining seconds */ /* open stream */ stream = open_memstream(&retval,&size); if(stream == 0) { fprintf(stderr,"Unable to allocate memory"); return 0; } /* populate stream */ first = true; for(i=0;i<N_EL;i++) { if ( *(traverse[i]) != 0 ) { if(!first) { fprintf(stream,", %" PRIuMAX " %s", *(traverse[i]), labels[i]); } else { fprintf(stream,"%" PRIuMAX " %s", *(traverse[i]), labels[i]); } fflush(stream); first=false; } } fprintf(stream,"\n"); fclose(stream); return retval; } uintmax_t sec_to_week(uintmax_t seconds) { return sec_to_day(seconds)/7; } uintmax_t sec_to_day(uintmax_t seconds) { return sec_to_hour(seconds)/24; } uintmax_t sec_to_hour(uintmax_t seconds) { return sec_to_min(seconds)/60; } uintmax_t sec_to_min(uintmax_t seconds) { return seconds/60; } uintmax_t week_to_sec(uintmax_t weeks) { return day_to_sec(weeks*7); } uintmax_t day_to_sec(uintmax_t days) { return hour_to_sec(days*24); } uintmax_t hour_to_sec(uintmax_t hours) { return min_to_sec(hours*60); } uintmax_t min_to_sec(uintmax_t minutes) { return minutes*60; }
Copy stdin to stdout
C
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#include <stdio.h> int main(){ char c; while ( (c=getchar()) != EOF ){ putchar(c); } return 0; }
Count the coins
C
There are four types of common coins in US currency: :::# quarters (25 cents) :::# dimes (10 cents) :::# nickels (5 cents), and :::# pennies (1 cent) There are six ways to make change for 15 cents: :::# A dime and a nickel :::# A dime and 5 pennies :::# 3 nickels :::# 2 nickels and 5 pennies :::# A nickel and 10 pennies :::# 15 pennies ;Task: How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents). ;Optional: Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? (Note: the answer is larger than 232). ;References: * an algorithm from the book ''Structure and Interpretation of Computer Programs''. * an article in the algorithmist. * Change-making problem on Wikipedia.
#include <stdio.h> #include <stdlib.h> #include <stdint.h> // ad hoc 128 bit integer type; faster than using GMP because of low // overhead typedef struct { uint64_t x[2]; } i128; // display in decimal void show(i128 v) { uint32_t x[4] = {v.x[0], v.x[0] >> 32, v.x[1], v.x[1] >> 32}; int i, j = 0, len = 4; char buf[100]; do { uint64_t c = 0; for (i = len; i--; ) { c = (c << 32) + x[i]; x[i] = c / 10, c %= 10; } buf[j++] = c + '0'; for (len = 4; !x[len - 1]; len--); } while (len); while (j--) putchar(buf[j]); putchar('\n'); } i128 count(int sum, int *coins) { int n, i, k; for (n = 0; coins[n]; n++); i128 **v = malloc(sizeof(int*) * n); int *idx = malloc(sizeof(int) * n); for (i = 0; i < n; i++) { idx[i] = coins[i]; // each v[i] is a cyclic buffer v[i] = calloc(sizeof(i128), coins[i]); } v[0][coins[0] - 1] = (i128) {{1, 0}}; for (k = 0; k <= sum; k++) { for (i = 0; i < n; i++) if (!idx[i]--) idx[i] = coins[i] - 1; i128 c = v[0][ idx[0] ]; for (i = 1; i < n; i++) { i128 *p = v[i] + idx[i]; // 128 bit addition p->x[0] += c.x[0]; p->x[1] += c.x[1]; if (p->x[0] < c.x[0]) // carry p->x[1] ++; c = *p; } } i128 r = v[n - 1][idx[n-1]]; for (i = 0; i < n; i++) free(v[i]); free(v); free(idx); return r; } // simple recursive method; slow int count2(int sum, int *coins) { if (!*coins || sum < 0) return 0; if (!sum) return 1; return count2(sum - *coins, coins) + count2(sum, coins + 1); } int main(void) { int us_coins[] = { 100, 50, 25, 10, 5, 1, 0 }; int eu_coins[] = { 200, 100, 50, 20, 10, 5, 2, 1, 0 }; show(count( 100, us_coins + 2)); show(count( 1000, us_coins)); show(count( 1000 * 100, us_coins)); show(count( 10000 * 100, us_coins)); show(count(100000 * 100, us_coins)); putchar('\n'); show(count( 1 * 100, eu_coins)); show(count( 1000 * 100, eu_coins)); show(count( 10000 * 100, eu_coins)); show(count(100000 * 100, eu_coins)); return 0; }
Create an HTML table
C
Create an HTML table. * The table body should have at least three rows of three columns. * Each of these three columns should be labelled "X", "Y", and "Z". * An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. * The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. * The numbers should be aligned in the same fashion for all columns.
#include <stdio.h> #include <stdlib.h> int main() { int i; printf("<table style=\"text-align:center; border: 1px solid\"><th></th>" "<th>X</th><th>Y</th><th>Z</th>"); for (i = 0; i < 4; i++) { printf("<tr><th>%d</th><td>%d</td><td>%d</td><td>%d</td></tr>", i, rand() % 10000, rand() % 10000, rand() % 10000); } printf("</table>"); return 0; }
Currency
C
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents. ;Note: The '''IEEE 754''' binary floating point representations of numbers like '''2.86''' and '''.0765''' are not exact. For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate. Use the values: ::* 4000000000000000 hamburgers at $5.50 each (four quadrillion burgers) ::* 2 milkshakes at $2.86 each, and ::* a tax rate of 7.65%. (That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naive task solutions using 64 bit floating point types.) Compute and output (show results on this page): ::* the total price before tax ::* the tax ::* the total with tax The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax. The output must show dollars and cents with a decimal point. The three results displayed should be: ::* 22000000000000005.72 ::* 1683000000000000.44 ::* 23683000000000006.16 Dollar signs and thousands separators are optional.
mpf_set_d(burgerUnitPrice,5.50); mpf_set_d(milkshakePrice,2 * 2.86); mpf_set_d(burgerNum,4000000000000000); mpf_set_d(milkshakeNum,2);
Currying
C
{{Wikipedia|Currying}} ;Task: Create a simple demonstrative example of Currying in a specific language. Add any historic details as to how the feature made its way into the language.
#include<stdarg.h> #include<stdio.h> long int factorial(int n){ if(n>1) return n*factorial(n-1); return 1; } long int sumOfFactorials(int num,...){ va_list vaList; long int sum = 0; va_start(vaList,num); while(num--) sum += factorial(va_arg(vaList,int)); va_end(vaList); return sum; } int main() { printf("\nSum of factorials of [1,5] : %ld",sumOfFactorials(5,1,2,3,4,5)); printf("\nSum of factorials of [3,5] : %ld",sumOfFactorials(3,3,4,5)); printf("\nSum of factorials of [1,3] : %ld",sumOfFactorials(3,1,2,3)); return 0; }
Cut a rectangle
C
A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below. [[file:rect-cut.svg]] Write a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts. Possibly related task: [[Maze generation]] for depth-first search.
#include <stdio.h> #include <stdlib.h> typedef unsigned char byte; int w = 0, h = 0, verbose = 0; unsigned long count = 0; byte **hor, **ver, **vis; byte **c = 0; enum { U = 1, D = 2, L = 4, R = 8 }; byte ** alloc2(int w, int h) { int i; byte **x = calloc(1, sizeof(byte*) * h + h * w); x[0] = (byte *)&x[h]; for (i = 1; i < h; i++) x[i] = x[i - 1] + w; return x; } void show() { int i, j, v, last_v; printf("%ld\n", count); #if 0 for (i = 0; i <= h; i++) { for (j = 0; j <= w; j++) printf("%d ", hor[i][j]); puts(""); } puts(""); for (i = 0; i <= h; i++) { for (j = 0; j <= w; j++) printf("%d ", ver[i][j]); puts(""); } puts(""); #endif for (i = 0; i < h; i++) { if (!i) v = last_v = 0; else last_v = v = hor[i][0] ? !last_v : last_v; for (j = 0; j < w; v = ver[i][++j] ? !v : v) printf(v ? "\033[31m[]" : "\033[33m{}"); puts("\033[m"); } putchar('\n'); } void walk(int y, int x) { if (x < 0 || y < 0 || x > w || y > h) return; if (!x || !y || x == w || y == h) { ++count; if (verbose) show(); return; } if (vis[y][x]) return; vis[y][x]++; vis[h - y][w - x]++; if (x && !hor[y][x - 1]) { hor[y][x - 1] = hor[h - y][w - x] = 1; walk(y, x - 1); hor[y][x - 1] = hor[h - y][w - x] = 0; } if (x < w && !hor[y][x]) { hor[y][x] = hor[h - y][w - x - 1] = 1; walk(y, x + 1); hor[y][x] = hor[h - y][w - x - 1] = 0; } if (y && !ver[y - 1][x]) { ver[y - 1][x] = ver[h - y][w - x] = 1; walk(y - 1, x); ver[y - 1][x] = ver[h - y][w - x] = 0; } if (y < h && !ver[y][x]) { ver[y][x] = ver[h - y - 1][w - x] = 1; walk(y + 1, x); ver[y][x] = ver[h - y - 1][w - x] = 0; } vis[y][x]--; vis[h - y][w - x]--; } void cut(void) { if (1 & (h * w)) return; hor = alloc2(w + 1, h + 1); ver = alloc2(w + 1, h + 1); vis = alloc2(w + 1, h + 1); if (h & 1) { ver[h/2][w/2] = 1; walk(h / 2, w / 2); } else if (w & 1) { hor[h/2][w/2] = 1; walk(h / 2, w / 2); } else { vis[h/2][w/2] = 1; hor[h/2][w/2-1] = hor[h/2][w/2] = 1; walk(h / 2, w / 2 - 1); hor[h/2][w/2-1] = hor[h/2][w/2] = 0; ver[h/2 - 1][w/2] = ver[h/2][w/2] = 1; walk(h / 2 - 1, w/2); } } void cwalk(int y, int x, int d) { if (!y || y == h || !x || x == w) { ++count; return; } vis[y][x] = vis[h-y][w-x] = 1; if (x && !vis[y][x-1]) cwalk(y, x - 1, d|1); if ((d&1) && x < w && !vis[y][x+1]) cwalk(y, x + 1, d|1); if (y && !vis[y-1][x]) cwalk(y - 1, x, d|2); if ((d&2) && y < h && !vis[y + 1][x]) cwalk(y + 1, x, d|2); vis[y][x] = vis[h-y][w-x] = 0; } void count_only(void) { int t; long res; if (h * w & 1) return; if (h & 1) t = h, h = w, w = t; vis = alloc2(w + 1, h + 1); vis[h/2][w/2] = 1; if (w & 1) vis[h/2][w/2 + 1] = 1; if (w > 1) { cwalk(h/2, w/2 - 1, 1); res = 2 * count - 1; count = 0; if (w != h) cwalk(h/2+1, w/2, (w & 1) ? 3 : 2); res += 2 * count - !(w & 1); } else { res = 1; } if (w == h) res = 2 * res + 2; count = res; } int main(int c, char **v) { int i; for (i = 1; i < c; i++) { if (v[i][0] == '-' && v[i][1] == 'v' && !v[i][2]) { verbose = 1; } else if (!w) { w = atoi(v[i]); if (w <= 0) goto bail; } else if (!h) { h = atoi(v[i]); if (h <= 0) goto bail; } else goto bail; } if (!w) goto bail; if (!h) h = w; if (verbose) cut(); else count_only(); printf("Total: %ld\n", count); return 0; bail: fprintf(stderr, "bad args\n"); return 1; }
Damm algorithm
C
The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. ;Task: Verify the checksum, stored as last digit of an input.
#include <stdbool.h> #include <stddef.h> #include <stdio.h> bool damm(unsigned char *input, size_t length) { static const unsigned char table[10][10] = { {0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, {7, 0, 9, 2, 1, 5, 4, 8, 6, 3}, {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, {1, 7, 5, 0, 9, 8, 3, 4, 2, 6}, {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, {3, 6, 7, 4, 2, 0, 9, 5, 8, 1}, {5, 8, 6, 9, 7, 2, 0, 1, 3, 4}, {8, 9, 4, 5, 3, 6, 2, 0, 1, 7}, {9, 4, 3, 8, 6, 1, 7, 2, 0, 5}, {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}, }; unsigned char interim = 0; for (size_t i = 0; i < length; i++) { interim = table[interim][input[i]]; } return interim == 0; } int main() { unsigned char input[4] = {5, 7, 2, 4}; puts(damm(input, 4) ? "Checksum correct" : "Checksum incorrect"); return 0; }
Deceptive numbers
C
Repunits are numbers that consist entirely of repetitions of the digit one (unity). The notation '''Rn''' symbolizes the repunit made up of '''n''' ones. Every prime '''p''' larger than 5, evenly divides the repunit '''Rp-1'''. ;E.G. The repunit '''R6''' is evenly divisible by '''7'''. 111111 / 7 = 15873 The repunit '''R42''' is evenly divisible by '''43'''. 111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677 And so on. There are composite numbers that also have this same property. They are often referred to as ''deceptive non-primes'' or ''deceptive numbers''. The repunit '''R90''' is evenly divisible by the composite number '''91''' (=7*13). 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221 ;Task * Find and show at least the first '''10 deceptive numbers'''; composite numbers '''n''' that evenly divide the repunit '''Rn-1''' ;See also ;* Numbers Aplenty - Deceptive numbers ;* OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}
#include <stdio.h> unsigned modpow(unsigned b, unsigned e, unsigned m) { unsigned p; for (p = 1; e; e >>= 1) { if (e & 1) p = p * b % m; b = b * b % m; } return p; } int is_deceptive(unsigned n) { unsigned x; if (n & 1 && n % 3 && n % 5) { for (x = 7; x * x <= n; x += 6) { if (!(n % x && n % (x + 4))) return modpow(10, n - 1, n) == 1; } } return 0; } int main(void) { unsigned c, i = 49; for (c = 0; c != 50; ++i) { if (is_deceptive(i)) { printf(" %u", i); ++c; } } return 0; }
Deepcopy
C
Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: * Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. * Any limitations of the method. * That the structure and its copy are different. * Suitable links to external documentation for common libraries.
#include<stdlib.h> #include<stdio.h> typedef struct elem{ int data; struct elem* next; }cell; typedef cell* list; void addToList(list *a,int num){ list temp, holder; if(*a==NULL){ *a = (list)malloc(sizeof(cell)); (*a)->data = num; (*a)->next = NULL; } else{ temp = *a; while(temp->next!=NULL) temp = temp->next; holder = (list)malloc(sizeof(cell)); holder->data = num; holder->next = NULL; temp->next = holder; } } list copyList(list a){ list b, tempA, tempB, temp; if(a!=NULL){ b = (list)malloc(sizeof(cell)); b->data = a->data; b->next = NULL; tempA = a->next; tempB = b; while(tempA!=NULL){ temp = (list)malloc(sizeof(cell)); temp->data = tempA->data; temp->next = NULL; tempB->next = temp; tempB = temp; tempA = tempA->next; } } return b; } void printList(list a){ list temp = a; while(temp!=NULL){ printf("%d,",temp->data); temp = temp->next; } printf("\b"); } int main() { list a,b; int i; for(i=1;i<=5;i++) addToList(&a,i); printf("List a is : "); printList(a); b = copyList(a); free(a); printf("\nList a destroyed, List b is : "); printList(b); return 0; }
Department numbers
C
There is a highly organized city that has decided to assign a number to each of their departments: ::* police department ::* sanitation department ::* fire department Each department can have a number between '''1''' and '''7''' (inclusive). The three department numbers are to be unique (different from each other) and must add up to '''12'''. The Chief of the Police doesn't like odd numbers and wants to have an even number for his department. ;Task: Write a computer program which outputs all valid combinations. Possible output (for the 1st and 14th solutions): --police-- --sanitation-- --fire-- 2 3 7 6 5 1
#include<stdio.h> int main() { int police,sanitation,fire; printf("Police Sanitation Fire\n"); printf("----------------------------------"); for(police=2;police<=6;police+=2){ for(sanitation=1;sanitation<=7;sanitation++){ for(fire=1;fire<=7;fire++){ if(police!=sanitation && sanitation!=fire && fire!=police && police+fire+sanitation==12){ printf("\n%d\t\t%d\t\t%d",police,sanitation,fire); } } } } return 0; }
Detect division by zero
C
Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.
#include <limits.h> /* INT_MIN */ #include <setjmp.h> /* siglongjmp(), sigsetjmp() */ #include <stdio.h> /* perror(), printf() */ #include <stdlib.h> /* exit() */ #include <signal.h> /* sigaction(), sigemptyset() */ static sigjmp_buf fpe_env; /* * This SIGFPE handler jumps to fpe_env. * * A SIGFPE handler must not return, because the program might retry * the division, which might cause an infinite loop. The only safe * options are to _exit() the program or to siglongjmp() out. */ static void fpe_handler(int signal, siginfo_t *w, void *a) { siglongjmp(fpe_env, w->si_code); /* NOTREACHED */ } /* * Try to do x / y, but catch attempts to divide by zero. */ void try_division(int x, int y) { struct sigaction act, old; int code; /* * The result must be volatile, else C compiler might delay * division until after sigaction() restores old handler. */ volatile int result; /* * Save fpe_env so that fpe_handler() can jump back here. * sigsetjmp() returns zero. */ code = sigsetjmp(fpe_env, 1); if (code == 0) { /* Install fpe_handler() to trap SIGFPE. */ act.sa_sigaction = fpe_handler; sigemptyset(&act.sa_mask); act.sa_flags = SA_SIGINFO; if (sigaction(SIGFPE, &act, &old) < 0) { perror("sigaction"); exit(1); } /* Do division. */ result = x / y; /* * Restore old hander, so that SIGFPE cannot jump out * of a call to printf(), which might cause trouble. */ if (sigaction(SIGFPE, &old, NULL) < 0) { perror("sigaction"); exit(1); } printf("%d / %d is %d\n", x, y, result); } else { /* * We caught SIGFPE. Our fpe_handler() jumped to our * sigsetjmp() and passes a nonzero code. * * But first, restore old handler. */ if (sigaction(SIGFPE, &old, NULL) < 0) { perror("sigaction"); exit(1); } /* FPE_FLTDIV should never happen with integers. */ switch (code) { case FPE_INTDIV: /* integer division by zero */ case FPE_FLTDIV: /* float division by zero */ printf("%d / %d: caught division by zero!\n", x, y); break; default: printf("%d / %d: caught mysterious error!\n", x, y); break; } } } /* Try some division. */ int main() { try_division(-44, 0); try_division(-44, 5); try_division(0, 5); try_division(0, 0); try_division(INT_MIN, -1); return 0; }
Determinant and permanent
C
permanent of the matrix. The determinant is given by :: \det(A) = \sum_\sigma\sgn(\sigma)\prod_{i=1}^n M_{i,\sigma_i} while the permanent is given by :: \operatorname{perm}(A)=\sum_\sigma\prod_{i=1}^n M_{i,\sigma_i} In both cases the sum is over the permutations \sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.) More efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known. ;Related task: * [[Permutations by swapping]]
#include <stdio.h> #include <stdlib.h> #include <tgmath.h> void showmat(const char *s, double **m, int n) { printf("%s:\n", s); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%12.4f", m[i][j]); putchar('\n'); } } int trianglize(double **m, int n) { int sign = 1; for (int i = 0; i < n; i++) { int max = 0; for (int row = i; row < n; row++) if (fabs(m[row][i]) > fabs(m[max][i])) max = row; if (max) { sign = -sign; double *tmp = m[i]; m[i] = m[max], m[max] = tmp; } if (!m[i][i]) return 0; for (int row = i + 1; row < n; row++) { double r = m[row][i] / m[i][i]; if (!r) continue; for (int col = i; col < n; col ++) m[row][col] -= m[i][col] * r; } } return sign; } double det(double *in, int n) { double *m[n]; m[0] = in; for (int i = 1; i < n; i++) m[i] = m[i - 1] + n; showmat("Matrix", m, n); int sign = trianglize(m, n); if (!sign) return 0; showmat("Upper triangle", m, n); double p = 1; for (int i = 0; i < n; i++) p *= m[i][i]; return p * sign; } #define N 18 int main(void) { double x[N * N]; srand(0); for (int i = 0; i < N * N; i++) x[i] = rand() % N; printf("det: %19f\n", det(x, N)); return 0; }
Determine if a string has all the same characters
C
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are the same ::::* indicate if or which character is different from the previous character ::* display each string and its length (as the strings are being examined) ::* a zero-length (empty) string shall be considered as all the same character(s) ::* process the strings from left-to-right ::* if all the same character, display a message saying such ::* if not all the same character, then: ::::* display a message saying such ::::* display what character is different ::::* only the 1st different character need be displayed ::::* display where the different character is in the string ::::* the above messages can be part of a single message ::::* display the hexadecimal value of the different character Use (at least) these seven test values (strings): :::* a string of length 0 (an empty string) :::* a string of length 3 which contains three blanks :::* a string of length 1 which contains: '''2''' :::* a string of length 3 which contains: '''333''' :::* a string of length 3 which contains: '''.55''' :::* a string of length 6 which contains: '''tttTTT''' :::* a string of length 9 with a blank in the middle: '''4444 444k''' Show all output here on this page.
/** * An example for RossetaCode - an example of string operation with wchar_t and * with old 8-bit characters. Anyway, it seem that C is not very UTF-8 friendly, * thus C# or C++ may be a better choice. */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* * The wide character version of the program is compiled if WIDE_CHAR is defined */ #define WIDE_CHAR #ifdef WIDE_CHAR #define CHAR wchar_t #else #define CHAR char #endif /** * Find a character different from the preceding characters in the given string. * * @param s the given string, NULL terminated. * * @return the pointer to the occurence of the different character * or a pointer to NULL if all characters in the string * are exactly the same. * * @notice This function return a pointer to NULL also for empty strings. * Returning NULL-or-CHAR would not enable to compute the position * of the non-matching character. * * @warning This function compare characters (single-bytes, unicode etc.). * Therefore this is not designed to compare bytes. The NULL character * is always treated as the end-of-string marker, thus this function * cannot be used to scan strings with NULL character inside string, * for an example "aaa\0aaa\0\0". */ const CHAR* find_different_char(const CHAR* s) { /* The code just below is almost the same regardles char or wchar_t is used. */ const CHAR c = *s; while (*s && c == *s) { s++; } return s; } /** * Apply find_different_char function to a given string and output the raport. * * @param s the given NULL terminated string. */ void report_different_char(const CHAR* s) { #ifdef WIDE_CHAR wprintf(L"\n"); wprintf(L"string: \"%s\"\n", s); wprintf(L"length: %d\n", wcslen(s)); const CHAR* d = find_different_char(s); if (d) { /* * We have got the famous pointers arithmetics and we can compute * difference of pointers pointing to the same array. */ wprintf(L"character '%wc' (%#x) at %d\n", *d, *d, (int)(d - s)); } else { wprintf(L"all characters are the same\n"); } wprintf(L"\n"); #else putchar('\n'); printf("string: \"%s\"\n", s); printf("length: %d\n", strlen(s)); const CHAR* d = find_different_char(s); if (d) { /* * We have got the famous pointers arithmetics and we can compute * difference of pointers pointing to the same array. */ printf("character '%c' (%#x) at %d\n", *d, *d, (int)(d - s)); } else { printf("all characters are the same\n"); } putchar('\n'); #endif } /* There is a wmain function as an entry point when argv[] points to wchar_t */ #ifdef WIDE_CHAR int wmain(int argc, wchar_t* argv[]) #else int main(int argc, char* argv[]) #endif { if (argc < 2) { report_different_char(L""); report_different_char(L" "); report_different_char(L"2"); report_different_char(L"333"); report_different_char(L".55"); report_different_char(L"tttTTT"); report_different_char(L"4444 444k"); } else { report_different_char(argv[1]); } return EXIT_SUCCESS; }