代码高尔夫:模数除法

发布于 2024-09-05 09:41:28 字数 269 浏览 8 评论 0原文

挑战:

在不使用您的语言已经提供的模除运算符的情况下,编写一个程序,该程序将接受用户的两个整数输入,然后显示第一个数字模数除以第二个数字的结果。假设所有输入均为正。

示例:

    Input of first number:2
    Input of second number:2
    Result:0

谁获胜:

如果您不知道 Code Golf 是如何工作的,获胜者就是用最少字符编写该程序的人。

Challenge:

Without using the modulus divide operator provided already by your language, write a program that will take two integer inputs from a user and then displays the result of the first number modulus divided number by the second number. Assume all input is positive.

Example:

    Input of first number:2
    Input of second number:2
    Result:0

Who wins:

In case you don't know how Code Golf works, the winner is the person who writes this program in the least amount of characters.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(29

脱离于你 2024-09-12 09:41:43

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

F#, 268 chars

Did I win?

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
又爬满兰若 2024-09-12 09:41:42

在 ruby​​ 中,有 38 个字符
p (a=gets.to_i)-((b=gets.to_i)*(a/b))
不是赢家:(

In ruby with 38 chars
p (a=gets.to_i)-((b=gets.to_i)*(a/b))
Not a winner :(

浮生面具三千个 2024-09-12 09:41:42

DC:7个字符(可能是5个;)

??37axp

用法如下:

echo "X\nY" | dc -e "??37axp"

[并且,参考上面的一些其他示例,如果允许将输入插入到代码中,则可以是5个字符:

37axp

如:

dc -e "17 3 37axp"

只是认为值得一提]

DC: 7 Chars (maybe 5 ;)

??37axp

Used as follows:

echo "X\nY" | dc -e "??37axp"

[And, referencing some other examples above, if input is allowed to be inserted into the code, it can be 5 chars:

37axp

as in:

dc -e "17 3 37axp"

Just thought it worth a mention]

我ぃ本無心為│何有愛 2024-09-12 09:41:41

Rebmu:10 个字符(无 I/O)和 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
)

Rebmu: 10 chars (no I/O) and 15 chars (with I/O)

If I/O is not required as part of the program source and you're willing to pass in named arguments then we can get 10 characters:

>> rebmu/args [sbJmpDVjKk] [j: 20 k: 7]
== 6

If I/O is required then that takes it to 15:

>> rebmu [rJrKwSBjMPdvJkK]
Input Integer: 42
Input Integer: 13
3

But using multiplication and division isn't as interesting (or inefficient) as this 17-character solution:

rJrKwWGEjK[JsbJk]

Which under the hood is turned into the equivalent:

r j r k w wge j k [j: sb j k]

Documented:

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
)
鹿港巷口少年归 2024-09-12 09:41:41

Perl 25 个字符

<>=~/ /;say

Perl 25 个字符

-

用法:

echo 15 6 | perl modulo.pl
3
*int

Perl 25 个字符

/

用法:



用法:

Perl 25 characters

<>=~/ /;say

Perl 25 characters

-

usage:

echo 15 6 | perl modulo.pl
3
*int

Perl 25 characters

/

usage:



usage:

流星番茄 2024-09-12 09:41:41

Haskell,30 个字符

m a b=a-last((a-b):[b,2*b..a])

这是我的第一个高尔夫代码,请自由评论代码并发布改进。 ;-)

我知道我不会赢,但我只是想使用列表分享我的解决方案。

Haskell, 30 chars

m a b=a-last((a-b):[b,2*b..a])

This is my first code golf, be free to comment on code and post improvements. ;-)

I know I won't win, but I just wanted to share my solution using lists.

逆蝶 2024-09-12 09:41:40

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);}}

请注意,程序确实可以工作,但

它也会在线程“main”java.lang.NoSuchMethodError: main 中抛出异常。

在输入输入和输出输出后,

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);}}

Note the program does work, but it also throws

Exception in thread "main" java.lang.NoSuchMethodError: main

after the inputs are entered and after the output is outputted.

