Because I know that half of /prog/ can't program, let's make simple ones!
---------------------- MySavings.java ----------------------
/**
* @(#)MySavings.java
*
* MySavings application
*
* @author Tim H
* @version 1.00 2010/5/7
*/
import java.util.Scanner;
public class MySavings {
public static void printInterface() {
System.out.print(
"1. Show total in bank.\n" +
"2. Add a penny.\n" +
"3. Add a nickel.\n" +
"4. Add a dime.\n" +
"5. Add a quarter.\n" +
"6. Take money of out bank.\n" +
"Enter 0 to quit.\n" +
"Enter your choice: "
);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int choice = 1;
int moneyChoice = 0;
double amount = 0;
switch(choice){
case 0: System.out.println("(c)Tim H 2010\nHave a nice day!"); break;
case 1: System.out.println("Your current total is: " + bank.GetTotal()); break;
case 2:
case 3:
case 4:
case 5: moneyChoice = choice - 2; bank.AddMoney(moneyChoice); break;
case 6:
System.out.print("Enter the amount you wish to withdraw: ");
amount = input.nextDouble();
bank.SubtractTotal(amount);
break;
default:
System.out.println("Please enter a choice between 1-6!");
break;
}
public void AddMoney(int choice){
switch (choice) {
case 0:
total += 0.01;
System.out.println("One penny added to total!\nYour total is now: " + total);
break;
case 1:
total += 0.05;
System.out.println("One nickel added to total!\nYour total is now: " + total);
break;
case 2:
total += 0.10;
System.out.println("One dime added to total!\nYour total is now: " + total);
break;
case 3:
total += 0.25;
System.out.println("One quarter added to total!\nYour total is now: " + total);
break;
}
}
public double GetTotal(){
return total;
}
public void SubtractTotal(double amount){
total -= amount;
System.out.println(amount + " has been subtracted from your total!\nYour total is now: " + total);
}
}
}
}
Name:
Anonymous2010-05-08 4:37
My attempt at a Game of Life simulator for Python 2.x #!/usr/bin/env python
# -*- coding: utf-8 -*-
#Game of Life
#Written by Faggot, 29 April 2010
#>> Modules
import sys
import time
import random
#> Constants
_boardsize_x = 80#40 # Cells Across
_boardsize_y = 40#20 # Cells Vertically
_populate_chance = 0.12#0.135 # 0-1 Chance of Cell Population
#>>
#>> GoL Class
#>> Contains all the boards, functions, etc
#>>
class golBoard:
#> Board Creation
def __init__(self):
#Board-Current
self.boardCurr = [[0 for board_x in range(_boardsize_x)]
for board_y in range(_boardsize_y)]
#Board-Next
self.boardNext = [[0 for board_x in range(_boardsize_x)]
for board_y in range(_boardsize_y)]
#> Board Population - Random
def populate(self):
for board_y in range(_boardsize_y):
for board_x in range(_boardsize_x):
if random.random() <= _populate_chance:
self.boardCurr[board_y][board_x] = 1
#> Board Display
def display(self):
for board_y in range(_boardsize_y):
for board_x in range(_boardsize_x):
if self.boardCurr[board_y][board_x] == 1:
sys.stdout.write('\xe2') #Unicode Block - u2588
else:
sys.stdout.write(' ') #write() is required because
#print inserts space after chars
print '\n',
print '\n',
#> Board Neighbors
def _neighbors(self, board_y, board_x):
neighbors = 0
for y in range(-1, 2):
for x in range(-1, 2):
#> Error Checking
# The -1 at edges is so that peices don't
# stick to the edges of the board,
# I haven't properly tested the edge neighbor
# calculations, so I'm just doing this to be safe
if board_x+x == -1:
neighbors -= 1
elif board_y+y == -1:
neighbors -= 1
elif board_x+x >= _boardsize_x:
neighbors -= 1
elif board_y+y >= _boardsize_y:
neighbors -= 1
#Correct Values!
else:
if self.boardCurr[board_y+y][board_x+x] == 1:
if x == 0 and y == 0:
pass #So it doesn't count itself
else:
neighbors += 1
return neighbors
#> Board Updating
def update(self):
for board_y in range(_boardsize_y):
for board_x in range(_boardsize_x):
#Dead, Underpopulation
if self._neighbors(board_y,board_x) < 2:
self.boardNext[board_y][board_x] = 0
#>>
#>> GoL Program - Display, Iterate, Display, Iter...
#>> The usual method
#>>
while True: #Board-Spawner
#boardStore = [[0 for board_x in range(_boardsize_x)]
# for board_y in range(_boardsize_y)]
gol = golBoard()
gol.populate()
gol.update() # To kill all the extras that spawn
# when a random board is created
#while True:
for num in range(51):
print "Game of Life, Iteration", num
print _boardsize_x, "by", _boardsize_y, "board"
gol.display()
#>>
#>> GoL Program - Iterate to fin, Display
#>> The batch-calculation method
#>>
if False: #Poor-Man's Block Comment
print "\n\n\n"
gol = golBoard()
gol.populate()
i = 1
for num in range(49):
gol.update()
i += 1
print "Game of Life, Iteration", i
print _boardsize_x, "by", _boardsize_y, "board"
gol.display()
else:
node_temp = self.root
while True:
if data == node_temp.data:
print(data, "- Node Already Exists")
break
elif data < node_temp.data:
if node_temp.linkL == None:
node_temp.linkL = node(data)
break
else:
node_temp = node_temp.linkL
elif data > node_temp.data:
if node_temp.linkR == None:
node_temp.linkR = node(data)
break
else:
node_temp = node_temp.linkR
#>
#> Number Tree
#> String Trees work as well
#>
import random
nums = tree()
for i in range(10):
nums.add(random.randint(4, 30))
print('\n')
# Ordered Node Listing
for num in nums.tree(nums.root):
print(num)
print('\n')
# Tree Structure Listing
for num in nums.tree(nums.root, False):
print(num)
print('\n')
Name:
Anonymous2010-05-08 12:30
>>1
I realize you are one of those who "can't program", please find attached a corrected version of your program. In future, please refrain from posting on /prog/ until you have achieved satori.
import java.util.*;
public class Savings {
public static void main(String[] args) {
final Scanner sc = new Scanner(System.in);
Account account = new Account();
SortedMap<Integer, AccountChoice> choices = new TreeMap<Integer, AccountChoice>();
choices.put(0, new AccountChoice() {
public String toString() { return "Close account and exit."; }
public void invoke(Account ac) { System.exit(0); }
});
choices.put(1, new AccountChoice() {
public String toString() { return "Show balance."; }
public void invoke(Account ac) {
System.out.println(new java.text.DecimalFormat("#0.00").format(ac.getBalance()/100.0));
}
});
choices.put(2, new AccountChoice() {
public String toString() { return "Add a "+ Currency.PENNY + "."; }
public void invoke(Account ac) {
try { ac.deposit(Currency.PENNY.toCents()); }
catch(IllegalArgumentException e) { System.out.println(e.getMessage()); }
}
});
choices.put(3, new AccountChoice() {
public String toString() { return "Add a "+ Currency.NICKEL + "."; }
public void invoke(Account ac) {
try { ac.deposit(Currency.NICKEL.toCents()); }
catch(IllegalArgumentException e) { System.out.println(e.getMessage()); }
}
});
choices.put(4, new AccountChoice() {
public String toString() { return "Add a "+ Currency.DIME + "."; }
public void invoke(Account ac) {
try { ac.deposit(Currency.DIME.toCents()); }
catch(IllegalArgumentException e) { System.out.println(e.getMessage()); }
}
});
choices.put(5, new AccountChoice() {
public String toString() { return "Add a "+ Currency.QUARTER + "."; }
public void invoke(Account ac) {
try { ac.deposit(Currency.QUARTER.toCents()); }
catch(IllegalArgumentException e) { System.out.println(e.getMessage()); }
}
});
choices.put(6, new AccountChoice() {
public String toString() { return "Make a withdrawl."; }
public void invoke(Account ac) {
System.out.print("Enter the amount you wish to withdraw (cents): ");
int amount = sc.nextInt();
try { ac.withdraw(amount); System.out.println("Withdrawl successful."); }
catch(Exception e) { System.out.println(e.getMessage()); }
}
});
while(true) {
for(Map.Entry<Integer, AccountChoice> choice : choices.entrySet())
System.out.println(choice.getKey() + ". " + choice.getValue());
System.out.print("Enter your choice: ");
int option = sc.nextInt();
if(!choices.containsKey(option)) System.out.println("Please enter a valid choice.");
else choices.get(option).invoke(account);
}
}
}
abstract class AccountChoice {
public abstract void invoke(Account ac);
}
enum Currency {
PENNY(1, "penny"),
NICKEL(5, "nickel"),
DIME(10, "dime"),
QUARTER(25, "quarter");
private long cents;
private String name;
private Currency(long cents, String name) {
this.cents = cents;
this.name = name;
}
public long toCents() {
return cents;
}
public String toString() {
return name;
}
}
class Account {
private long savings;
public Account() {
savings = 0;
}
public void deposit(long cents) {
if(cents < 0) throw new IllegalArgumentException("Cannot deposit negative cents.");
savings += cents;
}
public long getBalance() {
return savings;
}
public void withdraw(long cents) throws InsufficientFundsException {
if(cents > savings) throw new InsufficientFundsException("Insufficient funds for withdrawl.");
if(cents < 0) throw new IllegalArgumentException("Cannot withdraw negative cents.");
savings -= cents;
}
}
class InsufficientFundsException extends IllegalArgumentException {
public InsufficientFundsException(String message) {
super(message);
}
}
def _print(a): print a
coins = "penny", "nickel", "dime", "quarter"
prntrfc = lambda: map(_print, \
map(lambda (i, j): str(i) + j, \
enumerate(["", ". Show total in bank."] + \
map(lambda n: ". Add a %s." % n, coins) +\
[". Take money of out bank. [sic]"]))[1:])
class Pig():
def __init__(s):
s.t = 100.
def __add__(s, n):
a = .01, .05, .1, .25
s.t += a[n]
print "One %s added to total!\nYour total is now:" % coins[n], s.t
def __sub__(s, n):
s.t -= n
print n, "has been subtracted from your total!\nYour total is now:", s.t
def __str__(s):
return str(s.t)
pig = Pig()
while True:
p = lambda n: pig + n
cl = (lambda: _print("(c) Xarn 2012\nHave a nice day!"),
lambda: _print("Your current total is: " + str(pig)),
lambda: p(0),
lambda: p(1),
lambda: p(2),
lambda: p(3),
lambda: pig - float(raw_input("Enter the amount you wish to withdr" +\
"aw: ")))
prntrfc()
try:
cl[int(raw_input(""))]()
except IndexError:
print "Please enter a choice between 1-6!"
Name:
Anonymous2010-05-08 21:27
>>10 Your post has been reported to Herr Guido's Personal Guard. You are strongly advised to cease all functional FIOC activity.
Since we're writing toy programs, I'll just look up some toy code that I wrote last year when I was learning CL:
(defun seq (n m &optional (k 1))
(loop for i from n to m by k collect i))
(defun prime-sieve (n)
(let ((primes (seq 2 n)))
(loop for i from 2 to n
do (set-differencef primes (rest (seq i n i))))
(sort primes #'<)))
Name:
Anonymous2010-05-09 5:50
primes = 2 : 3 : 5 : 7 : [k + r | k <- [0, 30..], r <- [11, 13, 17, 19, 23, 29, 31, 37], primeTest (k + r)]
where primeTest n = all ((0 /=) . mod n) . takeWhile ((n >=) . join (*)) $ drop 3 primes
Name:
Anonymous2010-05-09 6:12
toy programs? look out, here comes some FOIC!
this code is actually faster than the factorial function in the math module (which is written in c!)... proof that guido can't code for shit. from itertools import takewhile, dropwhile
def eratosthenes():
D = {}
q = 2
while 1:
if q not in D:
yield q
D[q*q] = [q]
else:
for p in D[q]:
D.setdefault(p+q,[]).append(p)
del D[q]
q += 1
def bitcount(n):
r = 0;
while n > 0:
r += n & 1
n >>=1
return r
def take(n, g):
for i in range(n): yield g.next()
def swing(n):
primes = list(takewhile(lambda x: x <= n, eratosthenes()))
smalloddswing = [1,1,1,3,3,15,5,35,35,315,63,693,231,3003,429,6435,6435,109395,12155,230945,46189,969969,88179,2028117,676039,16900975,1300075,35102025,5014575,145422675,9694845,300540195,300540195]
if n < 33: return smalloddswing[n]
primelist = []
primesa = takewhile(lambda x: x * x <= n, dropwhile(lambda x: x < 3, primes))
primesb = takewhile(lambda x: x * 3 <= n, dropwhile(lambda x: x * x <= n, primes))
for prime in primesa:
q = n // prime
p = 1
while q > 0:
if q & 1 == 1: p *= prime
q //= prime
if p > 1: primelist.append(p)
return reduce(lambda x, y: x * y, list(takewhile(lambda x: x <= n, dropwhile(lambda x: x << 1 <= n, primes))) + primelist + filter(lambda x: n // x & 1 == 1, primesb), 1)
def recfactorial(n):
if n < 2: return 1
return recfactorial(n >> 1) ** 2 * swing(n)
def factorial(x):
if x < 0: raise ValueError('factorial() not defined for negative values')
n = int(x)
if n != x: raise ValueError('factorial() only accepts integral values')
if n < 20: return reduce(lambda x, y: x * y, range(2,n + 1), 1)
return recfactorial(n) << (n - bitcount(n))
Name:
Anonymous2010-05-09 9:53
I think we should fork Python, throw out the entire standard library, get rid of the idiotic GIL, fix lambda, and add shittons of functional stuff to it. Anyone with me to do this?
Name:
Anonymous2010-05-09 9:54
>>28
Incidentally, that was already my plan for the summer (assuming I don't find work).
>>35
But the nice part of it is that the error increases in a beautiful exponential curve, so you can get a good estimate of how big it's going to be and adjust the result based on that.
The only problem is knowing the sign of the error, though that problem apparently goes away when the number you're taking the factorial of is big enough. Here's a graph of the value of the approximate function minus the value of the actual factorial:
copy this code and save it with the .py extention in the same place you saved the ball image and run it (I recommend using the pyscripter IDE over IDLE)
#Another Version of the Sieve of Eratosthenes
l, n = [], 100
for i in range(n): l.append(True)
i = 2
while i * i <= n:
if l[i-1] == True:
#if not i%2:
for j in range(i*i, n+1, i): l[j-1] = False
i += 1
i = 2
while i <= n:
if l[i-1] == True : print(i, " ", end = "")
i += 1
Name:
VIPPER2010-11-18 16:37
#!/bin/perl
my $JEWS = "";
print $JEWS .= "JEWS " while 1;
print "this message will never be printed, prepare your anus for VIPPER\n";
There are many brands of <a href="http://www.barbourjackets-uk.org/"><strong>barbour fusilier</strong></a> in the market today. Each of the brand promises to bring out something new to the customers.
10 LET A=0
20 LET A=A+1
30 IF A MOD 15=0 THEN 80
40 IF A MOD 3=0 THEN 100
50 IF A MOD 5=0 THEN 120
60 GOTO 140
80 PRINT"FIZZBUZZ"
90 GOTO 20
100 PRINT"FIZZ"
110 GOTO 20
120 PRINT"BUZZ"
130 IF A<100 THEN 20
131 SLEEP
132 END
140 PRINT A
150 GOTO 20
Name:
Anonymous2011-12-02 23:26
<?function f($x){return(!$x)?1:$x*f($x-1);}?>
Name:
Anonymous2011-12-03 7:56
#t ; Enjoy a Scheme/Python quine
'''() ;
(print "Hello from Scheme!")
; '''
(); print "Hello from Python!"