Programming Exercise!

OKAY LADS, I'VE ENTERED THE MATRIX. PROGRAM A FUNCTION THAT WILL PRINT A GIVEN SENTENCE IN A NICE FRAME. OR THIS BIRD WILL STAB YOU DIGITALLY.

As always here's the first example:

>pic rel: output
public static void main(String[] args) {
RandomExcercises re = new RandomExcercises();
re.printFrame("Quite frankly I do not like black females I prefer caucasian females");
}

public void printFrame(String sentence) {
String[] words = sentence.split(" ");

int longestLength = 0;
for (String word : words) {
if (word.length() > longestLength)
longestLength = word.length();
}

for (int i = 0; i < longestLength + 6; i++)
System.out.print("#");
System.out.println();

System.out.print("#");
for (int i = 0; i < longestLength + 4; i++)
System.out.print(" ");
System.out.print("#");
System.out.println();

for (String word : words) {

System.out.print("# ");

for (int i = 0; i < Math.floor((double) (longestLength - word.length()) / 2.0); i++)
System.out.print(" ");

System.out.print(word);

for (int i = 0; i < Math.ceil((double) (longestLength - word.length()) / 2.0); i++)
System.out.print(" ");

System.out.println(" #");
}

System.out.print("#");
for (int i = 0; i < longestLength + 4; i++)
System.out.print(" ");
System.out.print("#");
System.out.println();

for (int i = 0; i < longestLength + 6; i++)
System.out.print("#");
System.out.println();
}

println("############################");
println("####A GIVEN SENTENCE#####");
println("############################");

here u go bro

Homework?

YOU HAVE BEEN STABBED

NO SEE SECOND POST. FOR YOU IT IS HOMEWORK, YES.

>FOR YOU IT IS HOMEWORK, YES.
Kek, using Sup Forums to do your homework, pathetic.

Never learned CS, college dropout master race reporting in.

Dont hurt me Mr. Bird I am new to programming

s,,q+# +.shift.q+ #+,e+print join qq+\n+,q+#+x length,$_,q+#+x length

$ perl birdplsno.pl "bird please no"
##################
# bird please no #
##################
$

U HAVE BEEN WARNED
LOOK AT THE EXAMPLE: LOOKS BETTER, BUT NOW TRY ALIGNING TEXT IN THE MIDDLE WHILE EACH WORD IS ON A NEW LINE.

>BUT NOW TRY ALIGNING TEXT IN THE MIDDLE WHILE EACH WORD IS ON A NEW LINE.
or what?

i wanna see someone use ncurses

Just stab me then Mr.Bird

Kek, faggots are literary helping OP to do his homework.

NICE TRIPS BUT YOU WILL BE STABBED.

void Main()
{
Console.println("************************************************");
Console.println("* ");
Console.println("* Hello World *");
Console.println("* ");
Console.println("************************************************");
}

YOU BETTER NOT BE THAT RETARDED ON PURPOSE:
IT IS SUMMER, THIS IS THE BIRDMIN. BIRDMIN DOESN'T HAVE HOMEWORK. BUT YOU DO! STABBEDDDD!

Welcome back, OP!

class String
def in_a_box
# find width
words = self.split
width = 4 + words.max_by(&:size).size
#create output
output = "#" * width
output

def pprint(userInput):
border = "*" * (len(userInput) + 4)
print(border)
print("* " + userInput + " *")
print(border)

def main():
userInput = input("Insert a new string: ")
pprint(userInput)

if __name__ == "__main__":
main()

Fucking Tabs messed up my formatting..

class String
def in_a_box
# find width
words = self.split
width = 4 + words.max_by(&:size).size
#create output
output = "#" * width

var pretty = function(text, maxlen) {
var borderWidth = 2;
var borderChar = '#';
//ensure no word in text is > maxlen
var words = text.split(" ");
words.forEach(function(word) {
//increase the maxlen to the largest word if so
if(word.length > maxlen)
maxlen = word.length;
});

var lines = [];
var line = "";
var clin = 0;
//prep the bull
words.forEach(function(word) {
word += " ";
if(line.length + word.length > maxlen) {
var diff = maxlen - line.length;
line += " ".repeat(diff);
lines[clin] = line;
line = "";
clin++;
}
line += word;
});
//fix up the last line
var diff = maxlen - line.length;
line += " ".repeat(diff);
lines[clin] = line;

//borders
var prettyLines = [];
for(var i = 0; i < borderWidth; i++) {
prettyLines[i] = borderChar.repeat(borderWidth*2 + maxlen);
prettyLines[i+lines.length+borderWidth] = borderChar.repeat(borderWidth*2 + maxlen);
}
//content
for(var i = 0; i < lines.length; i++) {
prettyLines[i+borderWidth] = borderChar.repeat(borderWidth)+lines[i]+borderChar.repeat(bo
rderWidth);
}

return prettyLines;
}

