CodeChef is a non-commercial competitive programming community
Login
Username (New User? Signup) Password (Forgot Password?)
Signup
Login or
Signup with
Connect
Note
  • Publicize your achievements on your Facebook Wall.
  • Challenge your friends or ask them for help.

Site Navigation

  • PRACTICE
    • Easy
    • Medium
    • Hard
    • Challenge
    • Peer
  • COMPETE
    • All Contests
    • June Long 2012
    • May Cook-Off
    • May Long 2012
  • DISCUSS
    • Forums
    • Blog
    • Wiki
    • Facebook
    • Twitter
  • COMMUNITY
    • CodeChef Meetups
    • Campus Chapters
    • Host your Contest
    • User Groups
    • CodeChef TechTalks
    • All Educational Initiatives
  • HELP
    • Frequently Asked Questions
    • FAQ for problem setters
    • Problem Setting
    • Tutorials
    • Long Contest Ranks
    • Short Contest Ranks
    • Event Calendar
  • ABOUT
    • About CodeChef
    • Team CodeChef
    • Press Room
    • CodeChef Financials
    • CodeChef Sponsorships
    • CEO's Corner
    • Contact Us
    • About Directi
Home » Wiki » Sample Solutions

Sample Solutions

 

 

Table of Contents 
  1. Submitting a Solution :
  2. C++
  3. C
  4. Pascal
  5. Java
  6. Jar
  7. Nice
  8. Python
  9. Lisp
  10. Scheme
  11. OCaml
  12. Haskell
  13. Clips
  14. Prolog
  15. C#
  16. Brainf*ck
  17. Perl
  18. Ruby
  19. Pike
  20. PHP
  21. Intercal
  22. NASM
  23. Ada95
  24. Bash
  25. Smalltalk
  26. Fortran
  27. Icon
  28. Erlang

 

Submitting a Solution :


To submit a solution choose problem from list of problems and press button 'Submit' near the top right corner of the problem page. You can submit multiple solutions to each problem. Score for the problem is equal to the score of the best submitted solution.

To see the Statistic for problem choose problem from list of problems and press button 'All submissions' at the top of the problem description. To view the status, hover over the check box, cross or warning icon in the result column.

Solutions in different languages need to be structured in particular ways. For example, the public class in Java needs to be named as Main. Here are a few sample solutions in different languages for a very elementary problem statement.

Solutions to TEST are given below in 26 programming languages. Feel free to respond with questions/comments/suggestions.

 

C++


[code]

#include <iostream>

int main(void) {
char c, d=10;
while(std::cin.get(c) && (c!='2' || d!='4') && std::cout.put(d))
d=c;
}
[/code]

C


[code]


#include <stdio.h>

int main(void) {
int x;
for(; scanf("%d",&x) > 0 && x != 42; printf("%d\n", x));
return 0;
}
[/code]

Pascal


[code]


program test;
var x: integer;
begin
repeat
readln(x);
if x<>42 then writeln(x);
until x=42
end.
[/code]

Java


[code]


public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
String s;
while (!(s=r.readLine()).startsWith("42")) System.out.println(s);
}
}
[/code]

Jar


  • Make a file main-class.txt. From the Bash prompt: echo -e 'Main-Class: Main\r' > main-class.txt
  • Copy Main.class and any other necessary classes and resources into a subdirectory of your work directory called jarstuff: mkdir jarstuff; cp Main.class resources.zip jarstuff
  • Create the executable jar: jar cfm MySolution.jar main-class.txt -C jarstuff . Make sure to include that final dot!

Nice


[code]


void main (String[] args)
{
java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
String s;
while (!(s=notNull(r.readLine())).startsWith("42")) System.out.println(s);
}
[/code]

Python


[code]


k=raw_input()
while int(k)!=42:
print k
k=raw_input()
[/code]

Lisp


[code]


(loop for l = (read-line)
for n = (parse-integer l)
until (= n 42) do (format t "~D~%" n))
[/code]

Scheme


[code]


