[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y ] [Search | Free Show | Home]

>Write a function that takes a list of lines from the user,

This is a blue board which means that it's for everybody (Safe For Work content only). If you see any adult content, please report it.

Thread replies: 138
Thread images: 17

File: challenge.png (13KB, 320x320px) Image search: [Google]
challenge.png
13KB, 320x320px
>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 4chan technology board called /g/
What is /g/'s favorite language?
install gentoo


Example Output:
technology language? favorite install called gentoo 4chan board /g/'s This post made What was the /g/ to is
>>
>>58725257
#!/bin/sh

sort_lines() {
awk '{ for(i=1;i<=NF;i++) { print length($i), $i }}' |
sort -n -r |
cut -d' ' -f 2 |
tr '\n' ' '
echo ""
}
>>
>>58726137
Wait, you need it to stop on a blank line, not EOF.
#!/bin/sh

sort_lines() {
awk '$0=="" { exit } { for(i=1;i<=NF;i++) { print length($i), $i }}' |
sort -n -r |
cut -d' ' -f 2 |
tr '\n' ' '
echo ''
}
>>
What a stupid useless idea for a program.
Why do teachers assign dumb crap like this instead of real world examples?
>>
>>58726185
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
>>
>>58726185
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.
>>
>>58726172
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
>>
File: 1470430509245.gif (339KB, 492x376px) Image search: [Google]
1470430509245.gif
339KB, 492x376px
>>58725257
Curious to see a C, C++ or Java person take a shot at this
>>
#include <iostream>

int main(void)
{
for (unsigned int i = 1; i <= 100; i++) {
((i % 3 == 0) && !(i % 5 == 0)) && std::cout << "Fizz" << std::endl;
((i % 5 == 0) && !(i % 3 == 0)) && std::cout << "Buzz" << std::endl;
((i % 3 == 0) && (i % 5 == 0)) && std::cout << "FizzBuzz" << std::endl;
!((i % 3 == 0) || (i % 5 == 0)) && std::cout << i << std::endl;
}

return 0;
}
>>
File: keklipse.png (6KB, 777x103px) Image search: [Google]
keklipse.png
6KB, 777x103px
>>58726595
>>
>>58727382
good post.
>>
>>58727415
good job, where's the code?
>>
>>58727382
this is a shitty fizzbuzz

#include <iostream>
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 << "fizzbuzz\n";
else if(fizz)
cout << "fizz\n";
else if(buzz)
cout << "buzz\n";
else
cout << i << endl;
}
return 0;
}
>>
File: keklipse.png (14KB, 1008x247px) Image search: [Google]
keklipse.png
14KB, 1008x247px
>>58727447
proprietary, would you like to buy a license?

>>58727382
>
>>
>>58727451
Can you not tell by the obviously shitty way I wrote it, that it's supposed to be shitty?
>>
>>58727495
all C++ code looks ugly so no one could tell
>>
>>58727495
my options:
>this guy is pulling the ultimate bamboozle and writing an intentionally sodomized fizzbuzz program
>this is yet another /g/ autist who doesn't know how to program

why would you expect me to choose the former?

>>58727503
roasted
>>
>>58725257
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<String> 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
>>
>>58725257
Why would I do this when I'm not even being threatened by a bird?
>>
>>58727529
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
>>
File: gnu-summed-up.jpg (190KB, 1280x960px) Image search: [Google]
gnu-summed-up.jpg
190KB, 1280x960px
>>58725257
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))
>>
>>58727559
I wouldn't want to see a 1 liner lol it would be completely unreadable I'm sure aka shit code
>>
>>58726595
here you go, it's not pretty but I tried to keep it as short as possible
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#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);
}
>>
>>58728295
>writing C this poorly
Reeeeeeeee
>>
File: dude.jpg (44KB, 620x375px) Image search: [Google]
dude.jpg
44KB, 620x375px
>>58728295
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 "<"(Left, Right : String_Pointer) return Boolean is (Left.all < Right.all);
package String_Vectors is new Ada.Containers.Vectors(Index_Type=>Positive, Element_Type=>String_Pointer);
package String_Vectors_Sort is new String_Vectors.Generic_Sorting;

String_Vector : String_Vectors.Vector;