look i did it mom

import framedtext

printframed("A GIVEN SENTENCE")

Is that python?
Looks fucking swell.

Glorious C is absolutely the best language to do this in.
[spoiler]kill me[/spoiler]
#include
#include

/*
* Draw a nicu framu of the given text to stdout
* @param border the border character to use
* @param divider the divider char to split the text on
* @param pad padding around the text (including the border)
*/
void draw_frame(char *text, char border, char text_divider, int pad) {
char divider_string[] = {text_divider, 0};
int text_length = (int) strlen(text);
int max_width = 0;
int lines = 1;

for (int i = 0, j = 0; i < text_length; i++) {
if (text[i] != text_divider) {
j++;
} else {
lines++;
j = 0;
}
if (j >= max_width) max_width = j;
}

int w = max_width + pad * 2 + 1; // +1 for newlines
int h = lines + pad * 2;
char out[w * h + 1];
out[sizeof(out) - 1] = 0;

for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int i = y * w + x;
if (x == w - 1) {
out[i] = '\n';
} else if (x == 0 || x == w - 2 || y == 0 || y == h - 1) {
out[i] = border;
} else {
out[i] = ' ';
}
}
}

int last = 0, y = 2, x = 0, stop = 0;
while (!stop) {
char *next_newline = strstr(text + last, divider_string);
if (!next_newline) {
stop = 1;
next_newline = text + text_length;
}
int pos = (int) (next_newline - text);
x = w / 2 - ((pos - last) + 1) / 2;
memcpy(out + w * y + x, text + last, (size_t) (pos - last));
last = pos + 1;
y++;
}

printf("%s\n", out);
}

int main(void) {
draw_frame("just fuck my shit up family", '#', ' ', 2);
}

Funny

>words.forEach
Is this really idiomatic in js these days? Seems like huge waste of cycles to me, and more typing than a for.

It's ruby

Neat use of the language built-ins, like .max_by .size .center
Is extending the String class idiomatic for Ruby?

Not doing what op said. u failed

This sounds like fun

Will do when I get home, thanks OP

>Is this really idiomatic in js these days? Seems like huge waste of cycles to me, and more typing than a for.

the the built in for each lop is faster than the for loop.
its recommended to actually use the built in functions for what they do.
es6 has a lot of nice features too and has been clocked faster than cpp in some cases with v8 and chakra.

may or may not work
var s = "kek kuk cuck kik kak",
d = ['div','style'],
div , style;
d.map(a => eval(a + ' = document.createElement(' + a +')'));
div.createTextNode(s);
style.createTextNode('.kek{border: 3px outset red; border-radius:3px}');
div.className = 'kek';
d.map(a => eval('document.body.appendChild(' + a + ')'));

What's the definition of "a"?

the argument
current array element
like
['div', 'style'].map(function(a){console.log(a)})
gives us first div, then style

>the the built in for each lop is faster than the for loop.
Ah, I guess the foreach this way allows the jit to optimize more aggressively than just a for loop.

>es6 has a lot of nice features too and has been clocked faster than cpp in some cases with v8 and chakra.
Like you said, some cases. It's good but take it with a grain of salt.

