Skip to content

Instantly share code, notes, and snippets.

@jaldhar
Created June 23, 2017 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaldhar/5c24443fb3a5d34e1778962d17d53135 to your computer and use it in GitHub Desktop.
Save jaldhar/5c24443fb3a5d34e1778962d17d53135 to your computer and use it in GitHub Desktop.
Fold a string into a triangle
// triangle -- Fold a string into a triangle.
//
// From https://codegolf.stackexchange.com/questions/127649/fold-a-string-into-a-triangle
//
// By Jaldhar H. Vyas <jaldhar@braincells.com>
// Copyright (C) 2017, Consolidated Braincells Inc. All rights reserved.
// "Do what thou wilt shall be the whole of the license."
//
// Given a string whose length is divisible by 4, make a triangle as
// demonstrated below.
//
// If the string is abcdefghijkl, then the triangle would be:
//
// a
// b l
// c k
// defghij
//
// If the string is iamastringwithalengthdivisblebyfour, then the triangle would
// be:
// i
// a r
// m u
// a o
// s f
// t y
// r b
// i e
// n l
// gwithalengthdivisib
//
// If the string is thisrepresentationisnotatriangle, then the triangle would
// be:
// t
// h e
// i l
// s g
// r n
// e a
// p i
// r r
// esentationisnotat
//
// To compile: c++ -std=c++14 -O2 -g -Wall -o triangle triangle.cc
//
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char* argv[]) {
if (argc < 2) {
cerr << "Usage: triangle \"string\"" << endl;
return EXIT_FAILURE;
}
string input(argv[1]);
size_t len = input.length();
if (len % 4 != 0) {
cerr << "Length of string must be divisble by 4" << endl;
return EXIT_FAILURE;
}
size_t n = len / 4;
size_t left = 1;
size_t right = len - 1;
// Top of the triangle
cout.width(n + 1);
cout << input[0] << '\n';
// Intermediate lines
for (size_t i = 1, offset = n, gap = 2; i < n; i++, offset--, gap += 2) {
cout.width(offset);
cout << input[left++];
cout.width(gap);
cout << input[right--] << '\n';
}
// Base of the triangle
for (size_t i = left; i <= right; i++) {
cout << input[i];
}
cout << endl;
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment