to display this without using any loop ..?!
Recursion
Well, that's a little hard😂 #include <stdio.h> #include <stdlib.h> #define L(x) long x #define M main #define R return #define A atoi #define C char #define P(x) printf("%c", x) L(n)=-1;L(M)(L(r),L(c) ){L(v)=c+r-n;R n==-1 ?M(n=A(1[(C**)c]), 0):r==0?0:c>=n+r -1?(P(10),M(r- 1,0)):(P(v<0 ?32:8234>> ((v&1)<< 3)),M( r,c+1 )); } /* Example: % gcc -g triangle.c && ./a.out 10 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
A template version. I'm new to meta programming. Anybody knows more elegant ways? #include <iostream> #include <iterator> #include <algorithm> #include <utility> #include <array> #include <string> constexpr char get_char(size_t size, size_t index, size_t indent = 0) { auto last = size * 2 + indent - 1; if (size == 0) return 0; if (index == last) return '\n'; if (index > last) return get_char(size - 1, index - (last + 1), indent + 1); if (index < indent) return ' '; if ((index - indent) & 1) return ' '; return '*'; } constexpr size_t get_char_count(size_t size, size_t indent = 0) { if (size == 0) return 0; return size * 2 + indent + get_char_count(size - 1, indent + 1); } template <size_t n> struct TriangleString { static constexpr size_t count = get_char_count(n); using sequence = std::make_index_sequence<count>; template <size_t ...index> static constexpr auto to_array(std::index_sequence<index...>) { return std::array<char, count>{{get_char(n, index)...}}; } static constexpr std::array<char, count> value = to_array(sequence()); }; template <size_t n> constexpr std::array<char, TriangleString<n>::count> TriangleString<n>::value; int main() { auto arr = TriangleString<5>::value; auto it = std::ostream_iterator<char>{std::cout}; std::copy(std::begin(arr), std::end(arr), it); return 0; }
Обсуждают сегодня