begin
loop
declare
S : String := Get_Line;
Temp_Pointer : String_Pointer;
Index_Start : Natural := 1;
Index_End : Natural := 1;
begin
exit when S'Length = 0;
while Index_End /= S'Last+1 loop
Index_End := Index(S, " ", Index_Start);
if Index_End = 0 then
Index_End := S'Last+1;
end if;
Temp_Pointer := new String(1..Index_End-Index_Start);
Move(S(Index_Start..Index_End-1), Temp_Pointer.all);
String_Vectors.Append(String_Vector, Temp_Pointer);
Index_Start := Index_Non_Blank(S, Index_End);
end loop;
end;
end loop;

Put_Line("-----");

String_Vectors_Sort.Sort(String_Vector);

for I of String_Vector loop
Put_Line(I.all);
end loop;
end Word_Problem;
>>
>>58729717
very nice anon
>>
>>58730076
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(" "));
}
>>
>>58730216
This can be done in a shorter way
use std::io;

fn main() {
let mut words:Vec<String> = 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 <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>

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

int main()
{
std::string line;
std::string all_words;
while (true) {
std::cout << "Type a line of text: \n";
std::getline(std::cin, line);
if (line.empty()) {
break;
}
all_words += line + " ";
}
auto tokens = tokenize(all_words);
std::sort(tokens.begin(), tokens.end(),
[](const std::string &lhs, const std::string &rhs) {
return lhs.length() > rhs.length();
});
for (const auto s : tokens) {
std::cout << s << ' ';
}
std::cout << '\n';
return 0;
}

std::vector<std::string> tokenize(std::string line)
{
std::vector<std::string> ret;
std::stringstream ss(line);
std::string temp;
while (std::getline(ss, temp, ' ')) {
ret.push_back(temp);
}
return ret;
}


$ ./code_challenge
Type a line of text:
This post was made to the 4chan technology board called /g/
Type a line of text:
What is /g/'s favorite language?
Type a line of text:
install gentoo
Type a line of text:

technology language? favorite install gentoo called 4chan /g/'s board This What post made was /g/ the is to
>>
>>58725257
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]
>>
>>58725257
def sort_lines()
words = []
while (line = gets) != "\n"
line.chomp.split(/ +/).each {|word| words << word}
end
puts words.sort_by {|word| word.length}.reverse.join(' ')
end
>>
>all c++
fuckiing kill me useless fag language
>>
>>58730581
I forgot to mention this is Ruby
>>
>>58730391
What language is this?
>>
>>58730605
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(" ")'
>>
>>58730618
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
>>
>>58730608
Tcl
>>
>>58730697
cool, I love the increasing diversity of this thread
>>
for(i=0;i<100;i++){
f=i;while(f>3){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<string> allWords = new List<string>();
do
{
allWords.AddRange(Console.ReadLine().Split(' '));
}
while (allWords.Last() != "");

allWords.OrderByDescending(word => word.Count()).ToList().ForEach(word => Console.Write(word + " "));
}
}
>>
>>58730847
Pajeet, we saw your post the first time around.
>>
>>58730860
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
>>
>>58730922
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.

http://rosettacode.org/
>>
lines = []
loop do
str = gets
break if str.nil? or str.chomp!.empty?
lines << str
end
puts lines.flat_map(&:split).sort_by(&:length).reverse.join(' ')


>>58730581
I like the
while (line = gets)  != "\n"


>>58730847
the ugliest thing i've seen all day
>LINQ is a beast
>>
>>58731062
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.
>>
>>58730581
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 = <STDIN>) 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
>>
>>58731611
>but sorts them from longest words to shortest words
Oops, replace the "<" with a ">" in the last line.
>>
>>58731611
Which language is this?
>>
>>58731738
D
>>
>>58731748
Looks pretty good.
>>
>>58725257
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$
>>
>>58725257
I'll just post the fiddle so /g/ can make fun of me later and go "lolwebdev":

https://jsfiddle.net/9uyno0no/2/
>>
File: sortlist.png (12KB, 1040x495px) Image search: [Google]
sortlist.png
12KB, 1040x495px
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
>>
>>58732503
Even shorter
import Data.List (sortOn)

main = go [] >>= return . reverse . sortOn length >>= putStrLn . unwords
where go ls = do l <- getLine
if null l
then return $ concatMap words ls
else go $ l:ls
>>
>>58727559
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
>>
>>58732552
Yah, I looked at mine after and confused myself with my go and whatnot.
w/e its 6am and I'm tired
>>
>>58725257
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>

int main() {
std::vector<std::string> 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 << " ";
std::cout << words[i];
}
std::cout << std::endl;
return EXIT_SUCCESS;
}