一笔一画续写前缘 2024-09-12 09:41:40

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)))))

Common Lisp, 170 chars (including indentation):

(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)))))))

Old version (187 characters):

(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)))))
月隐月明月朦胧 2024-09-12 09:41:40

DC:8 个字符

odO/O*-p

$ echo '17 3 odO/O*-p' | dc
2

DC: 8 chars

odO/O*-p

$ echo '17 3 odO/O*-p' | dc
2
揽月 2024-09-12 09:41:40

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);}}

Java, 110 chars

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);}}
双手揣兜 2024-09-12 09:41:39

Perl,33 个字符

读取输入可能会进一步缩短。

($a,$b)=@ARGV;print$a-$b*int$a/$b

用法

$  perl -e "($a,$b)=@ARGV;print$a-$b*int$a/$b" 2457 766
   159

Perl, 33 chars

Reading the inputs could probably be shortened further.

($a,$b)=@ARGV;print$a-$b*int$a/$b

Usage

$  perl -e "($a,$b)=@ARGV;print$a-$b*int$a/$b" 2457 766
   159
神经大条 2024-09-12 09:41:39

爪哇。只是为了好玩

假设 s[0]s[1]ints。不确定这是否值得,但它很有趣。

请注意,这不会受到循环效应(大数)的影响,但仅适用于整数。而且,无论数字有多大,这个解决方案都同样快。所提供的大部分答案将生成巨大的递归堆栈,或者如果给出一个大数和一个小除数,则需要无限长的时间。

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);
    }
}

Java. Just for fun

Assuming that s[0] and s[1] are ints. Not sure this is worth anything but it was a bit of fun.

Note that this won't suffer from the loop effect (large numbers) but will only work on whole numbers. Also this solution is equally fast no matter how large the numbers are. A large percentage of the answers provided will generate a huge recursive stack or take infinitely long if givin say a large number and a small divisor.

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);
    }
}
缱绻入梦 2024-09-12 09:41:39

重击,21 个字符

echo $(($1-$1/$2*$2))

Bash, 21 chars

echo $(($1-$1/$2*$2))
翻身的咸鱼 2024-09-12 09:41:39

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));}

C, 226 chars

Late entry: I decided to go for the least number of characters while avoiding arithmetic operations altogether. Instead, I use the file system to compute the result:

#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));}
一绘本一梦想 2024-09-12 09:41:38

方案:38

(define(m a b)(- a(*(quotient a b)b)))

Scheme: 38

(define(m a b)(- a(*(quotient a b)b)))
堇色安年 2024-09-12 09:41:38

JavaScript,11 个字符

a-b*(0|a/b)

假设输入整数包含变量 ab

a = 2;
b = 2;
alert(a-b*(0|a/b)); // => 0

JavaScript, 11 chars

a-b*(0|a/b)

Assumes input integers are contained the variables a and b:

a = 2;
b = 2;
alert(a-b*(0|a/b)); // => 0
眼角的笑意。 2024-09-12 09:41:38

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;

PHP, 49 chars

Assuming query string input in the form of script.php?a=27&b=7 and short tags turned on:

<?echo($a=$_GET['a'])-(int)($a/$b=$_GET['b'])*$b;

(That could be shortened by four by taking out the single-quotes, but that would throw notices.)

With the vile register_globals turned on you can get it down to 25 chars:

<?echo $a-(int)($a/$b)*b;
以可爱出名 2024-09-12 09:41:37

红宝石:36 个字符

a,b=gets.split.map(&:to_i);p a-a/b*b

Ruby: 36 chars

a,b=gets.split.map(&:to_i);p a-a/b*b
萌梦深 2024-09-12 09:41:36

Clojure:30 个字符

#(if(>%2%1)%1(recur(-%1%2)%2)))

Clojure: 30 characters

#(if(>%2%1)%1(recur(-%1%2)%2)))
゛时过境迁 2024-09-12 09:41:36

Unefunge-98:14 13 22 个字符

&:7p&:' \/*-.@

Unefunge 是 Funge-98 的一维实例:http://quadium.net/funge/spec98.html