(do ((i (read) (read)))
((eq? i 42) '())
(begin
(display i)
(newline)))
[/code]

OCaml


[code]


while true do
let n = read_int () in
if n=42 then exit 0 else print_int n; print_newline ()
done
[/code]

Haskell


[code]


main = interact f
where f = unlines . takeWhile (/="42") . words
[/code]

 

Clips


[code]


(defrule readin
?f<-(initial-fact)
=>
(retract ?f)
(assert (number (read)))
)

(defrule writeout
?f<-(number ?n)(test (<> ?n 42))
=>
(retract ?f)
(printout t ?n crlf)
(assert (initial-fact))
)
[/code]

Prolog


[code]


program :- get_char(X),get_char(Y),check(X,Y).
check('4','2'):-!.
check(X,Y):-write(X),get_char(Z),check(Y,Z).
[/code]

 

C#


[code]


using System;
public class Test
{
public static void Main()
{
int n;
while ((n = int.Parse(Console.ReadLine()))!=42)
Console.WriteLine(n);
}
}
[/code]

 

Brainf*ck


[code]


+[>>----------
[++++++++++<,----------]
>--------------------------------------------------
>----------------------------------------------------
>

[
<+++++++++++++++++++++++++++++++++++++++++++++++ ++ +++
<+++++++++++++++++++++++++++++++++++++++++++++++ ++ +
[>]<
[.<]++++++++++.---------->
[>]>>
]<

[++++++++++++++++++++++++++++++++++++++++++++++++++ ++
<+++++++++++++++++++++++++++++++++++++++++++++++ ++ +
[>]<
[.<]++++++++++.---------->
[>]>
]<

[>+++++++++++++++++++++++++++++++++++++++++++++++ ++ +++
<+++++++++++++++++++++++++++++++++++++++++++++++ ++ +
[>]<
[.<]++++++++++.---------->
[>]
]<

]

[/code]

Perl


[code]

print while($_=<>)!=42

[/code]

Ruby


[code]


print while gets != "42\n"

[/code]

Pike


[code]


int main() {
while (sscanf(Stdio.stdin->gets(), "%d", int n), n!=42 && write(n+"\n"));
return 0;
}
[/code]

PHP


[code]


<?php
while (true) {
$input = fgets(STDIN, 3);
if ($input == 42) {
break;
} else {
echo $input;
}
}
?>
[/code]

 

Intercal


[code]


PLEASE DO ,1 <- #1
PLEASE DO .4 <- #0
PLEASE DO .5 <- #0
PLEASE DO .99 <- #0
DO COME FROM (30)
DO COME FROM (31)
DO WRITE IN ,1
DO .1 <- ,1SUB#1
DO .2 <- .4
DO (1000) NEXT
DO .4 <- .3~#255
DO (10) NEXT
(42) DO .1 <- .1
(20) DO .42 <- "&'&.4~#26'$#1"
PLEASE RESUME "?.42$#1"~#3
(10) DO (20) NEXT
DO FORGET #1
PLEASE COME FROM (42)
PLEASE STASH .1+.2+.3
DO .1 <- .4
DO .2 <- #50
DO (1010) NEXT
DO (100) NEXT
PLEASE STASH .1+.2+.3
DO .1 <- .99
DO .2 <- #52
DO (1010) NEXT
DO (101) NEXT
PLEASE GIVE UP
(201) DO .3 <- '.3~.3'~#1
PLEASE RESUME "?.3$#2"~#3
(101) DO (201) NEXT
DO FORGET #1
(32) PLEASE RETRIEVE .1+.2+.3
(200) DO .3 <- '.3~.3'~#1
PLEASE RESUME "?.3$#2"~#3
(100) DO (200) NEXT
DO FORGET #1
DO COME FROM (32)
PLEASE RETRIEVE .1+.2+.3
DO (102) NEXT
(31) DO .99 <- .4
(202) DO .98 <- '.99~.99'~#1
PLEASE RESUME "?.98$#2"~#3
(102) DO (202) NEXT
DO FORGET #1
DO .3 <- !99~#15'$!99~#240'
DO .3 <- !3~#15'$!3~#240'
DO .2 <- !3~#15'$!3~#240'
DO .1 <- .5
DO (1010) NEXT
DO .5 <- .2
DO ,1SUB#1 <- .3
PLEASE READ OUT ,1
(30) DO .99 <- .4
[/code]

NASM


[code]


global _start
section .data
buffer dw 0h
section .text
_start:
mov ecx, buffer
mov edx, 02h
call read
mov cx, word [buffer]
cmp cx, 3234h
je exit
cmp ch, 0ah
je one_dig
jmp two_dig
one_dig:
mov ecx, buffer
mov edx, 02h
call write
jmp _start
two_dig:
mov ecx, buffer
mov edx, 02h
call write
mov edx, 01h
mov ecx, buffer
call read ; read the 0ah
mov ecx, buffer
call write ; write the 0ah
jmp _start
exit:
mov eax, 01h ; exit()
xor ebx, ebx ; errno
int 80h
read:
mov eax, 03h ; read()
mov ebx, 00h ; stdin
int 80h
ret
write:
mov eax, 04h ; write()
mov ebx, 01h ; stdout
int 80h
ret
[/code]

 

Ada95


[code]


with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure test is
x : integer;
begin
loop
get(x);
if x/=42
then
put(x);
new_line(1);
else
exit;
end if;
end loop;
end test;
[/code]

 

Bash


[code]


while read a; do
if [ $a -eq 42 ]; then
exit
else
echo $a
fi
done
[/code]

Smalltalk


[code]

|c number|
[
number:=0.
[ (c := stdin next) asciiValue ~= 10 ]
whileTrue:
[number := (number * 10) + (c asciiValue) - 48.].
number ~= 42
]
whileTrue:
[Transcript show: number printString; cr.]
!
[/code]

 

Fortran


[code]


program TEST
integer ans
do
read (*,*) ans
if (ans.eq.42) stop
write (*,*) ans
enddo
stop
end
[/code]

 

Icon


[code]


procedure main ()
while (l := read()) ~= 42 do
write(l);
end

[/code]

 

Erlang


[code]

-module(tested).
-export([main/0]).

main() ->
loop().
loop() ->
case io:fread( "","~d" ) of
eof ->
true;
{ok, X} ->
[Y] = X,
if
Y == 42 ->
true;
true ->
io:fwrite( "~B\n",X ),
loop()
end
end.

[/code]


Comments

  • Login or Register to post a comment.

There is an error in python

hrishikesh911 @ 2 Feb 2010 12:35 PM

There is an error in python code. It does not work.

There should be an indentation block

Why Codechef don't support

oronno @ 25 Jun 2010 11:00 AM

Why Codechef don't support "BASIC" language.

what about javascript ?

Danko @ 2 Jul 2010 11:31 PM

what about javascript ?

Ok, this one works

Danko @ 2 Jul 2010 11:49 PM

Ok, this one works (JS)

 

importPackage(java.io);

importPackage(java.lang);

 

S = new BufferedReader( new InputStreamReader(System['in']) );

s = true;

 

while (s){

s = S.readLine();

if (s==42 || s==null) break;

System.out.println(s);

}

can we use math.h in a c

NRNishant @ 4 Aug 2010 12:23 AM

can we use math.h in a c program  ????

Dan, following may work for

kumarldh @ 2 Sep 2010 06:17 PM

Dan, following may work for JS javascript: while( (x = prompt('Enter value'))!=42){    alert(x);}

Does Code chef use an input

saik @ 12 Sep 2010 01:18 AM

Does Code chef use an input and output file for testing this program as mentioned in the FAQ section?

I am not able to understand this - When does codechef use the input of type "test.exe < in.txt > out.txt" to test the program and when does statements such as "std::cin.get(c)" [incase of C++ programming] is used.


Please explain asap, as i am not able to proceed in submitting any other solutions.

Thanks in advance.


Does Code chef use an input

saik @ 12 Sep 2010 01:18 AM

Does Code chef use an input and output file for testing this program as mentioned in the FAQ section?

I am not able to understand this - When does codechef use the input of type "test.exe < in.txt > out.txt" to test the program and when does statements such as "std::cin.get(c)" [incase of C++ programming] is used.


Please explain asap, as i am not able to proceed in submitting any other solutions.

Thanks in advance.


Does Code chef use an input

saik @ 12 Sep 2010 01:19 AM

Does Code chef use an input and output file for testing this program as mentioned in the FAQ section?

I am not able to understand this - When does codechef use the input of type "test.exe < in.txt > out.txt" to test the program and when does statements such as "std::cin.get(c)" [incase of C++ programming] is used.


Please explain asap, as i am not able to proceed in submitting any other solutions.

Thanks in advance.


  Does Code chef use an

saik @ 12 Sep 2010 01:22 AM

 

Does Code chef use an input and output file for testing this program as mentioned in the FAQ section?

I am not able to understand this - When does codechef use the input of type "test.exe < in.txt > out.txt" to test the program and when does statements such as "std::cin.get(c)" [incase of C++ programming] is used.


Please explain asap, as i am not able to proceed in submitting any other solutions.

Thanks in advance.


 

  Hi, Sorry, facing some

saik @ 12 Sep 2010 01:24 AM

 

Hi,

Sorry, facing some issue with posting comments.

Does Code chef use an input and output file for testing this program as mentioned in the FAQ section?

I am not able to understand this - When does codechef use the input of type "test.exe < in.txt > out.txt" to test the program and when does statements such as "std::cin.get(c)" [incase of C++ programming] is used.


Please explain asap, as i am not able to proceed in submitting any other solutions.

Thanks in advance.


Python

rawkus @ 13 Nov 2010 10:27 PM

Python 3.1

 

life_the_universe_and_everything = '42'

while True:

a = input('What is your number?')

if a == life_the_universe_and_everything:

break

print(a)

#include<iostream>#include<st

fantasy @ 15 Apr 2011 08:34 PM

#include<iostream>
#include<string>
#include<conio.h>
using namespace std;
int main()
{
string str,s1,s2;
int len,t;
cout<<"enter ur string";
getline(cin,str);
len=str.length();
t=len/2;
if(len<2)
{
cout<<"not valid";
}
if((len%2)==0)
{
s1 = str.substr (0,t);
s2 = str.substr (t,len);
}
cout<<"n";
string::reverse_iterator r1,r2;
for ( r1=s1.rbegin() ; r1 < s1.rend(); r1++ )
{
cout<<*r1;

}
for ( r2=s2.rbegin() ; r2 < s2.rend(); r2++ )
{
cout<<*r2;

}
getch();
return 0;
}

how to take an integer as a

pikku @ 13 May 2011 10:08 PM

how to take an integer as a input in prolog?

the most of codes given here

gundeep @ 26 Jun 2011 08:42 AM
the most of codes given here prints the number as soon as it is entered. Is this what we are siupposed to do? it gives the output 1 1 2 2 88 88 42 whereas it should have given Sample Input: 1 2 88 42 99 Sample Output: 1 2 88 Dont we need to use an aray????

what about the limitation on

sheshnath @ 5 Aug 2011 12:41 AM
what about the limitation on the value of n(i.e.<100)?

the c++ solution outputs 42

widdoh @ 10 Sep 2011 05:24 PM
the c++ solution outputs 42 before terminating (which is not the case in the sample ii/i provided) unless you have short boolean evaluation turned on!

how do I submit code in ruby

nitishupreti @ 28 Sep 2011 08:24 PM
how do I submit code in ruby with code in a class?

I agree with gundeep... we

shivam18 @ 30 Sep 2011 07:52 PM
I agree with gundeep... we need an array here.

I think it is executed as

amriteshanand @ 14 Oct 2011 11:32 AM
I think it is executed as "./a.out < input.txt > output.txt" on terminal. Thus standard inputs are not stored.While using compilers and making "test.exe" don't consider the inputs displayed.

[code] char c,

doomgiver @ 18 Oct 2011 11:46 AM
[code] char c, d=10; while(std::cin.get(c) && (c!='2' || d!='4') && std::cout.put(d)) d=c; [/code] what do these lines do? i understand that this is a while loop which takes input, checks for 42(somehow) and outputs the result, but how does it do that?

in fact, i think that all it

doomgiver @ 18 Oct 2011 12:49 PM
in fact, i think that all it is doing is to check for 2 or 4, can someone tell me why? and why is it not checking for 42, as the problem requires?

forget my last comments. i

doomgiver @ 18 Oct 2011 12:52 PM
forget my last comments. i found out how it works.

Is the C++ code correct? What

soundblaster @ 16 Nov 2011 12:23 PM
Is the C++ code correct? What happens if I feed a string that has 42 in it, it e.g '11142111'. I'm think it will fail.

I thought you had to follow

idontmakesense @ 8 Jan 2012 05:52 PM
I thought you had to follow the sample strictly, that is, have all your inputs first and only then the output. C++ code does one input one output.

ruby is always awesome!!!

anandveeramani @ 11 Feb 2012 10:48 PM
ruby is always awesome!!!
CodeChef is a non-commercial competitive programming community
  • About CodeChef
  • About Directi
  • CEO's Corner
  • C-Programming
  • Programming Languages
  • Contact Us
© 2009 Directi Group. All Rights Reserved. CodeChef uses SPOJ © by Sphere Research Labs
In order to report copyright violations of any kind, send in an email to copyright@codechef.com
CodeChef a product of Directi
The time now is:
CodeChef - A Platform for Aspiring Programmers

CodeChef was created as a platform to help programmers make it big in the world of algorithms, computer programming and programming contests. At CodeChef we work hard to revive the geek in you by hosting a programming contest at the start of the month and another smaller programming challenge in the middle of the month. We also aim to have training sessions and discussions related to algorithms, binary search, technicalities like array size and the likes. Apart from providing a platform for programming competitions, CodeChef also has various algorithm tutorials and forum discussions to help those who are new to the world of computer programming.

Practice Section - A Place to hone your 'Computer Programming Skills'

Try your hand at one of our many practice problems and submit your solution in a language of your choice. Our programming contest judge accepts solutions in over 35+ programming languages. Preparing for coding contests were never this much fun! Receive points, and move up through the CodeChef ranks. Use our practice section to better prepare yourself for the multiple programming challenges that take place through-out the month on CodeChef.

Compete - Monthly Programming Contests and Cook-offs

Here is where you can show off your computer programming skills. Take part in our 10 day long monthly coding contest and the shorter format Cook-off coding contest. Put yourself up for recognition and win great prizes. Our programming contests have prizes worth up to Rs.20,000 and $700lots more CodeChef goodies up for grabs.

Discuss

Are you new to computer programming? Do you need help with algorithms? Then be a part of CodeChef's Forums and interact with all our programmers - they love helping out other programmers and sharing their ideas. Have discussions around binary search, array size, branch-and-bound, Dijkstra's algorithm, Encryption algorithm and more by visiting the CodeChef Forums and Wiki section.

CodeChef Community

As part of our Educational initiative, we give institutes the opportunity to associate with CodeChef in the form of Campus Chapters. Hosting online programming competitions is not the only feature on CodeChef. You can also host a coding contest for your institute on CodeChef, organize an algorithm event and be a guest author on our blog.

Go For Gold

The Go for Gold Initiative was launched about a year after CodeChef was incepted, to help prepare Indian students for the ACM ICPC World Finals competition. In the run up to the ACM ICPC competition, the Go for Gold initiative uses CodeChef as a platform to train students for the ACM ICPC competition via multiple warm up contests. As an added incentive the Go for Gold initiative is also offering over Rs.8 lacs to the Indian team that beats the 29th position at the ACM ICPC world finals. Find out more about the Go for Gold and the ACM ICPC competition here.

Domain Name Registration, Web hosting, and Website Design provided by BigRock.com