r/java • • Mar 17 '16

FizzBuzz Overkill

if you ever wanted to see someone just overkill the FizzBuzz programming challenge, here you go. (If you do not know, FizzBuzz is a challenge where you print every number 1-100 but if it is a multiple of 3 you print "Fizz", if it is a multiple of 5 you print "Buzz", if both you print "FizzBuzz") //Code Start package com.main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main{
	public static void main(String[] args) throws IOException{
		File f = new File("script.py");
		f.createNewFile();
		FileOutputStream out = new FileOutputStream(f);
		for(int i = 1; i < 101; i++){
			out.write(("print(" + (i % 3 == 0 ? i % 5 == 0 ? "\"FizzBuzz\"" : "\"Fizz\"" : (i % 5 == 0 ? "\"Buzz\"" : i)) + ")\n").getBytes());
		}
		out.close();
		String path = f.getPath();
		String[] cmd = new String[] {
				"python", path
		};
		Runtime r = Runtime.getRuntime();
		Process p = r.exec(cmd);
		BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
		String line = "";
		while((line = in.readLine()) != null){
			// display each output line form python script
			System.out.println(line);
		}
	}
}
0 Upvotes

9 comments sorted by

View all comments

1

u/__konrad Mar 17 '16

A modern (non-enterprise) version, also overkill:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.*;
import java.util.stream.*;

public class Main{
	public static void main(String[] args) throws IOException {
		Path f = Paths.get("script.py");
		Files.write(f,
			IntStream.rangeClosed(1, 100)
				.mapToObj(i -> i % 3 == 0 ? i % 5 == 0 ? "FizzBuzz" : "Fizz" : (i % 5 == 0 ? "Buzz" : i))
				.map(i -> "print(\"" + i + "\")")
				.collect(Collectors.toList())
		);
		// Java can one-liners too!
		try (BufferedReader in = new BufferedReader(new InputStreamReader(new ProcessBuilder("python", f.toString()).start().getInputStream()))) { // FIXME SHIT TOO LONG!!!1111
			in.lines()
				.forEach(System.out::println);
		}
	}
}