-
-
Save codeeval/1258294 to your computer and use it in GitHub Desktop.
# On CodeEval, test cases are read in from a file which is the first argument to your program | |
# Open the file and read in line by line. Each line represents a different test case | |
# (unless given different instructions in the challenge description) | |
import sys | |
test_cases = open(sys.argv[1], 'r') | |
for test in test_cases: | |
# ignore test if it is an empty line | |
# 'test' represents the test case, do something with it | |
# ... | |
# ... | |
test_cases.close() |
Here is a sample template for Go!
https://gist.github.com/benjic/5824778#file-sample-go
package main
/*
Here is a sample construct that reads a file name supplied as an argument and
allows you, the programmer, to easily work with the supplied parameters. Have Fun!
*/
import (
"bufio"
"os"
//"strconv"
"strings"
)
func main() {
// Open your file using the second command line arguement becuase the binary name is the first.
file, err := os.Open(os.Args[1])
// Anticipate errors
if err == nil {
reader := bufio.NewReader(file)
str, err := reader.ReadString('\n')
for err == nil {
parameters := strings.Split(strings.Trim(s, "\n"), " ")
// Parameters is a slice of strings that represent the space delimited
// items located on each line of the file.
// At this point you would parse your strings if you need a different type ie
// a := strconv.Atoi(params[0])
// In my applicaitons I have used a single funciton to perform the proper action
// and return the anticipated result which is printed ie:
// fmt.Println(a)
str, err = reader.ReadString('\n')
}
} else {
// You can catch file propblems if you want. It is proper... :)
}
}
Tcl input boilerplate:
I'm new to Tcl, so no guarantees it's efficient, but it works!
set file [open [lindex $argv 0] r]
set input [read $file]
close $file
set lines [split $input "\n"]
foreach line $lines {
# work with each $line
}
For @gammaparticle's Java template I also had to:
import java.io.*;
Haskell boilerplate
import System.Environment
import System.Exit
main = getArgs >>= parse >>= putStr . process
parse [] = usage >> exit
parse [f] = readFile f
process = unlines . lines
usage = putStrLn "Usage: foo <file>"
exit = exitWith ExitSuccess
For Perl, you don't really need any "code," but simply use the command line flags on the shebang line.
To read in a file line at a time, preserving line endings: #!perl -n
To enable line end processing too: #!perl -ln
There are other switches too, that will enable, for example, auto-splitting on white space into @F
array.
Updated version of the Ruby boilerplate that handles blank lines for you (to avoid re-typing that part of the code every time):
File.open(ARGV[0]).each_line do |line|
line.strip!
next if line.empty?
# Do something with line
# ...
end
The C boilerplate isn't even compilable. Here's a version of it that can actually be used as a minimal application skeleton:
#include <stdio.h>
int main(int argc, char** argv)
{
FILE* fd;
char line[1024];
fd = fopen(argv[1], "r");
while (fgets(line, sizeof(line), fd))
{
/* Skip empty lines */
if (line[0] == '\n')
continue;
/* Do something with the line */
/* ... */
}
return 0;
}
Error checking is omitted for brevity's sake, which shouldn't be too terrible the code is only being run inside a controlled, well-defined environment.
A simplified Go/Golang template:
package main
import (
"bufio"
"fmt"
"os"
)
func solve(s string) string {
// Replace with actual solution code.
return s
}
func main() {
file, _ := os.Open(os.Args[1])
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(solve(scanner.Text()))
}
}
scanner.Scan
loops over the lines of the file, scanner.Text
returns the scanned line.
I am using following C# code (I was using the normal void main version but in the instructions it was mentioned that all functions should return 0 on exit. )
But it always throw unhandled Exception: System.UnauthorizedAccessException: access to path denied "/stdin.txt" error on submission.
static int Main(string[] args)
{
string filename =args[0]; //reading the name of file from the first argument
StreamReader sw = new StreamReader(new FileStream(filename, FileMode.Open));
string line; // will hold the currently read line
float weight = 0; //Maximum weight the package can hold.
while ((line = sw.ReadLine()) != null) //Iterates until there is no more line to read
{
}
return(0);
}
This isn't really what I use, but it works. Slightly obfuscated C code, because why not?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* rd_line: process one line at a time.
* rd_all: process entire file. (malloc()'d memory, careful.)
*/
#define rd rd_line
#define BUFSZ 1024
int eval(char*,int);
void rd_line(FILE *fp)
{char buf[BUFSZ];while((fgets(buf,sizeof(buf)-1,fp))){
if(buf[0]!='\n' && eval(buf,strlen(buf))){return;}}}
void rd_all(FILE *fp){char *buf;int sz, i=0;fseek(
fp,0L,SEEK_END);sz=ftell(fp);fseek(fp,0L,SEEK_SET);buf=
malloc(sz+1);if(!buf){return;}do{int z=fread(&buf[i],
sizeof(char), sz-i,fp);if(z<0){return;}i+=z;}while(i<sz);
buf[i]=0;eval(buf,sz);free(buf);buf=NULL;}int main(int ac,
char *av[]){FILE *fp;ac<2? exit(printf("invalid usage\n")):
(fp=fopen(av[1],"r"))?rd(fp),fclose(fp),exit(0):perror(av[1]),
exit(1);return(0);}int eval(char *buf, int len)
{
/* code here */
printf("%s", buf);
return 0;
}
Here's another javascript one. I like to the put all the details of the challenge at the top of my file in comments so that I don't have to refer back to the site. I usually chop up the line into an array but not always. I often work away from the computer and think through how I would solve it if I didn't have a computer rather than spend time browsing library functions.
When it comes to testing out helper functions or sub-problems I split a tmux window with vim running in one and node in the other. So far I've done all of them in javascript.
// challenge description
// sample input -
// sample output -
function coolFunction(input) {
'use strict';
var d = input.split(','), output = "";
return output;
}
var fs = require("fs");
fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) {
if (line !== "") { // ignore empty lines
console.log(coolFunction(line));
}
});
Another Go implementation. I can't remember where I found this:
package main
import (
"io/ioutil"
"strings"
"flag"
)
func main() {
flag.Parse();
args := flag.Args()
data, _ := ioutil.ReadFile(args[0])
lines := strings.Split(string(data), "\n")
}
Here's a slightly more idiomatic Python version:
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('filename')
args = parser.parse_args()
with open(args.filename) as f:
for line in f:
...
if __name__ == '__main__':
main()
how to read test cases in fibonnaci (easy)...can anyone give full soln. for reference.
i have a problem i didnot get what these lines of code mean and how to write the c code in code eval how to use the input file????????????
/* Sample code to read in test cases:
include <stdio.h>
int main(int argc, const char * argv[]) {
FILE *file = fopen(argv[1], "r");
char line[1024];
while (fgets(line, 1024, file)) {
// Do something with the line
}
return 0;
} */
I keep getting an Error"Program binary.exe' does not contain a static
Main' method suitable for an entry point" although I haven't changed the given Main function in the online editor,I'm using C#, try for yourself, you will get the same error even if you submit an empty Main function
@iskenxan Got the same problem, did you find a solution?
i'm confused that why you don't use stdin as the input of the program. It's quite commonly used on most online judge platforms.
How to read inputs using javascript?
Bnickel's gist is no longer valid for Objective-C. Use this, and don't forget to declare your variables outside of for loops, otherwise it will throw you loads of gnuC99 errors.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
// read filename from the first argument
NSString* filename = [NSString stringWithCString:argv[1] encoding:NSASCIIStringEncoding];
NSString* content = [NSString stringWithContentsOfFile:filename encoding:NSASCIIStringEncoding error:nil];
NSScanner* scanner = [NSScanner scannerWithString:content];
while (![scanner isAtEnd]) {
NSString* line;
[scanner scanUpToString:@"\n" intoString:&line];
//put your code here
printf("%s\n", [line cStringUsingEncoding:NSASCIIStringEncoding]);
}
[pool release];
return 0;
}
here is another template for Java; this works fine in my local environement, but does not work on codeeval, what is the nme of the file that is being passed as input in codeeval? couldn't find it in templates as well.
public void readByLine(){
try{
FileReader inputFile= new FileReader("input.txt");
BufferedReader buffer = new BufferedReader(inputFile);
String line;
while((line = buffer.readLine())!= null){
convert(line); //method to implement logic
// System.out.println(line); //just in case you need console testing
}
}
buffer.close();
}catch(FileNotFoundException ex){
System.out.println("file not found");
}catch(IOException ex){
System.out.println("there are some issues");
}
}
@amit000 they pass that with args so you can't hardcode the name m8
Here's my working rust version:
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;
fn solve(s: String) {
println!("{}", s)
}
fn main() {
let args: Vec<_> = env::args().collect();
let path = Path::new(&args[1]);
let display = path.display();
let file = match File::open(&path) {
// The `description` method of `io::Error` returns a string that describes the error
Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
Ok(file) => file,
};
let reader = BufReader::new(file);
let lines: Vec<_> = reader.lines().collect();
for l in lines {
solve(l.unwrap());
}
}
I must be getting severely confused about how to run a program with input containing multiple lines. Can someone walk me through how to submit an answer for the challenge linked below? Basically sum of the lines. The actual function that would add up all of the numbers is easy enough, but I do not understand how to make my input be the different numbers from a file with multiple lines.
Working in Javascript.
What do i write as input and output filenames?
Here's some starter code for Fortran. #MakeFortranGreatAgain
program main
implicit none
character(32) :: tests
character(10) :: test
integer :: stat
!Get file name
call get_command_argument(1, arg)
!Open file
open (11,file=trim(arg),action='read')
do
!read in test
read (11,'(a)',iostat=stat) test
if (stat /= 0) exit
if (str /= '') then
.........
! Code goes here
.........
end if
end do
close (11)
end program main
Please show me an example for python3, if you need to pass a parameter to the function, how do I issue the code?
JavaScript code that works in Node.js
Code will read a file passed as argument at command line.
It will display the result of the difference between the numbers given at every line, as shown below.
Test.txt
20 6
30 53
22 44
56 9
Output
14
-23
-22
47