Write a function that takes a list of lines from the user, stopping at the first empty line

>Write a function that takes a list of lines from the user, stopping at the first empty line.
>Then print out every word from every line (space separated) but sorts them from longest words to shortest words.

Python example:
def sort_lines():
lines, separated = [], []
while True:
entry = input('Enter a line: ')
if not entry:
break
lines.append(entry)

for line in lines:
words = line.split()
for word in words:
separated.append(word)
separated.sort(key=len, reverse=True)
print(' '.join(separated))


Example Input:
This post was made to the Sup Forums technology board called Sup Forums
What is Sup Forums's favorite language?
install gentoo


Example Output:
technology language? favorite install called gentoo Sup Forums board Sup Forums's This post made What was the Sup Forums to is

Other urls found in this thread:

rosettacode.org/
jsfiddle.net/9uyno0no/2/
repl.it/languages/
repl.it/F2AM/0
tutorialspoint.com/codingground.htm
ideone.com/ImzW8J
twitter.com/NSFWRedditGif

#!/bin/sh

sort_lines() {
awk '{ for(i=1;i

Wait, you need it to stop on a blank line, not EOF.
#!/bin/sh

sort_lines() {
awk '$0=="" { exit } { for(i=1;i

What a stupid useless idea for a program.
Why do teachers assign dumb crap like this instead of real world examples?

For the same reason people learn a bunch of math they'll never use in the real world. It's about thinking logically, critical thinking, etc

For what it's worth I do this kind of thing in the real world at work all the time. I'm a systems engineer and I often need to take long lists of servers from say stdin and do something with the list.

I'm ignorant of shell scripts but I trust that this works. Pretty cool I was hoping to see different ways to solve it with different languages

Curious to see a C, C++ or Java person take a shot at this

#include

int main(void)
{
for (unsigned int i = 1; i

...

good post.

good job, where's the code?

this is a shitty fizzbuzz

#include
using namespace std;

int main()
{
for(int i = 1; i != 100; ++i)
{
bool fizz = (i % 3 == 0);
bool buzz = (i % 5 == 0);

if(fizz && buzz)
cout

proprietary, would you like to buy a license?

>

Can you not tell by the obviously shitty way I wrote it, that it's supposed to be shitty?

all C++ code looks ugly so no one could tell

my options:
>this guy is pulling the ultimate bamboozle and writing an intentionally sodomized fizzbuzz program
>this is yet another Sup Forums autist who doesn't know how to program

why would you expect me to choose the former?

roasted

package a;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class b {
public static void main(String[] args) {
String input = ""; ArrayList unsorted = new ArrayList();
Scanner scan = new Scanner(System.in);
do {
input = scan.nextLine();
unsorted.addAll(Arrays.asList(input.split(" ")));
} while (!input.isEmpty());
unsorted.sort((f1, f2) -> Long.compare(f1.length(), f2.length()));
unsorted.forEach(f -> System.out.print(f + " "));
}
}


I'd like to see a one line solution, but I'm too shit to do it

Why would I do this when I'm not even being threatened by a bird?

You're right. You got me.
#!/usr/bin/env ruby

1.upto(100) do
|number|
((number % 3 == 0) && !(number % 5 == 0)) && (puts "Fizz")
((number % 5 == 0) && !(number % 3 == 0)) && (puts "Buzz")
((number % 3 == 0) && (number % 5 == 0)) && (puts "FizzBuzz")
!((number % 3 == 0) || (number % 5 == 0)) && (puts number)
end

little bit of improvement:

def sort_lines():
lines, separated = [], []
while True:
entry = input('Enter a line: ')
if not entry:
break
lines.append(entry)
for line in lines:
separated += line.split()
separated.sort(key=len, reverse=True)
print(' '.join(separated))

I wouldn't want to see a 1 liner lol it would be completely unreadable I'm sure aka shit code

here you go, it's not pretty but I tried to keep it as short as possible
#include
#include
#include

#define BUFFER_SIZE 16

int main() {
int words_cap = BUFFER_SIZE;
int words_count = 0;
char **words = malloc(sizeof(char *) * words_cap); // should check for failure but fuck that

int word_cap = BUFFER_SIZE;
int word_len = 0;
char *word = malloc(word_cap); // should check for failure but fuck that

char prev = '\0';
char c;
while (c != EOF && (prev != '\n' || c != '\n')) {
prev = c;
c = getchar();
if (c == ' ' || c == '\n') {
if (word_len > 0) {
word[word_len] = '\0';
if (words_count >= words_cap) {
words_cap *= 2;
words = realloc(words, sizeof(char *) * words_cap); // should check for failure but fuck that
}
int i = words_count;
while (i > 0 && strlen(words[i - 1]) < word_len) {
words[i] = words[i - 1];
i--;
}
words[i] = word;
words_count++;
word_cap = BUFFER_SIZE;
word_len = 0;
word = malloc(word_cap); // should check for failure but fuck that
}
} else if (c != EOF) {
if (word_len + 1 >= word_cap) {
word_cap *= 2;
word = realloc(word, word_cap); // should check for failure but fuck that
}
word[word_len] = c;
word_len++;
}
}
for (int i = 0; i < words_count; i++) {
printf("%s\n", words[i]);
free(words[i]);
}
free(word);
free(words);
}

>writing C this poorly
Reeeeeeeee

Nice, I don't really care about pretty I just wanted to see different ways to do it

powershell ignoring the blank line rule, pretty sure OP implied that on accident.
%{$_.split()} | sort -property length

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with System.Pool_Local;
with Ada.Containers.Vectors;

procedure Word_Problem is
Vector_Pool : System.Pool_Local.Unbounded_Reclaim_Pool;
type String_Pointer is access all String with Storage_Pool=>Vector_Pool;
function "="(Left, Right : String_Pointer) return Boolean is (Left.all = Right.all);
function "

very nice user

It actually does alphabetical order, but that's a trivial change and the inner loop should check Index_Start /= 0 , but whatever no one cares.

Rust
use std::io;

fn main() {
let mut lines = vec![];
let input = io::stdin();

loop {
let mut line = String::new();
match input.read_line(&mut line) {
Ok(1) => {
break;
},
Ok(_) => {
for word in line.split_whitespace() {
lines.push(word.to_string());
}
},
Err(e) => {
println!("Failed because of {}", e);
return;
}
}
}
lines.sort_by(|a, b| b.len().cmp(&a.len()));
println!("{}", lines.join(" "));
}

This can be done in a shorter way
use std::io;

fn main() {
let mut words:Vec = vec![];
let mut line = String::new();
let input = io::stdin();
loop {
match input.read_line(&mut line) {
Ok(1) => break,
Ok(_) => words.extend(line.split_whitespace().map(Into::into)),
Err(e) => {
println!("Failed because of {}", e);
return;
}
}
}
words.sort_by(|a, b| b.len().cmp(&a.len()));
println!("{}", words.join(" "));
}

Probably could be shortened quite a bit.
#include
#include
#include
#include
#include

std::vector tokenize(std::string);

int main()
{
std::string line;
std::string all_words;
while (true) {
std::cout rhs.length();
});
for (const auto s : tokens) {
std::cout

while {[gets stdin line] >= 0 && $line ne ""} {
lappend words {*}[split $line]
}
puts [lsort -command {apply {{x y} {
expr {[string length $x] < [string length $y]}
}}} $words]

def sort_lines()
words = []
while (line = gets) != "\n"
line.chomp.split(/ +/).each {|word| words

>all c++
fuckiing kill me useless fag language

I forgot to mention this is Ruby

What language is this?

ah, I was trying to figure it out. I've never seen 'chomp' before

jq -srR 'split("\n")|.[0:index("")]|[.[]|split("\\s";"")|.[]]|sort_by(-length)|join(" ")'

It removes trailing whitespace (including the newline character from the call to gets). As far as I know it does the same thing as .rstrip

Tcl

cool, I love the increasing diversity of this thread

for(i=0;i3){f-=3}
b=i;while(b>5){b-=5}
if(f==3&&b!=5){trace("fizz")}
if(f!=3&&b==5){trace("buzz")}
if(f==3&&b==5){trace("fizzbuzz")}
if(f!=3&&b!=5){trace(i)}
}

C#, LINQ is a beast:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
static void Main(string[] args)
{
List allWords = new List();
do
{
allWords.AddRange(Console.ReadLine().Split(' '));
}
while (allWords.Last() != "");

allWords.OrderByDescending(word => word.Count()).ToList().ForEach(word => Console.Write(word + " "));
}
}

Pajeet, we saw your post the first time around.

Wow ya caught me

Elixir
IO.stream(:stdio, :line)
|> Stream.take_while(& &1 != "\n")
|> Stream.flat_map(& &1 |> String.trim_trailing("\n") |> String.split(~r/\s/))
|> Enum.to_list
|> Enum.sort(& String.length(&1) >= String.length(&2))
|> Enum.join(" ")
|> IO.puts

awesome

Guile Scheme
(use-modules (ice-9 rdelim) (srfi srfi-26))

(let loop ((words '()))
(let ((line (read-line)))
(if (string-null? line)
(map (cute simple-format #t "~A " )
(sort words (lambda (x y) (> (string-length x) (string-length y)))))
(loop (append words (string-split line char-whitespace?))))))

Don't let all this identical code go to waste, you bastards. Post it to Rosetta Code.

rosettacode.org/

lines = []
loop do
str = gets
break if str.nil? or str.chomp!.empty?
lines

I called it a beast for a reason. Powerful but ugly. It isn't so bad once you get used to it and it is really quite capable.

Unless you're referring to the style and in that case IDGAF.

I just realized this can be rewritten as
words = []
while (line = gets) != "\n"
words += line.chomp.split(/ +/)
end
puts words.sort_by {|word| word.length}.reverse.join(' ')


Slightly cleaner

my @words;
while((my $input = ) ne "\n"){
chomp $input;
foreach my $w(split / /, $input){
@words = sort {length($b) length($a)} $w, @words;
}
}
print join ' ', @words, "\n";

void main() {
import std.stdio: readln, writeln;
import std.string: chomp;
import std.array: split;
import std.algorithm: sort;

string[] words;
string[] line;

while ((line = readln.chomp.split).length != 0)
words ~= line;
words.sort!("a.length < b.length").writeln;
}

>tfw the import list is longer than the actual program

>but sorts them from longest words to shortest words
Oops, replace the "" in the last line.

Which language is this?

D

Looks pretty good.

size = 0
GLOBAL words$ ARRAY size

SUB add_word(word$)
size = size + 1
REDIM words$ TO size
words$[size - 1] = word$
END SUB

WHILE TRUE DO
READLN s$ FROM stdin
IF s$ == "" THEN
BREAK
FI
SPLIT s$ BY " " TO s_words$ SIZE count
FOR i = 0 TO count - 1
add_word(s_words$[i])
NEXT
WEND

REPEAT
LET same = 1
FOR i = 1 TO size - 1
IF LEN(words$[i - 1]) < LEN(words$[i]) THEN
same = 0
SWAP words$[i], words$[i - 1]
FI
NEXT
UNTIL same

JOIN words$ BY " " TO s$ SIZE size
PRINT s$

I'll just post the fiddle so Sup Forums can make fun of me later and go "lolwebdev":

jsfiddle.net/9uyno0no/2/

Based Haskell
import Data.List (sortOn)
import Control.Monad (liftM)

main = liftM lsort (getAllLines []) >>= putStrLn . unwords

getAllLines :: [String] -> IO [String]
getAllLines ls = getLine >>= go
where go l = if null l
then return $ concatMap words ls
else getAllLines $ l:ls

lsort :: [String] -> [String]
lsort = reverse . sortOn length

Even shorter
import Data.List (sortOn)

main = go [] >>= return . reverse . sortOn length >>= putStrLn . unwords
where go ls = do l

Not as ugly as I thought it would be.
import Data.List (sortOn); main = let go ls = getLine >>= (\l -> if null l then return $ concatMap words ls else go $ l:ls) in go [] >>= return . reverse . sortOn length >>= putStrLn . unwords

Yah, I looked at mine after and confused myself with my go and whatnot.
w/e its 6am and I'm tired

#include
#include
#include
#include
#include

int main() {
std::vector words;
std::string s;
while(getline(std::cin, s) && !s.empty()) {
std::istringstream ss(s);
while (std::getline(ss, s, ' '))
words.push_back(s);
}
std::sort(words.begin(), words.end(),
[](const auto& x, const auto& y) {return x.size() > y.size();});
for (size_t i = 0; i < words.size(); ++i) {
if (i) std::cout

>use module
???

main = interact (intercalate " " . sortBy (flip $ on compare length) . concatMap words . takeWhile (not . null) . lines)

now do it without linq, and without do while, because that's a stupid loop

nice job

Ruby
puts(Enumerator.new{ |e| loop{ e

a little more optimized python version

def shorter():
lines = []
while True:
entry = input('Enter a line: ')
if not entry:
break
lines.append(entry)
separated = sum((line.split() for line in lines), [])
separated.sort(key=len, reverse=True)
print(' '.join(separated))

OP here. I've been using repl.it/languages/ to run code in this thread to see which solutions actually work.

It'd be cool to make these code challenge threads a regular thing, and we could use this site to link our working examples.

What do you guys think?

or maybe not. It looks like they don't support quite a few of the lesser used languages like D, Haskell, etc. Too bad

Wrong.

in what way? his example works for me

repl.it/F2AM/0

did this like in ten minutes i guess
function sort_lines($input) {
$lines = explode("\n",$input);
$words = [];
foreach($lines as $line) {
$line = trim($line);
if(strlen($line) == 0) {
break;
} else {
$temp_words = explode(' ',$line);
foreach($temp_words as $temp_word) {
array_push($words,$temp_word);
}
}
}
$words = array_unique($words);
array_multisort(array_map('strlen', $words), $words);
return implode(' ',array_reverse($words));
}

No sorry. I didn't know the function std::getline, I usually use getline of std::istream which is more annoying to use. Thank for the hint user.

module String_set = Set.Make (String);;

let fold_words f e line =
let index_from s i c =
try
Some (String.index_from s i c)
with
| Not_found -> None in
let len = String.length line in
let rec loop e i =
match index_from line i ' ' with
| None ->
let word = String.sub line i (len - i) in
f e word
| Some j ->
let word = String.sub line i (j - i) in
loop (f e word) (succ j) in
loop e 0
;;

let rec collect words =
match read_line () with
| "" -> words
| line ->
let folder words = function
| "" -> words
| word -> String_set.add word words in
let words = fold_words folder words line in
collect words
;;

let main () =
let words = collect String_set.empty in
let words =
List.sort
(fun s1 s2 -> String.length s2 - String.length s1)
(String_set.elements words) in
let rec print_words ppf = function
| [] -> ()
| [ word; ] -> Format.fprintf ppf "%s" word
| word :: words ->
Format.fprintf ppf "%s@ %a" word print_words words in
Format.printf "@[%a@]@." print_words words
;;

let () = main ();;

nice

tutorialspoint.com/codingground.htm

LINQ is nice, but why would you sacrifice readability for it?
static void Main(string[] args)
{
string inp;
var lst = new List();
while (!string.IsNullOrEmpty((inp = Console.ReadLine())))
lst.AddRange(inp.Split(' '));

lst.Sort((s1, s2) => s2.Length - s1.Length);
Console.WriteLine(string.Join(" ", lst));
}

Sweet language selection, but the site seems really sluggish. Maybe it's a time of a day thing

ideone.com/ImzW8J

This looks nice, it also shows input and output so you don't even have to try it yourself to see that it works.

Also, it supports Haskell and D

/toy program challenge/?

good find, I like their super short urls too

Use whatever language is best suited for such a simple task, or just use whatever you want. There's a lot of languages in this thread

I was just throwing out a potential thread name

>gcc version 4.6.3
>4.6
They are very outdated

Yeah last few posts we've been searching for a proper online IDE that can handle all languages necessary. Maybe we should just stick to posting [ code ] and trusting anons when they say it works. It's not like we're being graded or something I guess

ideone.com looks nice but I've been getting bugs with it already, just trying to run simple python code, so I dunno

Go 1.8
package main

import (
"bufio"
"bytes"
"fmt"
"os"
"sort"
"strings"
)

func main() {
var buffer bytes.Buffer

scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
if scanner.Text() == "" {
break
}
buffer.WriteString(" ")
buffer.WriteString(scanner.Text())
}

words := strings.Split(strings.Trim(buffer.String(), " "), " ")
sort.Slice(s, func(i, j int) bool {
return len(s[i]) < len(s[j])
})
fmt.Printf("%+v", words)
}

This thread has the following languages so far, pretty cool IMO

>python
>bash
>java
>ruby
>c
>c++
>c#
>ada
>rust
>d
>jq
>tcl
>guile scheme
>javascript
>haskell
>php
>go
>ocaml
>perl
>pascal

I don't see Pascal ITT.

yeah I probably goofed that list up, I've been trying to guess what some of these are.

I assume this one is BASIC but could be wrong

No love for assembly here?

show us how it's done

It's Basic.

MAGIC

Since gcc can output the assembly file (ends in .s I think?) couldn't you just take working C code from here and generate assembly

could cheat and take the c solution and read the generated assembly code.

hivemind