>>
>>58730950
>use module
???
>>
>>58725257
main = interact (intercalate " " . sortBy (flip $ on compare length) . concatMap words . takeWhile (not . null) . lines)
>>
>>58730847
now do it without linq, and without do while, because that's a stupid loop
>>
>>58732198
nice job
>>
>>58725257
Ruby
puts(Enumerator.new{ |e| loop{ e << gets.chomp } }.take_while{ |l| !l.empty? }.flat_map(&:split).sort_by(&:size).reverse)
>>
>>58725257
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))
>>
File: 1439904774106.jpg (115KB, 1300x866px) Image search: [Google]
1439904774106.jpg
115KB, 1300x866px
>>58725257
OP here. I've been using https://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?
>>
File: Untitled.png (75KB, 1076x988px) Image search: [Google]
Untitled.png
75KB, 1076x988px
>>58738239
or maybe not. It looks like they don't support quite a few of the lesser used languages like D, Haskell, etc. Too bad
>>
>>58730367
Wrong.
>>
>>58738349
in what way? his example works for me

https://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));
}
>>
>>58738431
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 anon.

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 "@[<v>%a@]@." print_words words
;;

let () = main ();;
>>
>>58731511
nice
>>
>>58738300
https://www.tutorialspoint.com/codingground.htm
>>
>>58730847
LINQ is nice, but why would you sacrifice readability for it?
>>58736199
static void Main(string[] args)
{
string inp;
var lst = new List<string>();
while (!string.IsNullOrEmpty((inp = Console.ReadLine())))
lst.AddRange(inp.Split(' '));

lst.Sort((s1, s2) => s2.Length - s1.Length);
Console.WriteLine(string.Join(" ", lst));
}
>>
>>58740266
Sweet language selection, but the site seems really sluggish. Maybe it's a time of a day thing
>>
File: ideone.png (140KB, 1590x910px) Image search: [Google]
ideone.png
140KB, 1590x910px
>>58738239
>>58738300
https://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.
>>
File: also.png (53KB, 844x435px) Image search: [Google]
also.png
53KB, 844x435px
>>58738300
>>58740565

Also, it supports Haskell and D
>>
/toy program challenge/?
>>
>>58740565
>>58740589
good find, I like their super short urls too

>>58740639
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
>>
>>58740677
I was just throwing out a potential thread name
>>
>>58738239
>gcc version 4.6.3
>4.6
They are very outdated
>>
>>58740795
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)
}

>>
File: c_programming_language.jpg (105KB, 480x640px) Image search: [Google]
c_programming_language.jpg
105KB, 480x640px
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
>>
>>58741357
I don't see Pascal ITT.
>>
>>58741376
yeah I probably goofed that list up, I've been trying to guess what some of these are.

>>58732047
I assume this one is BASIC but could be wrong
>>
No love for assembly here?
>>
>>58741629
show us how it's done
>>
>>58741498
It's Basic.
>>
>>58741684
MAGIC
>>
>>58741872
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
>>
>>58741629

could cheat and take the c solution and read the generated assembly code.
>>
>>58741978
>>58742011
hivemind
>>
::  /hoon/sorter/gen
/- sole
[. sole]
::
:- %ask
|= *
^- (sole-result (cask *))
=| strings/(list cord)
%+ sole-yo leaf+"Enter strings of text. Finish with an empty line."
|-
%+ sole-lo [& %$ ">"]
|= string/tape
?. =(string "")
%+ sole-yo leaf+"> {string}"
^$(strings [(crip string) strings])
=. strings
%+ sort strings
|= {a/@ b/@}
(gth a b)
%+ sole-yo
:+ %rose
["\0a" ~ ~]
%+ turn strings
|= s/cord
leaf+(trip s)
%- sole-so [%$ ~]


Result:
> +sorter
Enter strings of text. Finish with an empty line.
> what you're
> referring to
> as linux
> is actually
> a meme
referring to
is actually
what you're
as linux
a meme
>>
>>58742328
>hoon
>on my /g/
Holy shit, anon. What star do you hail from?
>>
File: madass.gif (2MB, 320x240px) Image search: [Google]
madass.gif
2MB, 320x240px
>>58742328
the result is supposed to combine all strings into a single string and sort the words from longest length to shortest length. but whatever, nice code nonetheless

>hoon
>>
Perl
sub w{while(<>){/^$/&&last;push@a,$_};print join" ",sort{-length($a)<=>-length($b)}map{split}@a}
>>
>>58742382
Orbiting ~wanzod. Greetings!

