Code-Golf: разделение по модулю
Проблема:
Без использования оператора деления модуля, предоставленного уже вашим языком, напишите программу, которая возьмет два целочисленных входа от пользователя, а затем отобразит результат первого номера модуля, деленное на второе число. Предположим, что весь вход положительный.
Пример:
Input of first number:2
Input of second number:2
Result:0
Кто победит:
Если вы не знаете, как работает Code Golf, победитель - это тот, кто записывает эту программу в наименьшем количестве символов.
Ответы
Ответ 1
CSS: 107 символов:)
CSS (ungolfed):
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: <ol> <li></li> <li></li> <li></li> <!-- etc. --> </ol>
Вывод:
Выход http://img155.imageshack.us/img155/4643/modd.png
Это не работает в IE (неожиданное удивление!).
Ответ 2
J, 10 символов
([-]*<[email protected]%)
Использование:
10 ([-]*<[email protected]%) 3
1
J, 17 символов (с вводом в виде списка)
({.-{:*[:<.{.%{:)
Использование:
({.-{:*[:<.{.%{:) 10 3
1
({.-{:*[:<.{.%{:) 225 13
4
Пояснение:
Я взял тотемный столб и превратил его в смайлик, и это сработало.
Ответ 3
Golfscript, 6 7 13 символы:
2*~/*-
Использование (только способ ввода в golfscript):
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
Ответ 4
RePeNt, 5 символов
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
Ответ 5
Ruby (32):
p(a=gets.to_i)-a/(b=gets.to_i)*b
Ответ 6
Конечно, я не выиграю, но здесь ничего не получается:
<?php
$a=readline("#1:");
$b=readline("#2:");
while($b<=$a)$a-=$b;
echo "Result: $a";
Ответ 7
Я знаю, что уже есть два ответа на Ruby, но почему бы и нет. получение входных данных таким образом - это другой подход, позволяющий сбить несколько символов.
Ruby 1.8.7+, 29 символов
a,n=*$*.map(&:to_i);p a-a*n/n
$ ruby a.rb 10 3
1
Ответ 8
Python: 25 символов
Работает с отрицательными числами, тождественно с оператором модуля. Принимает два запятых.
x,y=input()
print x-x/y*y
Ответ 9
C: 52
main(a,b){scanf("%d%d",&a,&b);printf("%d",a-a/b*b);}
Ответ 10
Clojure: 30 символов
#(if(>%2%1)%1(recur(-%1%2)%2)))
Ответ 11
Unefunge-98: 14 13 22 chars
&:7p&:' \/*[email protected]
Unefunge - это 1-мерный экземпляр 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 ()
Ответ 12
Ruby: 36 символов
a,b=gets.split.map(&:to_i);p a-a/b*b
Ответ 13
Схема: 38
(define(m a b)(- a(*(quotient a b)b)))
Ответ 14
JavaScript, 11 символов
a-b*(0|a/b)
Предполагает, что введенные целые числа содержат переменные a
и b
:
a = 2;
b = 2;
alert(a-b*(0|a/b)); // => 0
Ответ 15
Java. Просто для удовольствия
Предполагая, что s[0]
и s[1]
являются ints
. Не уверен, что это ничего не стоит, но было немного весело.
Обратите внимание, что это не будет иметь эффект цикла (большие числа), но будет работать только с целыми числами. Также это решение одинаково быстро, независимо от того, насколько велики числа. Большой процент предоставленных ответов приведет к созданию огромного рекурсивного стека или длится бесконечно долго, если givin скажет большое число и небольшой делитель.
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);
}
}
Ответ 16
PHP, 49 символов
Предположим, что ввод строки запроса в форме 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;
Ответ 17
Perl, 33 символа
Чтение входов может, вероятно, быть сокращено далее.
($a,$b)[email protected];print$a-$b*int$a/$b
Использование
$ perl -e "($a,$b)[email protected];print$a-$b*int$a/$b" 2457 766
159
Ответ 18
Bash, 21 символ
echo $(($1-$1/$2*$2))
Ответ 19
C, 226 символов
Поздняя запись: я решил пойти на меньшее количество символов, избегая при этом арифметических операций. Вместо этого я использую файловую систему для вычисления результата:
#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));}
Ответ 20
Java: 127 Chars
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);}}
Обратите внимание, что программа действительно работает, но она также бросает
Exception in thread "main" java.lang.NoSuchMethodError: main
после ввода входов и после вывода вывода.
Ответ 21
Общий 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)))))
Ответ 22
DC: 8 символов
odO/O*-p
$ echo '17 3 odO/O*-p' | dc
2
Ответ 23
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);}}
Ответ 24
Rebmu: 10 символов (без ввода-вывода) и 15 символов (с I/O)
Если I/O не требуется как часть источника программы, и вы готовы передать именованные аргументы, мы можем получить 10 символов:
>> rebmu/args [sbJmpDVjKk] [j: 20 k: 7]
== 6
Если требуется I/O, то это занимает 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
)
Ответ 25
Perl 25 символов
<>=~/ /;say$`-$'*int$`/$'
использование:
echo 15 6 | perl modulo.pl
3
Ответ 26
Haskell, 30 символов
m a b=a-last((a-b):[b,2*b..a])
Это мой первый гольф для кодов, свободно комментируйте код и публикуйте улучшения.; -)
Я знаю, что не выиграю, но просто хотел поделиться своим решением с помощью списков.
Ответ 27
В рубине с 38 символами
p (a=gets.to_i)-((b=gets.to_i)*(a/b))
Не победитель: (
Ответ 28
DC: 7 символов (возможно, 5;)
??37axp
Используется следующим образом:
echo "X\nY" | dc -e "??37axp"
[И, ссылаясь на некоторые другие примеры выше, если вход разрешен для ввода в код, это может быть 5 символов:
37axp
как в:
dc -e "17 3 37axp"
Просто подумал, что стоит упомянуть]
Ответ 29
F #, 268 символов
Я выиграл?
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