attributes = ['a', 'b', 'c']
values = [1, 2, 3]
for attr, val in zip(attributes, values):
setattr(obj, attr, val)
CSS (без ввода):
li {
counter-increment: a;
}
li:after {
content: counter(a);
}
li:nth-child(3n) { /* replace 3 with 2nd input ("b" in "a % b") */
counter-reset: a;
counter-increment: none;
}
Сопутствующий HTML:
Вывод:
Вывод http://img155.imageshack.us/img155/4643/modd.png
Это не работает в IE ( Сюрприз Сюрприз!).
Я выиграл?
printf "Input of first number:"
let x = stdin.ReadLine() |> int
printf "Input of second number:"
let y = stdin.ReadLine() |> int
let mutable z = x
while z >= 0 do
z <- z - y
// whoops, overshot
z <- z + y
// I'm not drunk, really
printfn "Result:%d" z
import java.util.*;enum M{M;M(){Scanner s=new Scanner(System.in);int a=s.nextInt(),b=s.nextInt();System.out.println(a-a/b*b);}}
Обратите внимание, что программа действительно работает, но также выдает исключение
в потоке «main» java.lang.NoSuchMethodError: main
после ввода вводится и после вывода выводится.
Предполагая, что s [0]
и s [1]
равны int
. Не уверен, что это чего-нибудь стоит, но было немного весело.
Обратите внимание, что это не пострадает от эффекта цикла (большие числа), но будет работать только с целыми числами. Кроме того, это решение одинаково быстро, независимо от того, насколько велики числа. Большой процент предоставленных ответов приведет к созданию огромного рекурсивного стека или займет бесконечно много времени, если вы скажете большое число и маленький делитель.
public class M
{
public static void main(String [] s)
{
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
System.out.println(a-a/b*b);
}
}
Чтение входных данных, вероятно, можно было бы еще сократить.
($a,$b)=@ARGV;print$a-$b*int$a/$b
$ perl -e "($a,$b)=@ARGV;print$a-$b*int$a/$b" 2457 766
159
a-b*(0|a/b)
Предполагается, что входные целые числа содержат переменные a
и b
:
a = 2;
b = 2;
alert(a-b*(0|a/b)); // => 0
a,b=gets.split.map(&:to_i);p a-a/b*b
Я знаю, что есть уже два ответа Ruby, но почему бы и нет; получение ввода таким образом - это достаточно другой подход, чтобы отбросить несколько символов.
a,n=*$*.map(&:to_i);p a-a*n/n
$ ruby a.rb 10 3 1
main(a,b){scanf("%d%d",&a,&b);printf("%d",a-a/b*b);}
Конечно, я не выиграю, но здесь ничего не выходит:
<?php
$a=readline("#1:");
$b=readline("#2:");
while($b<=$a)$a-=$b;
echo "Result: $a";
2?/*-
Запуск с использованием:
RePeNt mod.rpn 17 3
RePeNt "2?/*-" 17 3
RePeNt - это язык игрушек на основе стека, который я сделал сам, где каждый оператор / команда / цикл вводятся в обратной польской нотации (RPN) . Я отпущу интерпретатор, когда немного приберу его.
Command Explanation Stack
------- ----------- -----
n/a The program takes 2 parameters ( 17 3 ) and pushes them 17 3
onto the stack
2 Pushes a 2 onto the stack 17 3 2
? Pops a number (x) off the stack + copies the last x 17 3 17 3
stack items onto the stack
/ Divides on stack 17 3 5
* Multiplies on stack 17 15
- Subtracts on stack 2
2*~/*-
Использование (только способ ввода в сценарий гольфа):
echo 14 3 | ruby golfscript.rb modulo.gs
2
Пояснение:
2*~ #double the input string and eval (so now 14 3 14 3 are on the stack)
/ #int divide 14 / 3, gives quotient
*- #multiply that result by 3, subtract from 14, gives remainder
([-]*<.@%)
Использование:
10 ([-]*<.@%) 3
1
({.-{:*[:<.{.%{:)
Использование:
({.-{:*[:<.{.%{:) 10 3
1
({.-{:*[:<.{.%{:) 225 13
4
Пояснение:
Я взял тотемный столб и превратил его в смайлик , и это сработало.
Предполагая ввод строки запроса в виде script.php?a=27&b=7
и включенные короткие теги:
<?echo($a=$_GET['a'])-(int)($a/$b=$_GET['b'])*$b;
(Это можно сократить на четыре, убрав одинарные кавычки, но это вызовет ошибки. )
С включенным мерзким register_globals
вы можете сократить его до 25 символов:
<?echo $a-(int)($a/$b)*b;
&:7p&:' \/*-.@
Unefunge - это одномерный экземпляр Funge-98: http://quadium.net/funge/spec98.html
Объяснение (Command <- Explaination [Stack]):
& <- Get integer input of value A and store on stack.
[A]
: <- Duplicate top of stack.
[A A]
7 <- Push 7 on stack. Used for the `p` command.
[A A 7]
p <- Pop top two values (7 then A). Place the character whose ASCII value
is A at position 7 in the code (where the space is).
[A]
& <- Get integer input of value B and store on stack.
[A B]
: <- Duplicate top of stack.
[A B B]
' <- Jump over next character and grap the ASCII value of the jumped character.
[A B B A]
<- Because of the `p` command, this is actually the character whose ASCII
value is A at this point in the code. This was jumped over by the
previous instruction.
\ <- Swap top two values of stack.
[A B A B]
/ <- Pop top two values (B then A). Push (A/B) (integer division) onto stack.
[A B (A/B)]
* <- Pop top two values ((A/B) then B). Push (B*(A/B)) onto stack.
[A (B*(A/B))]
- <- Pop top two values ((B*(A/B)) then A). Push (A-(B*(A/B))) onto stack.
[(A-(B*(A/B)))]
. <- Pop top value and print it as an integer.
[]
@ <- Exit program.
Протестированный код - это неполный (но достаточно полный) интерпретатор Unefunge-98, который я написал для тестирования кода:
module Unefunge where
import Prelude hiding (subtract)
import qualified Data.Map as Map
import Control.Exception (handle)
import Control.Monad
import Data.Char (chr, ord)
import Data.Map (Map)
import System.Environment (getArgs)
import System.Exit (exitSuccess, exitFailure, ExitCode (..))
import System.IO (hSetBuffering, BufferMode (..), stdin, stdout)
-----------------------------------------------------------
iterateM :: (Monad m) => (a -> m a) -> m a -> m b
iterateM f m = m >>= iterateM f . f
-----------------------------------------------------------
data Cell = Integer Integer | Char Char
-----------------------------------------------------------
newtype Stack = Stack [Integer]
mkStack = Stack []
push :: Integer -> Stack -> Stack
push x (Stack xs) = Stack (x : xs)
pop :: Stack -> Stack
pop (Stack xs) = case xs of
[] -> Stack []
_:ys -> Stack ys
top :: Stack -> Integer
top (Stack xs) = case xs of
[] -> 0
y:_ -> y
-----------------------------------------------------------
data Env = Env {
cells :: Map Integer Cell
, position :: Integer
, stack :: Stack
}
withStack :: (Stack -> Stack) -> Env -> Env
withStack f env = env { stack = f $ stack env }
pushStack :: Integer -> Env -> Env
pushStack x = withStack $ push x
popStack :: Env -> Env
popStack = withStack pop
topStack :: Env -> Integer
topStack = top . stack
-----------------------------------------------------------
type Instruction = Env -> IO Env
cellAt :: Integer -> Env -> Cell
cellAt n = Map.findWithDefault (Char ' ') n . cells
currentCell :: Env -> Cell
currentCell env = cellAt (position env) env
lookupInstruction :: Cell -> Instruction
lookupInstruction cell = case cell of
Integer n -> pushInteger n
Char c -> case c of
'\''-> fetch
'\\'-> swap
'0' -> pushInteger 0
'1' -> pushInteger 1
'2' -> pushInteger 2
'3' -> pushInteger 3
'4' -> pushInteger 4
'5' -> pushInteger 5
'6' -> pushInteger 6
'7' -> pushInteger 7
'8' -> pushInteger 8
'9' -> pushInteger 9
' ' -> nop
'+' -> add
'-' -> subtract
'*' -> multiply
'/' -> divide
'#' -> trampoline
'&' -> inputDecimal
'.' -> outputDecimal
':' -> duplicate
'p' -> put
'@' -> stop
instructionAt :: Integer -> Env -> Instruction
instructionAt n = lookupInstruction . cellAt n
currentInstruction :: Env -> Instruction
currentInstruction = lookupInstruction . currentCell
runCurrentInstruction :: Instruction
runCurrentInstruction env = currentInstruction env env
nop :: Instruction
nop = return
swap :: Instruction
swap env = return $ pushStack a $ pushStack b $ popStack $ popStack env
where
b = topStack env
a = topStack $ popStack env
inputDecimal :: Instruction
inputDecimal env = readLn >>= return . flip pushStack env
outputDecimal :: Instruction
outputDecimal env = putStr (show n ++ " ") >> return (popStack env)
where
n = topStack env
duplicate :: Instruction
duplicate env = return $ pushStack (topStack env) env
pushInteger :: Integer -> Instruction
pushInteger n = return . pushStack n
put :: Instruction
put env = return env' { cells = Map.insert loc c $ cells env'}
where
loc = topStack env
n = topStack $ popStack env
env' = popStack $ popStack env
c = Char . chr . fromIntegral $ n
trampoline :: Instruction
trampoline env = return env { position = position env + 1 }
fetch :: Instruction
fetch = trampoline >=> \env -> let
cell = currentCell env
val = case cell of
Char c -> fromIntegral $ ord c
Integer n -> n
in pushInteger val env
binOp :: (Integer -> Integer -> Integer) -> Instruction
binOp op env = return $ pushStack (a `op` b) $ popStack $ popStack env
where
b = topStack env
a = topStack $ popStack env
add :: Instruction
add = binOp (+)
subtract :: Instruction
subtract = binOp (-)
multiply :: Instruction
multiply = binOp (*)
divide :: Instruction
divide = binOp div
stop :: Instruction
stop = const exitSuccess
tick :: Instruction
tick = trampoline
-----------------------------------------------------------
buildCells :: String -> Map Integer Cell
buildCells = Map.fromList . zip [0..] . map Char . concat . eols
eols :: String -> [String]
eols "" = []
eols str = left : case right of
"" -> []
'\r':'\n':rest -> eols rest
_:rest -> eols rest
where
(left, right) = break (`elem` "\r\n") str
data Args = Args { sourceFileName :: String }
processArgs :: IO Args
processArgs = do
args <- getArgs
case args of
[] -> do
putStrLn "No source file! Exiting."
exitFailure
fileName:_ -> return $ Args { sourceFileName = fileName }
runUnefunge :: Env -> IO ExitCode
runUnefunge = iterateM round . return
where
round = runCurrentInstruction >=> tick
main :: IO ()
main = do
args <- processArgs
contents <- readFile $ sourceFileName args
let env = Env {
cells = buildCells contents
, position = 0
, stack = mkStack
}
mapM_ (`hSetBuffering` NoBuffering) [stdin, stdout]
handle return $ runUnefunge env
return ()
Работает с отрицательными числами, идентично оператору модуля. Принимает два числа, разделенных запятыми.
x,y=input()
print x-x/y*y
odO / O * -p
$ echo '17 3 odO/O*-p' | dc
2
Java, 110 символов
class C{public static void main(String[]a){Long x=new Long(a[0]),y=x.decode(a[1]);System.out.print(x-x/y*y);}}
Common Lisp, 170 символов (включая отступ):
(defun mod-divide()
(flet((g(p)(format t"Input of ~a number:"p)(read)))
(let*((a(g"first"))(b(g"second")))
(format t "Result:~d~%"(- a(* b(truncate a b)))))))
Старая версия (187 символов):
(defun mod-divide()
(flet((g(p)(format t"Input of ~a number:"p)(read)))
(let*((a(g"first"))(b(g"second")))
(multiple-value-bind(a b)(truncate a b)(format t "Result:~d~%"b)))))
Если ввод-вывод не требуется как часть исходного кода программы, и вы хотите передать именованные аргументы, мы можем получить 10 символов:
>> rebmu/args [sbJmpDVjKk] [j: 20 k: 7]
== 6
Если ввод-вывод требуется, тогда что приводит к 15:
>> rebmu [rJrKwSBjMPdvJkK]
Input Integer: 42
Input Integer: 13
3
Но использование умножения и деления не так интересно (или неэффективно), как это 17-символьное решение:
rJrKwWGEjK[JsbJk]
Что под капотом превращается в эквивалент:
r j r k w wge j k [j: sb j k]
Документировано:
r j ; read j from user
r k ; read k from user
; write out the result of...
w (
; while j is greater than or equal to k
wge j k [
; assign to j the result of subtracting k from j
j: sb j k
]
; when a while loop exits the expression of the while will have the
; value of the last calculation inside the loop body. In this case,
; that last calculation was an assignment to j, and will have the
; value of j
)
Поздняя запись: Я решил пойти по пути наименьшего количества символов и полностью избежать арифметических операций . Вместо этого я использую файловую систему для вычисления результата:
#include <stdio.h>
#define z "%d"
#define y(x)x=fopen(#x,"w");
#define g(x)ftell(x)
#define i(x)fputs(" ",x);
main(a,b){FILE*c,*d;scanf(z z,&a,&b);y(c)y(d)while(g(c)!=a){i(c)i(d)if(g(d)==b)fseek(d,0,0);}printf(z,g(d));}
Perl 25 символов
<>=~/ /;say$`-$'*int$`/$'
использование:
echo 15 6 | perl modulo.pl
3
m a b=a-last((a-b):[b,2*b..a])
Это мой первый код-гольф, не стесняйтесь комментировать код и размещать улучшения. ;-)
Я знаю, что не выиграю, но я просто хотел поделиться своим решением с использованием списков.
В рубине с 38 символами
p (a = gets.to_i) - ((b = gets.to_i) * (a / b))
Не победитель :(
??37axp
Используется следующим образом:
echo "X\nY" | dc -e "??37axp"
[И, ссылаясь на некоторые другие примеры выше, если ввод разрешен для вставки в код, это может быть 5 символов:
37axp
как в:
dc -e "17 3 37axp"
Просто подумал, что стоит упомянуть]