说明(命令 <- 说明 [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 ()

Unefunge-98: 14 13 22 chars

&:7p&:' \/*-.@

Unefunge is the 1-dimensional instance of Funge-98: http://quadium.net/funge/spec98.html

Explanation (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.

Code tested is this incomplete (but complete enough) Unefunge-98 interpreter I wrote to test the code:

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 ()
情域 2024-09-12 09:41:34

C:52

main(a,b){scanf("%d%d",&a,&b);printf("%d",a-a/b*b);}

C: 52

main(a,b){scanf("%d%d",&a,&b);printf("%d",a-a/b*b);}
扶醉桌前 2024-09-12 09:41:34

Python:25 个字符

负数的行为,与模运算符相同。采用两个逗号分隔的数字。

x,y=input()
print x-x/y*y

Python: 25 chars

Behaves with negative numbers, identically to modulus operator. Takes two comma-separated numbers.

x,y=input()
print x-x/y*y
请爱~陌生人 2024-09-12 09:41:33

当然我不会赢,但这里什么也没有:

<?php  
$a=readline("#1:");  
$b=readline("#2:");  
while($b<=$a)$a-=$b;  
echo "Result: $a";  

Sure I won't win, but here goes nothing:

<?php  
$a=readline("#1:");  
$b=readline("#2:");  
while($b<=$a)$a-=$b;  
echo "Result: $a";  
洛阳烟雨空心柳 2024-09-12 09:41:33

我知道已经有两个 Ruby 答案,但为什么不呢?以这种方式获取输入是一种足够不同的方法,足以消除一些字符。

Ruby 1.8.7+,29 个字符

a,n=*$*.map(&:to_i);p a-a*n/n
$ ruby a.rb 10 3
1

I know there's already two Ruby answers, but why not; getting the input this way is a different enough approach to knock off a few characters.

Ruby 1.8.7+, 29 chars

a,n=*$*.map(&:to_i);p a-a*n/n
$ ruby a.rb 10 3
1
一生独一 2024-09-12 09:41:32

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

Golfscript, 6 7 13 chars:

2*~/*-

Usage (only way to input into golfscript):

echo 14 3 | ruby golfscript.rb modulo.gs
2

Explanation:

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
南七夏 2024-09-12 09:41:32

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

RePeNt, 5 chars

2?/*-

Run using:

RePeNt mod.rpn 17 3
RePeNt "2?/*-" 17 3

RePeNt is a stack-based toy language I made myself where every operator/command/loop is entered in Reverse Polish Notation (RPN). I will release the interpreter when I have tidied it up a bit.

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
烟雨扶苏 2024-09-12 09:41:32

红宝石 (32):

p(a=gets.to_i)-a/(b=gets.to_i)*b

Ruby (32):

p(a=gets.to_i)-a/(b=gets.to_i)*b
浅唱ヾ落雨殇 2024-09-12 09:41:31

J,10 个字符

([-]*<.@%)

用法:

   10 ([-]*<.@%) 3
1

J,17 个字符(以列表形式输入)

({.-{:*[:<.{.%{:)

用法:

  ({.-{:*[:<.{.%{:) 10 3
1

  ({.-{:*[:<.{.%{:) 225 13
4

解释:

我拿了一个图腾柱,把它变成了一个笑脸,它起作用了。

J, 10 characters

([-]*<.@%)

Usage:

   10 ([-]*<.@%) 3
1

J, 17 characters (with input as a list)

({.-{:*[:<.{.%{:)

Usage:

  ({.-{:*[:<.{.%{:) 10 3
1

  ({.-{:*[:<.{.%{:) 225 13
4

Explanation:

I took a totem pole and turned it into a smiley, and it worked.

好菇凉咱不稀罕他 2024-09-12 09:41:30

CSS:107 个字符 :)

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:
<代码>

    ;

这在 IE 中不起作用(惊喜!)。

CSS: 107 chars :)

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;
}

Accompanying HTML:
<ol> <li></li> <li></li> <li></li> <!-- etc. --> </ol>

This doesn't work in IE (surprise surprise!).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文