>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
Wait, you need it to stop on a blank line, not EOF. #!/bin/sh
sort_lines() { awk '$0=="" { exit } { for(i=1;i
William Reed
What a stupid useless idea for a program. Why do teachers assign dumb crap like this instead of real world examples?
Jace Howard
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
Adam Sanders
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.
Zachary Fisher
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
Brayden Price
Curious to see a C, C++ or Java person take a shot at this
Jackson Gutierrez
#include
int main(void) { for (unsigned int i = 1; i
Isaiah Howard
...
Aaron Clark
good post.
Jayden Morris
good job, where's the code?
Jayden Jones
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
Jordan Bell
proprietary, would you like to buy a license?
>
Luke Clark
Can you not tell by the obviously shitty way I wrote it, that it's supposed to be shitty?
Anthony Scott
all C++ code looks ugly so no one could tell
Bentley Wilson
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
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))
Matthew Lopez
I wouldn't want to see a 1 liner lol it would be completely unreadable I'm sure aka shit code
Matthew Edwards
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); }
Kayden Cooper
>writing C this poorly Reeeeeeeee
Wyatt Cooper
Nice, I don't really care about pretty I just wanted to see different ways to do it
Austin Davis
powershell ignoring the blank line rule, pretty sure OP implied that on accident. %{$_.split()} | sort -property length
Brayden Gray
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 "
Adam Cox
very nice user
Robert Wright
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.
Isaac Thomas
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(" ")); }
Hunter Clark
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(" ")); }
Parker Fisher
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
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() != "");
lines = [] loop do str = gets break if str.nil? or str.chomp!.empty? lines
Dominic Hernandez
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.
Ryder Lee
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(' ')
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
Gabriel Hall
>but sorts them from longest words to shortest words Oops, replace the "" in the last line.
Kayden Russell
Which language is this?
Michael Martinez
D
Jaxson Cruz
Looks pretty good.
William Brooks
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$
Gabriel Martinez
I'll just post the fiddle so Sup Forums can make fun of me later and go "lolwebdev":
main = go [] >>= return . reverse . sortOn length >>= putStrLn . unwords where go ls = do l
Leo Jones
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
William Ortiz
Yah, I looked at mine after and confused myself with my go and whatnot. w/e its 6am and I'm tired
Adam Watson
#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
Dylan Fisher
>use module ???
Jayden Long
main = interact (intercalate " " . sortBy (flip $ on compare length) . concatMap words . takeWhile (not . null) . lines)
Samuel Hughes
now do it without linq, and without do while, because that's a stupid loop
Cooper Rivera
nice job
Julian Scott
Ruby puts(Enumerator.new{ |e| loop{ e
Isaac Sullivan
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))
Landon Ortiz
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?
Grayson Martin
or maybe not. It looks like they don't support quite a few of the lesser used languages like D, Haskell, etc. Too bad
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)); }
Nolan Long
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 ;;
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(' '));
This looks nice, it also shows input and output so you don't even have to try it yourself to see that it works.
Gabriel Barnes
Also, it supports Haskell and D
Andrew Phillips
/toy program challenge/?
Julian Ross
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
Chase Turner
I was just throwing out a potential thread name
Gavin Lopez
>gcc version 4.6.3 >4.6 They are very outdated
Dylan Carter
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