>>58742439
Sorry, it's late. Reading comprehension is way down. Might rewrite sometime tomorrow.
>>
let a = []
process.stdin.on('data', d => {
if (d == '\n') {
console.log(a.sort((x,y)=>x.length<y.length).join(' '))
process.exit()
}
a = a.concat(d.toString().split(' ').map(x=>x.replace('\n','')))
})
>>
>>58742473
Golfed a bit more, because why not.
sub w{while(<>){/^$/&&last;push@a,$_};print join$",sort{-length$a<=>-length$b}map{split}@a}
>>
>>58742535
interesting, I haven't used perl before. that's not a lot of code
>>
>>58742535

Wow, no wonder people say perl is write-only.

I can only imagine being ready to leave a company and writing a ton of code like this right before I left.
>>
>>58738476
anon, I know you're writing php, but for php that's gross.

observe this beauty

<?php

$lines = "This post was made to the 4chan technology board called /g/
What is /g/'s favorite language?
install gentoo";

$lines = explode(' ', str_replace("\n", ' ', $lines));
usort($lines, function($a, $b) { return ((strlen($a) < strlen($b)) ? 1 : -1); });
print implode(' ', $lines);
>>
-- Lua 5.1/LuaJIT
function sort_lines()
local words = {}
for line in io.lines() do
if line == "" then break end
for word in string.gmatch(line, "[^%s]+") do
words[#words + 1] = word
end
end
table.sort(words, function (a, b)
return string.len(a) > string.len(b)
end)
print(table.concat(words, " "))
end

sort_lines()
>>
File: thumbs-up.gif (1MB, 320x240px) Image search: [Google]
thumbs-up.gif
1MB, 320x240px
>>58744240
>>
>>58742702
What is a code formatter
>>
#include <iostream>
#include <map>
#include <vector>
#include <sstream>

int main()
{
std::string str;
std::string word;
std::map<int, std::vector<std::string>> words;

do
{
std::getline(std::cin, str);
std::istringstream ss(str);
while(ss >> word)
{
words[word.length()].push_back(word);
}
}while(!str.empty());

for(auto wordvec = words.rbegin(); wordvec != words.rend(); ++wordvec)
{
for(auto word : wordvec->second)
{
std::cout << word << " ";
}
}
std::cout << std::endl;
}
>>
>>58745331
this looks pretty clean. I've never written C++ before, does it get old having type std:: pretty much constantly?
>>
>>58725257

>2017
>using mutable variables

(use '[clojure.string :as str])
(defn dongs []
(loop [l (read-line)
lines []]
(if (str/blank? l)
(->> lines
(map #(str/split % #"\s+"))
(reduce concat [])
(sort-by count))
(recur (read-line) (conj lines l)))))
>>
>>58745584
It's bothersome at first, but you get used to it.
>>
>>58745778
whoops, forgot to reverse after sorting
>>
>>58745584
I'd have a macro on my computer if I used c++, tbqh
>>
>>58725257
So easy with Ruby.

def sort_lines(lines)
p_words = lines.take_while {|line| line != ''}.reduce {|a, b| a + ' ' + b}.split(' ').sort {|a, b| b.length <=> a.length}
end
>>
File: code_sort.png (6KB, 1448x80px) Image search: [Google]
code_sort.png
6KB, 1448x80px
>>58746024
Formatted.
>>
words = []
while True:
line = input().split()
if not line:
break
words += line
print(' '.join(sorted(words, key=len, reverse=True)))
>>
>>58746094
You should learn to use code tags
>>

var line = [];
var text;

while((text = prompt("Enter a line:", "")) ? line.push(text): false);

line.sort(function(a, b) { return b - a;});

line.forEach(function(element) { document.write(element + '<br>'); });

>>
Perl.

%_=map{map{$_=>1} split /\W+/} <>; print join " ",sort{length $b <=> length $a} keys %_;
>>
>>58747223
Oops, that one was bad. This one is correct.

var line = [];
var text;

while((text = prompt("Enter a line:", "")) ? text.split(" ").forEach(function(element) { line.push(element) }) || true : false);

line = line.sort(function(a, b) { return b.length - a.length;});

line.forEach(function(element) { document.write(element + '<br>'); });
>>
>>58747295
Ah, so it seems there's no need to remove duplicates. Then it can be written shorter.

print join " ",sort{length $b <=> length $a} map{split /\W+/} <>;
>>
PHP Cli
<?php

$lines = [];
while ( ($line = readline()) != '') {
$lines[] = $line;
}
$words = array_reduce($lines,function ($words,$line) {
return array_merge($words,explode(' ',$line));
},[]);
usort($words,function($a,$b){
return strlen($b)-strlen($a);
});
echo implode(' ',$words);
>>
>>58725257

import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class Challenge {
public static void main(String[] args) {
List<String> words = new LinkedList<>();
@SuppressWarnings("resource")
Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
while(!input.equals("")) {
words.addAll(Arrays.asList(input.trim().split("\\s+")));
input = kb.nextLine();
}

words.stream().sorted(Comparator.comparingInt(str -> -str.length())).forEach(System.out::println);
}
}


Gives following output/input:
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class Challenge {
public static void main(String[] args) {
List<String> words = new LinkedList<>();
@SuppressWarnings("resource")
Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
while(!input.equals("")) {
words.addAll(Arrays.asList(input.trim().split("\\s+")));
input = kb.nextLine();
}

words.stream().sorted(Comparator.comparingInt(str -> -str.length())).forEach(System.out::println);
}
}
>>
>>58730847

but it's uglier than the equivalent Java statement:
>>58747484

The Java reads better.
LINQ is supposed to be better than the Java alternative, and you made it look worse.
>>
>all those python (((solutions))) that don't know their way around the standard library
#!/usr/bin/env python3

import itertools

def readlines():
while True:
yield input()

lines = itertools.takewhile(lambda x: x, readlines())
wordlists = map(str.split, lines)
words = itertools.chain.from_iterable(wordlists)
print(*sorted(words, key=len, reverse=True))
>>
>>58745584
you can do using namespace std to import everything in std(you won't have to type the std:: then)
or you can import just what you need
using std::cout;
using std::endl;
etc.
>>
>>58742328
>>58742439
Fixed:
::  /hoon/sorter/gen
/- sole
[. sole]
::
:- %ask
|= *
^- (sole-result (cask *))
=| words/(list cord)
%+ sole-yo leaf+"Enter strings of text. Finish with an empty line."
|-
%+ sole-lo [& %$ ~]
%+ sole-go (more ace (star ;~(less ace next)))
|= line/(list tape)
?. =(line (limo ~[""]))
^$(words (weld (turn line crip) words))
%+ sole-yo :- %leaf
%+ roll (sort words gth)
|= {w/cord s/tape}
:(weld s (trip w) " ")
%- sole-so [%$ ~]


Input:
hoon is too weird
no one will be able to program in it
hoon is ridiculously simple
our documentation and tooling are just immature


Output:
documentation ridiculously immature program tooling simple weird just hoon hoon will able our too are one and it is is to no in be 
>>
>>58743427
looks nice. my code looks like that becuase i followed OP's insturctionsstep by step without trying to reduce the whole procedure into a couple of lines of code.
>>
File: smug.jpg (117KB, 492x492px) Image search: [Google]
smug.jpg
117KB, 492x492px
import Data.List

sortLn :: String -> String
sortLn = unwords . reverse . sortOn length . words
. unlines . takeWhile (not . null) . lines

main :: IO ()
main = interact $ \x -> sortLines x ++ "\n"
>>
>people using Java and not closing their Scanners
>not even using try-with-resources
>>
File: ackchyually.png (19KB, 200x200px) Image search: [Google]
ackchyually.png
19KB, 200x200px
>>58747938
itertools.takewhile(lambda x: x


This looks a little ugly IMO. I don't use lambda functions because every modern thing I've read (e.g. from the core developers) say you should use normal functions because they're easier to read and understand. And as you know, a key goal of Python is the readability and shareability.

e.g., this code >>58737968 is two SLOC longer than yours, but it's nicer, cleaner code.

and this >>58746975 is even cleaner

Just my opinion though, don't let a stranger get you down buddy.
>>
>>58751441
I was in the same train as you, but once you try functional programming, it grows on you.
Thread posts: 138
Thread images: 17


[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y] [Search | Top | Home]

I'm aware that Imgur.com will stop allowing adult images since 15th of May. I'm taking actions to backup as much data as possible.
Read more on this topic here - https://archived.moe/talk/thread/1694/


If you need a post removed click on it's [Report] button and follow the instruction.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com.
If you like this website please support us by donating with Bitcoins at 16mKtbZiwW52BLkibtCr8jUg2KVUMTxVQ5
All trademarks and copyrights on this page are owned by their respective parties.
Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
This is a 4chan archive - all of the content originated from that site.
This means that RandomArchive shows their content, archived.
If you need information for a Poster - contact them.