C#
using System;
namespace Bordering
{
class Programmation
{
static void Main(string[] args)
{
Console.WriteLine("Input some Poo");
PrintTheFrameMyOstrige(_input: Console.ReadLine());
Console.ReadKey();
}
static void PrintTheFrameMyOstrige(string _input)
{
string[] palabras = _input.Split(' ');
int maxLength = 0;
string word = string.Empty;
for(int k=0;k maxLength)
{
maxLength = word.Length;
}
}
for(int i = 0;i

I am Dragon Dildo Man and I say fuck you and suck my cock.

sage.

I hate foreach loops and so, in my adaptation, I started to write one but then I decided that foreach loops must die.

You just copied birdman

>911

Never forget.

Could that image have any more padding?

Of course.

#!/usr/bin/env node
/*!
**| OP's Homework
**| frameText.sh.js
**|
**| Written by X
**| Version 2016.08.08.0900
**|
**@license WTFPL
*/

const borderChar = '#';
let inputs = process.argv.slice(2);

if(!inputs.length){
process.stderr.write('FATAL EXCEPTION: NO INPUT SPECIFIED.\n');
process.exit(9);
}

function printFrame(text){
const longestWord = Math.max(...text.map((s)=>{ return s.length; }));

function bookend(start){
function cap(){
process.stdout.write(Array(longestWord+6).join(borderChar));
process.stdout.write('\n');
}
if(start){ cap(); }
process.stdout.write(borderChar);
process.stdout.write(Array(longestWord+4).join(' '));
process.stdout.write(borderChar);
process.stdout.write('\n');
if(!start){ cap(); }
}

bookend(true);
text.forEach((cv)=>{
process.stdout.write(borderChar + ' ');

process.stdout.write(longestWord === cv.length ? '' : Array(Math.floor((longestWord - cv.length) / 2) + 1).join(' '));
process.stdout.write(cv);
process.stdout.write(longestWord === cv.length ? '' : Array(Math.ceil((longestWord - cv.length) / 2) + 1).join(' '));

process.stdout.write(' ' + borderChar);
process.stdout.write('\n');
});
bookend(false);
}

while(inputs.length){
let input = inputs.shift().split(' ');
printFrame(input);
process.stdout.write('\n');
}

process.exit(0);

>@license WTFPL
Don't

These threads are amazing, even though never reply to them.

import math

def box(string):
words = string.split(' ')
width = max(map(len, words)) + 4
bar = '#' * width
margin = lambda w: (width - len(w) - 2) / 2
right = lambda w: math.ceil(margin(w)) * ' ' + '#'
left = lambda w: '#' + ' ' * math.floor(margin(w))
row = lambda w: left(w) + w + right(w)
return '\n'.join([bar, *[row(w) for w in words], bar])

print(box('birdmin is a pretty cool guy'))

*map(row, words)

>Neat use of the language built-ins, like .max_by .size .center

Thanks!

>Is extending the String class idiomatic for Ruby?

It's called "monkey patching" and the way I did this is not consider good style, especially in bigger projects ..
Basically every string can now use the method "in_the_box" which is not desirable (think of name conflicts).

A proper approach would be.. well, there are serveral ways.

The most simple solution would be to use inheritance and create a sub-class of string:

class String_with_box < String
def in_a_box
# code here
end
end

s = String_with_box.new("OP is (literally) a glorious winged faggot")

puts s # normal output
puts s.in_a_box # output with box

Haha, nice..

I never knew there are so many similar operators in Ruby and Python3, like string multiplying ('#' * x) and the "sponge"-operator (*[some Array here] ).

Python is definately nice, if I have some time I'll try to pick it up along the way..

>tfw nobody comments on my code
t-that means it's perfect right?

def box_print(text, padding)
words = [' '] + text.split(' ') + [' ']
max = words.map { |w| w.length }.sort!.reverse![0] + (2*padding) + 2
puts '*'*max
words.each { |w| puts '*' + ' '*(padding+(max-2-(2*padding)-w.length)/2).ceil + w \
+ ' '*(padding+(max-2.0-(2*padding)-w.length)/2).ceil + '*' }
puts '*'*max
end

text = 'Fuck off and die'
box_print text, 3

#output {
border: 1px solid;
word-spacing: 9999px;
text-align: center;
}

Which one is your code user-chan?

this

toilet --gay "A GIVEN SENTENCE"
or
figlet A GIVEN SENTENCE

Mainly just nit-picky

>(int) strlen(text);
Don't be afraid of size_t

>text_divider
strtok

>for (y) for (x), if case1 case2 case3
do case 3 (' ') with memset
do case 2's y = 0/y = h with memset
do case 1 and 2's x with a single for loop

>Mainly just nit-picky
I don't mind, I'm not that good with C

>Don't be afraid of size_t
My IDE / compiler does warn about this, so I thought a cast was appropriate.

>strtok
Didn't know about this, thanks! It's way better, I should've googled it first.

echo -e "\nmuslims\n"

Which one was yours?

Have you?

>IN A NICE FRAME
So, how about adding newlines to the given sentence to make the frame around it as close to 1.618:1 w:h? sound good?

...

thats me, delete this now or im calling the police

Just do it, I've never been stabbed digitally before, what is it like?

like getting a bad dragon up the ass but better

Might I comment?


> text.split(' ')

You could also just write "text.split", since blank is the default delimiter..


> max = words.map { |w| w.length }.sort!.reverse![0] + (2*padding) + 2

No need to use "sort!" and "reverse!" here. With "max = words.map (..)" you already create a new Array instance, therefore you should use "sort" and "reverse", since you have a new Array anyway.


>' '*(padding+(max-2-(2*padding)-w.length)/2).ceil

I guess you know that the "String::center" function does this job for you? But if you want to calculate the space on your own, it's nicely done..

blank != ' '
It splits on spaces.

sentence

also every time knifebird user asks me to make something with string manipulation i hate him a little because strsplit()'s output is a list and I hate dealing with lists in R.

Every solution has offcentered words as we are talking about text and not pixels here. As long as the border is allright it's okay.

It just werks

Probably could be a lot shorter but it works ok

import Data.List

main :: IO ()
main = do
input IO ()
niceframe input = do
mapM_ putStrLn [hash,blank,fixed,blank,hash]
where fixed = intercalate "\n" $ map (handle len) input
len = 8 + (maximum $ map length input)
hash = take len $ cycle "#"
blank = concat $ ["#", take (len - 2) $ cycle " ", "#"]

handle :: Int -> String -> String
handle max xs = concat $ ["#", space gap1, xs, space gap2, "#"]
where gap = max - length xs - 2
gap1 = gap `div` 2
space x = take x $ cycle " "
gap2
| odd gap = gap `div` 2 + 1
| otherwise = gap `div` 2

#!/usr/bin/env python

def box(string, width=30):
pad_right = lambda n: ' ' * (n - 1) + '║'

words = string.split(' ')
response = ['╔' + '═' * (width - 2) + '╗']
response += ['║']

while(words):
if len(response[-1] + words[0]) < width - 1:
response[-1] += ' ' + words.pop(0)
else:
response[-1] += pad_right(width - len(response[-1]))
response += ['║']

response[-1] += pad_right(width - len(response[-1]))
response += ['╚' + '═' * (width - 2) + '╝']

return '\n'.join(response)

print(box("I'm reminded of the day my daughter came in, looked over my shoulder at some Perl 4 code, and said, 'What is that, swearing?"))

> no eXtended ASCII tables
> all centered text
Come on user.

Shit's messed up, couldn't be arsed to make it more clean

I did what he asked, it's (You) who did not understand what he asked.

#!/bin/sh
cowsay $1

the only correct answer

bump

#include
#include
#include
#include

#define PADDING 2

void printtimes(char c, int n) {
for(int i = 0; i < n; i++) {
std::cout

$ ./frame "I have no idea what I'm doing."
############
# #
# I #
# have #
# no #
# idea #
# what #
# I'm #
# doing. #
# #
############


#include
#include
#include
#include
#include

void split(const std::string& sentence,
char delim,
std::vector& out) {
std::istringstream stream(sentence);
std::string word;

while (std::getline(stream, word, delim)) {
out.push_back(word);
}
}

int max_len(const std::vector& words) {
int max = -1;
for (const auto& word : words) {
int len = word.length();
if (len > max) max = len;
}
return max;
}

std::pair padding(std::string word, int max_len) {
int len = word.length();
int diff = max_len - len;
double raw_pad = (diff) / 2;
int front_pad = (int) std::floor(raw_pad);
return std::make_pair(front_pad, diff - front_pad);
}

void print_word(std::string word, int max_len) {
std::cout

post code fgt

Jesus c++ is ugly

probably only because that's basically my first c++ program besides hello world

i've been meaning to learn it for a while now but never got around to actually doing it

No way! You can have the end of it though.
))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))

Hope so, just realised I'm probably doing a year of it next uni year, will still be better than c# though hopefully. I want to do meme languages like haskell

#include
#include

int main()
{
std::string input;
std::vector words;

int maxLen = 0;

words.push_back("");
while(std::cin >> input)
{
words.push_back(input);
maxLen = std::max(maxLen, (int)input.size());
}
words.push_back("");
maxLen += 4;

for(int i = 0;i < maxLen + 2;++ i) std::cout

Please don't stab me senpai

main = do
text

Ur mum loves getting digitally stabbed, even licks my fingers after.

Use code tags you plebs

def pad(word, length):
word = "#" + " "*((length-len(word))/2) + word
word = word + " "*(length-len(word))+"#"
return word

def frame(words):
words = [""]+words.split(" ")+[""]
width = len(max(words, key=len))+5
yield "#"*(width+1)
for i in words:
yield pad(i, width)
yield "#"*(width+1)

for i in frame("I bond burgered your sister last night"):
print i

##############
# #
# I #
# bond #
# burgered #
# your #
# sister #
# last #
# night #
# #
##############

Running a pre-existing program doesn't count. The least you could do is reimplement it.

textframe

>2016
>Still on Python 2
Do you even asyncio bro?

(defun stabby (str)
(let* ((words (tokenize str))
(len (reduce #'max (mapcar #'length words))))
(format t "~%~v@{~A~:*~}~%~A~v@{~A~:*~}~2:*~A"
(+ 6 len) #\# (+ 4 len) #\Space)
(dolist (word words)
(format t "~%#~v@{~A~:*~}~*~A~v@{~A~:*~}#"
(+ 2 (floor (- len (length word)) 2)) #\Space word
(+ 2 (ceiling (- len (length word)) 2)) #\Space))
(format t "~%~*~A~v@{~A~:*~}~2:*~A~%~2:*~v@{~A~:*~}"
(+ 6 len) #\# (+ 4 len) #\Space)))

(defun tokenize (str)
(loop for start = 0 then (1+ end)
for end = (position #\Space str :start start)
collect (subseq str start end)
until (null end)))

>:*~}
:*~}

What a mindfuck

cowsay

no birdo no
frame s
= do
border
putStr "|" >> putStr s >> putStrLn "|"
border
where border = putStrLn (replicate (length s + 2) '-')

main = do
sentence > getLine
frame sentence

zeroth order naive solution

textBox :: String -> Int -> String -> String
textBox border maxWidth str = unlines $ [ header ] ++ content ++ [ header ]
where header = take boxWidth $ cycle border
content = map (pad . fill) lines
boxWidth = maximum $ map length content

pad line = unwords $ [ border, line, border ]
lines = reverse . map (unwords . reverse) . foldl f [] $ words str
textWidth = maximum $ map length lines

fill line = left ++ line ++ right
where (left, right) = (replicate q ' ', replicate (q+r) ' ')
(q, r) = (textWidth - length line) `quotRem` 2

f [] w = [[w]]
f (l:ls) w
| length (pad $ unwords l')

it's somewhat flexible though

λ putStrLn $ textBox "" 40 "OKAY LADS, I'VE ENTERED THE MATRIX. PROGRAM A FUNCTION THAT WILL PRINT A GIVEN SENTENCE IN A NICE FRAME. OR THIS BIRD WILL STAB YOU DIGITALLY."

OKAY LADS, I'VE ENTERED THE
MATRIX. PROGRAM A FUNCTION THAT
WILL PRINT A GIVEN SENTENCE IN A
NICE FRAME. OR THIS BIRD WILL STAB
YOU DIGITALLY.

λ putStrLn $ textBox "@@" 80 "OKAY LADS, I'VE ENTERED THE MATRIX. PROGRAM A FUNCTION THAT WILL PRINT A GIVEN SENTENCE IN A NICE FRAME. OR THIS BIRD WILL STAB YOU DIGITALLY."
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ OKAY LADS, I'VE ENTERED THE MATRIX. PROGRAM A FUNCTION THAT WILL PRINT A @@
@@ GIVEN SENTENCE IN A NICE FRAME. OR THIS BIRD WILL STAB YOU DIGITALLY. @@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

you're gay if you can't even do this homework assignment

>doesn't count
According to what?
>the least you could do
You saw the leat they could do. Go be stupid somewhere else.

Breh OP always posts his own solution as an example.

haskellfags, r8 me

import Data.List

main = do
s > getLine)
frame (words s)

encumber a b = b >> a >> b

frame xs = encumber (mapM_ foo xs) border
where paddingL x = div (biggest - length x) 2
paddingR x = biggest - length x - paddingL x
border = putStrLn ("+" ++ replicate (biggest + 2) '-' ++ "+")
biggest = length (maximumBy (\x y -> length x `compare` length y) xs)
foo x = do
putStr "| "
putStr (replicate (paddingL x) ' ')
putStr x
putStr (replicate (paddingR x) ' ')
putStrLn " |"

this is really good holy shit

A++ FOR YOU HASKELL, WILL GET HASKELL AS A SUBJECT THIS YEAR ON UNI, SO MIGHT HAVE TO CREATE SOME EXERCISE EXAMPLES WITH THAT.

TO THE FAGS THAT USE NATIVE/PRE-EXISTING SOLUTIONS: STABBED. GET YOUR MIND TO DO SOME WORK

TO THE GUYS THAT THINK I CAN'T DO MY OWN HOMEWORK: STABBED, YOU POOR FAGGOTS CAN'T EVEN SEE STRAIGHT. THE 2ND POST IS MINE.

(PHP IS A BIT MEH THO)
(C# & JAVA IS JUST COPY AND TRANSLATE)
TO THE GUYS THAT DID IT IN OTHER LANGUAGES: GRADED A


TO THE GUYS THAT KEPT ALL TEXT ON ONE LINE: STABBED AND F-, TRY AGAIN. FAGGOTS.

NICE ASCII CHARACTERS, CLEAN SOLUTION.