Rosetta Stone Challenge: Find the rule for a series

15

2

The goal of a Rosetta Stone Challenge is to write solutions in as many languages as possible. Show off your programming multilingualism!

The Challenge

Your challenge is to implement a program that will input a list of numbers and output the rule used to generate each successive number in the series, in as many programming languages as possible. You are allowed to use any sort of standard library function that your language has, since this is mostly a language showcase.

What is a "series?"

A series is an ordered list of integers. Each successive number in the series can be generated by applying a simple rule to the previous number in the series. In this challenge, the rule consists of multiplying the number by a constant, and then adding a second constant. Both of the constants can be any integer. The goal of this challenge is to output those two constants.

For the series 2 5 11, the rule can be written as 2 1. This means that each number is the previous number, times 2, plus 1. An important fact is that most series have exactly one rule. Some series have either an infinite number or none at all, but you will not have to deal with this.

Input

Input will be a list of three different integers which are the numbers in the sequence. The numbers can be either space, comma, or newline delimited, but please specify which. I am going to be flexible on this limitation because certain languages may have input restrictions. Here are four examples of input:

0 7 14
2 5 11
2 0 -4
5 -19  77

Output

Output will be two integers which represent the rule used to generate the series. The first number will be the multiplicative constant, while the second number will be the additive constant. The formatting of the output can be space, comma, or newline delimited. I am flexible on this limitation as well. Here are the corresponding examples of output:

1 7
2 1
2 -4
-4 1

The Objective Winning Criterion

As for an objective winning criterion, here it is: Each language is a separate competition as to who can write the shortest entry, but the overall winner would be the person who wins the most of these sub-competitions. This means that a person who answers in many uncommon languages can gain an advantage. Code-golf is mostly a tiebreaker for when there is more than one solution in a language: the person with the shortest program gets credit for that language.

Rules, Restrictions, and Notes

Your program can be written in any language that existed prior to April 9th, 2012. I will also have to rely on the community to validate some responses written in some of the more uncommon/esoteric languages, since I am unlikely to be able to test them.


Current Leaderboard

This section will be periodically updated to show the number of languages and who is leading in each.

  • AWK (32) - mellamokb
  • bash (31) - Peter Taylor
  • Befunge (29) - Howard
  • bc (39) - kernigh
  • brainfuck (174) - CMP
  • C (78) - l0n3_shArk
  • C++ (96) - leftaroundabout
  • Common Lisp (88) - kernigh
  • Cray Chapel (59) - Kyle Kanos
  • csh (86) - kernigh
  • Cuda (301) - leftaroundabout
  • dc (30) - kernigh
  • DOS BATCH (54) - mellamokb
  • Element (27) - Howard
  • es (95) - kernigh
  • Factor (138) - kernigh
  • Felix (86) - kirbyfan64sos
  • Fortran (44) - Kyle Kanos
  • Go (101) - Howard
  • GolfScript (16) - Howard
  • Golflua (44) - Kyle Kanos
  • Haskell (35) - leftaroundabout
  • J (23) - Gareth
  • Java (141) - Howard
  • JavaScript (47) - mellamokb
  • Julia (71) - M L
  • Lua (51) - Howard
  • Mercury (319) - leftaroundabout
  • MoonScript (48) - kirbyfan64sos
  • Nimrod (146) - leftaroundabout
  • Owl (22) - r.e.s.
  • Pascal (88) - leftaroundabout
  • Perl (57) - Gareth
  • PHP (61) - mellamokb
  • PicoLisp (72) - kernigh
  • Piet (56) - M L
  • PostScript (61) - Howard
  • Python (40) - Howard
  • Q (36) - tmartin
  • QBasic (34) - mellamokb
  • R (50) - r.e.s.
  • Ruby (44) - Howard
  • Scala (102) - Gareth
  • SQL (57) - Aman ZeeK Verma
  • TI-83 BASIC (25) - mellamokb
  • Unlimited Register Machine (285) - Paxinum
  • VBA (57) - Gaffi
  • Whitespace (123) - r.e.s.
  • zsh (62) - kernigh

Current User Rankings

Equal ranks are sorted alphabetically.

  1. Howard (9): Befunge (29), Element (27), Go (101), GolfScript (16), Java (141), Lua (51), PostScript, (61) Python, (40) Ruby (44)

  2. kernigh (8): bc (39), Common Lisp (88), csh (86), dc (30), es (95), Factor (138), PicoLisp (72), zsh (62)

  3. leftroundabout (6): C++ (96), Cuda (301), Haskell (35), Mercury (319), Nimrod (146), Pascal (88)

  4. mellamokb (6): AWK (32), DOS BATCH (54), JavaScript (47), PHP (61), QBasic (34), TI-83 BASIC (41)

  5. Gareth (3): J (23), Perl (57), Scala (102)

  6. Kyle Kanos (3): Cray Chapel (59), Fortran (44), Golflua (44)

  7. r.e.s. (3): Owl (22), R (50), Whitespace (123)

  8. kirbyfan64sos (2): Felix (86), MoonScript (48)

  9. M L (2): Julia (71), Piet (56)

  10. Aman Zeek verma (1): SQL (57)

  11. CMP (1): brainfuck (174)

  12. Gaffi (1): VBA (57)

  13. l0n3_shArk (1): C (78)

  14. Paxinum (1): Unlimited Register Machine (285)

  15. Peter Taylor (1): bash (31)

  16. tmartin (1): Q (36)

PhiNotPi

Posted 2012-04-09T16:43:15.573

Reputation: 26 739

It doesn't look like people actually read the tags, or other descriptions... – ceased to turn counterclockwis – 2012-04-09T17:35:43.937

@leftaroundabout: Why do you say that? I am aware (for instance) that my solution doesn't take array input and plan to fix it later. And I'm too lazy to post more than one solution at the moment :) According to the Object Winning Criterio, code-golf is the tie-breaker for two posts with the same language, hence I've included the character count for easy reference in case someone else posts a JavaScript solution. This may in fact be one of those rare moments when a question deserves both the code-golf and code-challenge tags. – mellamokb – 2012-04-09T17:36:52.533

Yeah, you're right: someone has to do the not-unusual languages as well. – ceased to turn counterclockwis – 2012-04-09T18:02:27.307

I like the way you specified this problem, but mathematical pendants will tell you that a general series is not required to have a generating rule at all. – dmckee --- ex-moderator kitten – 2012-04-09T19:59:39.613

I know, but trying to calculate a generating rule wouldn't be much fun if there wasn't one. :) – PhiNotPi – 2012-04-09T20:03:31.253

3

As long as you keep the Current Leaderboard in the same standard format as above, you can use this to generate each user's scores: http://jsfiddle.net/bk2WM/2/

– mellamokb – 2012-04-10T14:43:43.493

@mellamokb Wow, thanks. As the number of languages increases, that could actually become very useful. – PhiNotPi – 2012-04-10T14:59:00.893

Added a score-board to my post from the current list. – mellamokb – 2012-04-11T13:49:11.183

1

My newest version (http://jsfiddle.net/bk2WM/4/) provides a raw output (in the textarea) you can copy/paste into a post, and formats it like I did in my post. Feel free to change/play with the layout.

– mellamokb – 2012-04-11T14:26:34.787

Doesn't my PostScript solution count? ;-) – Howard – 2012-04-11T16:27:10.503

@Howard Sorry, I must have overlooked it. – PhiNotPi – 2012-04-11T17:43:15.247

Answers

9

GolfScript, 16 characters

~1$- 1$3$-/.p@*-

Input is given as space-separated list.

JavaScript, 56 characters

p=prompt;x=alert;a=p();b=p();x(m=(p()-b)/(b-a));x(b-a*m)

Input is given on prompt.

Ruby, 44 characters

a,b,c=eval("[#{gets}]");m=c-b;p m/=b-a,b-m*a

Input is here given as comma-separated list.

Python, 40 characters

a,b,c=input();m=c-b;m/=b-a;print m,b-m*a

Input is again comma-separated.

Java, 141 characters

enum E{E;static int s(){return new java.util.Scanner(System.in).nextInt();}{int a=s(),b=s(),m=s()-b;m/=b-a;System.out.print(m+" "+(b-a*m));}}

Input separated by newline.

Lua, 51 characters

r=io.read
a,b=r(),r()
m=(r()-b)/(b-a)
print(m,b-m*a)

Input separated by newline.

Go, 101 characters

package main
import"fmt"
var a,b,c int
func main(){fmt.Scan(&a,&b,&c)
c-=b
c/=b-a
fmt.Print(c,b-a*c)}

Input separated by newline.

Fortran, 90 characters

      PROGRAM X
      READ(*,*)I,J,K
      K=(K-J)/(J-I)
      WRITE(*,*)K,J-I*K
      END

Input separated by newline.

Befunge, 29 characters

&01p&:11p:&-01g11g-/:.01g*-.@

PostScript, 61 characters

2 5 14
1 index sub 1 index 3 index sub idiv dup = 3 2 roll mul sub =

Owl, 23 characters

<%<%<$-1`4'-/%.32)2'*-.

Input separated by newline.

Element, 27 characters

_-a;_3:'-_+"a~+/2:`a~*+\ ``

Input separated by newline.

Howard

Posted 2012-04-09T16:43:15.573

Reputation: 23 109

Shameless heist of my JavaScript solution ;) – mellamokb – 2012-04-09T19:33:28.907

1Well two can play this game... :P – mellamokb – 2012-04-09T22:31:40.233

@mellamokb Nice one. But I did already upvote your answer ;-) So what's left for us: beat the 48 characters... – Howard – 2012-04-10T04:01:11.807

Done, now 47 characters :) – mellamokb – 2012-04-10T12:45:57.713

I might argue that your befunge solution requires another row at runtime, so should be 29x2. I;m also just jealous. – captncraig – 2012-04-11T02:42:29.693

@CMP Ah, code-golf is bytes of source code ;-) – Howard – 2012-04-11T04:37:55.537

2Wow, you golfed in my language. I feel honored. I also feel obligated to beat you. :) – PhiNotPi – 2012-04-11T19:50:01.637

1About your Element solution, it appears that the last ` mark isn't needed. Is this an error on your part or an error in my interpreter that I posted on Pastebin? Oh, and I have a 27 character solution. – PhiNotPi – 2012-04-11T22:17:00.690

@PhiNotPi You were right. It was an issue with my script which piped the input directly into your interpreter (i.e. with no newlines appended). The interpreter then removes the last character and thus the last code character. I changed the chop to chomp and everything was fine then. Oh, and I also found a 27 character solution. I'm still figuring out how to golf in Element as this was the first time I used this language at all ;-) – Howard – 2012-04-13T18:16:21.887

I'm surprised that you have managed to learn the language so quickly! Here is my 27 character solution: -2:''_3:'-+""+/2:`"*+\ `` (I hope it displays properly) EDIT: It appears to be very similar to your solution, actually. – PhiNotPi – 2012-04-13T18:22:34.877

By the way, what is your opinion of Element as a language for golfing? I think that it is good with math, but not very good for complex string manipulation. – PhiNotPi – 2012-04-13T18:42:46.380

I also found that solution after posting mine. It endded is equivalent: first item on control stack corresponds to element a in the above version. – Howard – 2012-04-13T18:42:53.790

I agree. It takes several characters to do something like a simple split on an input string. And sometimes you have to work around the point that you can't simply swap top numbers on the stack. – Howard – 2012-04-13T18:53:31.623

You can swap the top two items on the stack with 0 1@ which moves the top item so that it is the second item (the stack is indexed starting on zero for the top item). This would be shorter with a single command, but the @ operation is more versatile in that it can move any item to anywhere in the stack. – PhiNotPi – 2012-04-13T20:24:20.637

8

QBasic, 42

INPUT "",a,b,c
m=(c-b)/(b-a)
PRINT m;b-m*a

Requires input with commas, outputs with spaces (is this ok?)


Mercury, 319

:-module r.
:-interface.
:-import_module io,list,int,char,string.
:-pred main(io::di,io::uo)is det.
:-implementation.
main(!IO):-io.read_line_as_string(J,!IO),(if J=ok(I),[A,B,C]=list.map(string.det_to_int,string.words_separator(char.is_whitespace,I)),M=(C-B)/(B-A)then io.format("%d %d",[i(M),i(B-M*A)],!IO)else true).

Haskell, 85 81

f[a,b,c]|m<-(c-b)`div`(b-a)=[m,b-m*a]
main=getLine>>=mapM_ print.f.map read.words

Now inputs with spaces, outputs with newlines.


C, 80

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

C++, 96

#include<iostream>
main(){int a,b,c,m;std::cin>>a>>b>>c;m=(c-b)/(b-a);std::cout<<m<<' '<<b-m*a;}

Nimrod, 146

import strutils
var
 q:array[0..3,int]
 b,m:int
for i in 0..2:q[i]=ParseInt(readLine(stdin))
b=q[1]
m=(q[2]-b)div(b-q[0])
echo($m,",",$(b-m*q[0]))

Input w/ newlines, output comma.


This one won't count, but I feel it still fits in in some way:

Mathematical theorem, 713 characters of LaTeX

\documentclass{article}\usepackage{amsmath}\usepackage{amsthm}\begin{document}Theorem: for a sequence $(a_i)_i$ of integers with $a_2\neq a_1$ where $a_3-a_2$ is divisible by $a_2-a_1$, $m:=\frac{a_3-a_2}{a_2-a_1},\ p:=a_2-m\cdot a_1$ give rise to a sequence\[b_i:=\begin{cases}a_1&\text{for }i=1\\b_{i-1}\cdot m+p&\text{else}\end{cases}\] such that $b_i=a_i\ \forall i\leq 3$.

Proof: $i=1$ is trivial,\[\begin{aligned}b_2=&b_1\cdot m+p=a_1\frac{a_3-a_2}{a_2-a_1}+a_2-\frac{a_1a_3-a_1a_2}{a_2-a_1}=a_2,\\b_3=&b_2\cdot m+p=\frac{a_2a_3-a_2^2}{a_2-a_1}+a_2-\frac{a_1a_3-a_2^2}{a_2-a_1}\\=&\frac{a_2a_3-a_1a_3+(a_2-a_1)a_2-a_2^2+a_1a_2}{a_2-a_1}\\=&\frac{a_2-a_1a_3+0}{a_2-a_1}=a_3.\end{aligned}\]\qed\end{document}

Output of the LaTeX mathematical-theorem solution


While we're at writing := definitions...

Pascal, 90 88

program r;var a,b,c:integer;begin;read(a,b,c);c-=b;c:=c div(b-a);write(c,' ',b-c*a);end.

Cuda, 301

#include<stdio.h>
__global__ void r(int*q){if(!(blockIdx.x|threadIdx.x)){q[1]-=*q;q[1]/=(*q-q[2]);*q-=q[1]*q[2];}}
main(){int p[3],*q;scanf("%d%d%d",p+2,p,p+1);cudaMalloc(&q,24);cudaMemcpy(q,p,24,cudaMemcpyHostToDevice);r<<<1,1>>>(q);cudaMemcpy(p,q,24,cudaMemcpyDeviceToHost);printf("%d %d",p[1],*p);}

ceased to turn counterclockwis

Posted 2012-04-09T16:43:15.573

Reputation: 5 200

1You can save two chars in the C solution by eliminating m and reusing c, and another two by using c-=b;c/=b-a; instead of c=(c-b)/(b-a);. – Peter Taylor – 2012-04-10T11:46:44.800

In the C solution, you don't need the spaces in the scanf() format string. – Reto Koradi – 2015-06-14T17:52:32.093

8

Brainfuck - 174

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

Piet - 82?

Not sure how to measure competitive golf here. I'm gonna go with total image size (in codels) Mine is 41x2: enter image description here

Befunge - 34

&00p&10p&10g-10g00g-/:.00g*10g\-.@

English - 278

The multiplier is the quotient of the difference of the second 
and third values and the second and first values. 
To generate a new term, multiply the current term by the multiplier
and add the difference of the first value and the product of the 
multiplier and the second value.

Not sure if this counts, but thought I'd give it a shot. It is remarkably difficult to describe even a simple algorithm accurately. Kinda wish English supported some kind of grouping symbol to establish precedence.

captncraig

Posted 2012-04-09T16:43:15.573

Reputation: 4 373

Link me to an interpreter (a complete one that understands the entire language, and is not just geared towards solving this problem) and I may accept it. – PhiNotPi – 2012-04-10T19:37:11.073

ummm, http://www.worldinterpreting.com?

– captncraig – 2012-04-11T02:10:57.047

1It's ok, another person has written a mathematical proof in LaTeX. It didn't count, but adds to the variety. – PhiNotPi – 2012-04-11T02:13:12.470

If I try out your Piet solution with npiet I get this result: D:\Software\Programming\Piet\npiet-1.3a-win32>npiet series2.png ? 5 ? -19 ? 77

05

The solution should be -4 1 – M L – 2015-06-14T16:18:15.617

The image you posted does not work unless you grow it by one pixel (not codel!) at the right side. 461 pixels aren’t divisible by 11, which is a rather unusual codel size, by the way ;) – M L – 2015-06-18T00:57:49.537

7

AWK (32)

{m=$3-$2;print m/=$2-$1,$2-$1*m}

Demo: http://ideone.com/kp0Dj


bash (38)

awk '{m=$3-$2;print m/=$2-$1,$2-$1*m}'

Demo: http://ideone.com/tzFi8


DOS/BATCH (54 55)

set/a m=(%3-%2)/(%2-%1)&set/a n=%2-%m%*%1&echo %m% %n%

Takes parameters as space-separated list of arguments.


Java (143 185)

enum R{R;{int a=0,b=0,c,i=2;for(;(c=new java.util.Scanner(System.in).nextInt()+b*--i)+i>=c;b=c)a+=c*i;c/=b-a;System.out.print(c+" "+(b-a*c));}}


JavaScript (48 61 67)

p=prompt;m=p(b=p(a=p()))-b;alert([m/=b-a,b-a*m])

​ Demo: http://jsfiddle.net/BT8bB/6/


PHP (61 77)

<?list(,$a,$b,$c)=$argv;$c-=$b;echo($c/=$b-$a).' '.$b-=$c*$a;

Demo: http://ideone.com/CEgke


QBasic (34)

INPUT a,b,c
m=(c-b)/(b-a)
?m;b-m*a

TI-83 Basic (25 41)

:Prompt A,B,C
:(C-B)/(B-A
:Disp Ans,B-AAns

Yes, the missing right parenthesis is on purpose. It's a well-known optimization technique that closing the parentheses before a STO operation is not necessary in TI-83 Basic programming.

mellamokb

Posted 2012-04-09T16:43:15.573

Reputation: 5 544

1The JS one doesn't work for me in Firefox - I get an error that p is undefined. Does the JS spec say that function arguments should be evaluated before the function is resolved? – Peter Taylor – 2012-04-12T14:26:13.497

Hmm. Yes you are correct. According to the spec, it should not work, as explained in this similar SO question: http://stackoverflow.com/questions/9941736/why-javascript-doesnt-let-a-function-redefine-itself-from-within-itself. The functions are supposed to be bound before their arguments are evaluated, and Chrome apparently does it in reverse order.

– mellamokb – 2012-04-12T15:39:44.830

I've tried long and hard to beat the highest Java solution by a completely different approach you can see above. 143 is the closest I've been able to get. Anyone have any ideas, please send my way! – mellamokb – 2012-04-12T18:52:34.277

7

AWK, 35 characters

{m=($3-$2)/($2-$1);print m,$2-$1*m}
  • Input format: 2 0 -4

bc, 39 characters

define f(a,b,c){
m=(c-b)/(b-a)
m
b-a*m}
  • Input format: z=f(2, 0, -4)
  • The input is a bc expression. After bc reads the source file, it reads the standard input. This is why the input must look like a function call.
  • I use OpenBSD bc, which requires a newline after the {.

Common Lisp, 88 characters

(let*((a(read))(b(read))(c(read))(m(/(- c b)(- b a))))(format
t "~A ~A" m (- b(* a m))))
  • Input format: 2 0 -4

csh, 86 characters

set i=(`cat`)
@ m=($i[3] - $i[2]) / ($i[2] - $i[1])
@ n=$i[2] - $i[1] * $m
echo $m $n
  • Input format: 2 0 -4
  • The 86th character is newline at end of file. csh is the only language for which I count newline at end of file. This is because csh never runs the last command unless newline is there.
  • set i=($<) does not work, because $< has no word splitting.

dc, 30 characters

?scsbsalclb-lbla-/psmlblalm*-p
  • Input format: 2 0 _4, where _ is the underscore.

es, 95 characters

i=(`cat)
b=$i(2)
m=`{expr \( $i(3) - $b \) / \( $b - $i(1) \)}
echo $m `{expr $b - $i(1) \* $m}
  • Input format: 2 0 -4
  • es is the extensible shell by Paul Haahr and Byron Rakitzis.

Factor, 138 characters

USING: eval formatting io kernel locals math ;
contents eval( -- a b c ) [let :> ( a b c )
c b - b a - / dup a * b swap - "%d %d" printf ]
  • Input format: 2 0 -4

PicoLisp, 74 72 characters

(in()(let(r read a(r)b(r)c(r)m(/(- c b)(- b a)))(print
m (- b(* a m)))))
  • Input format: 2 0 -4
  • EDIT: Lost 2 characters by changing a(read)b(read)c(read) to r read a(r)b(r)c(r).

TI-83 BASIC, 63 61 characters

:Input A
:Input B
:Input C
:(C-B)/(B-A)→M
:Disp M
:Disp B-A*M
  • Input format: 2 ENTER 0 ENTER ¯4 ENTER, where ¯ is the calculator's unary minus.
  • I counted Unicode characters; (the right arrow) counts as U+2192. For example, the calculator counts Input A as 2 characters, but I count Input A as 7 characters. I also count : as 1 character.
  • EDIT: I miscounted: there are 61, not 63, characters.

zsh, 62 characters

i=(`cat`)
((b=i[2],m=(i[3]-b)/(b-i[1]),n=b-i[1]*m))
echo $m $n
  • Input format: 2 0 -4

kernigh

Posted 2012-04-09T16:43:15.573

Reputation: 2 615

6

Whitespace, 123

    





















I/O is newline-separated. (To obtain the source code, enter edit mode and copy the whitespace between the preformat tags; or, see the online example at Ideone.)

Explanation, where S,T,L represents Space,Tab,Linefeed:

Pseudocode     Whitespace
----------     ----------
push 0         SS SSL
readn          TLTT
push 1         SS STL
readn          TLTT
push 2         SS STSL
dup            SLS
readn          TLTT
retr           TTT
push 1         SS STL
retr           TTT
-              TSST
push 1         SS STL
retr           TTT
push 0         SS SSL
retr           TTT
-              TSST
/              TSTS
dup            SLS
outn           TLST
push 10        SS STSTSL
outc           TLSS
push 0         SS SSL
retr           TTT
*              TSSL
push 1         SS STL
retr           TTT
swap           SLT
-              TSST
outn           TLST
exit           LLL

R, 50

x=scan(n=3);y=diff(x);z=y[2]/y[1];c(z,x[2]-x[1]*z)

I/O is space-separated.


Owl

---22---

< <%<-2`2`-/%.10)2'*-.

I/O is newline-separated.

---19--- (if this version is allowed; but I think it's cheating, since the \ is executable code):

1`-1`3`-/%.32)2'*-.

I/O is space-separated. Command-line usage: owl prog 5 19\ 77 (the \ acts as a postfix unary minus in Owl).

r.e.s.

Posted 2012-04-09T16:43:15.573

Reputation: 2 872

With your Owl entry, I can suspend judgement of your 19 char solution since your 22 char solution is already winning for the language. – PhiNotPi – 2012-04-13T18:34:09.823

5

J, 23 characters

(],1{x-0{x*])%~/2-/\x=:

Usage:

   (],1{x-0{x*])%~/2-/\x=: 5 _19 77
_4 1

Negative numbers are represented by underscores in J.

PHP, 88 characters

<?php
list($x,$y,$z)=split(' ',fgets(STDIN));
$a=($z-$y)/($y-$x);
echo$a." ".($y-$a*$x);

Scala, 102 characters

val x=readLine.split(" ").toList.map(_.toInt)
val a=(x(2)-x(1))/(x(1)-x(0))
print(a+" "+(x(1)-x(0)*a))

Perl, 57 characters

s!(.+) (.+) (.+)!$a=($3-$2)/($2-$1);$a." ".($2-$1*$a)!e

Requires the '-p' option, for which I have added 2 characters. Assumes that the input is valid to save some characters.

All my answers take space separated numbers.

Gareth

Posted 2012-04-09T16:43:15.573

Reputation: 11 678

About J programs ... Is input allowed to be coded directly in the source file instead of prompting it from the user? – r.e.s. – 2012-04-13T16:23:16.540

@r.e.s. I've given it just the way I would invoke it on the command line. Adding 1!:1]3on the right of the expression will read the input from STDIN. I think there has been discussion on meta or in comments to some J answers over whether this should be allowed or not. I'm somewhat ambivalent - I enjoy figuring out how to get J to do what I want in the smallest space, I'll take the 6 character penalty for input from STDIN if that's what everyone wants. – Gareth – 2012-04-13T16:50:33.713

I was thinking that if it's allowed for J, then some other entries might be shortened in a similar way. (BTW, I couldn't get your suggested expression to work, but (],1{x-0{x*])%~/2-/\x=:".1!:1]1 seems ok in console mode.) – r.e.s. – 2012-04-13T17:02:39.080

@r.e.s. Oh yeah, I forgot to convert from a string to a list of numbers (though the 3 at the end normally works ok for me?) – Gareth – 2012-04-13T17:07:48.777

If you make the Perl a subroutine rather than a full program, you can get it down to 50 bytes (and no command-line flags are necessary): ($a=($_[1]-pop)/($_[0]-$_[1])).$/.($_[1]-$_[0]*$a) – msh210 – 2016-03-11T19:20:50.073

4

PHP, 74,72,69

<?fscanf(STDIN,'%d%d%d',$a,$b,$c);echo($d=($c-$b)/($b-$a)).' '.($b-$d*$a);

When input is passed as arguments:

<?echo($d=($argv[3]-$argv[2])/($b=$argv[2]-$a=$argv[1])).' '.($b-$d*$a);

Now, as @mellamokb suggested, using $n=$argv:

<?$n=$argv;echo($d=($n[3]-$n[2])/($b=$n[2]-$a=$n[1])).' '.($b-$d*$a);

C, 77,78

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

^ doesn't work so, here's the stuff: [thanks to @ugoren for bringing it to notice]

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

l0n3sh4rk

Posted 2012-04-09T16:43:15.573

Reputation: 1 387

+1 Wow, didn't know you could fscanf and scanf without spaces. Awesome! – mellamokb – 2012-04-10T15:41:52.627

1In your second PHP solution, couldn't you save a few more characters by renaming $argv, i.e., $n=$argv at the beginning? – mellamokb – 2012-04-10T19:24:18.960

@mellamokb- yeah! I didn't think about that! thanks! :) – l0n3sh4rk – 2012-04-11T08:30:47.073

Your C code doesn't work (I tried on Linux). I relies on a very strange parameter evaluation order - why would scanf be done first, then d=.. then b-d*a? – ugoren – 2012-04-11T09:29:11.387

I test for only the 0 7 14 case. Will look into it now. And the scanf gets evaluated first, I tried putting the printf inside the scanf, but i got an ouput before I could give the input. – l0n3sh4rk – 2012-04-11T09:37:11.733

Now, the new one seems to work fine. I infer that the execution is done from right to left. – l0n3sh4rk – 2012-04-11T10:10:14.300

1

From what I can tell, this just arbitrarily "happens" to work in most environments (ex: http://ideone.com/I2cPg), but the order of parameter evaluation in C is undefined behavior, and so technically shouldn't be relied upon: http://orangejuiceliberationfront.com/funny-thing-about-c-parameter-evaluation-order/

– mellamokb – 2012-04-11T13:27:50.040

3

DOS-BATCH, 98

@ECHO OFF&SET/P p=&SET/P q=&SET/P r=&SET/A m=(%r%-%q%)/(%q%-%p%)&SET/A n=%q%-%p%*%m%&ECHO %m% %n%

Input in separate lines

Bash, 51

m=$((($3 - $2)/($2 - $1)))
echo $m $(($2 - $m*$1))

Example : sh prog.sh 2 0 -4 (space separated arguments)

Perl, 84

@s=split(/ /,&lt;STDIN&gt;);$m=($s[2]-$s[1])/($s[1]-$s[0]);print $m." ".($s[1]-$s[0]*$m);

Java, 297

import java.util.*;public class A{public static void main(String a[]){StringTokenizer s=new StringTokenizer(new Scanner(System.in).nextLine());int i=4;int[] p=new int[i];while(i-->1)p[3-i]=Integer.parseInt(s.nextToken());p[3]=(p[2]-p[1])/(p[1]-p[0]);System.out.print(p[3]+" "+(p[1]-p[0]*p[3]));}}

Space separated input, space separated output.

SQL, 57

select (&3-&2)/(&2-&1),&2-((&3-&2)/(&2-&1)*&1) from dual

This is a sad entry, but 'just' solves the purpose. The query binds input at runtime 1,2,3 are variables in order of input.

Aman ZeeK Verma

Posted 2012-04-09T16:43:15.573

Reputation: 609

Even though others have already beat your bash solution, I just wanted to suggest you could have removed all those extra spaces and saved 6 characters. – mellamokb – 2012-04-12T12:53:27.263

Thanks mellamokb, I did realize that, I just sort of ignored it later. Also, I hate myself of not thinking your dos/batch solution, that should have clicked my head..args ahh! – Aman ZeeK Verma – 2012-04-12T15:04:25.870

3

bash (42 chars)

Pure bash:

((m=($3-$2)/($2-$1),c=$2-m*$1));echo $m $c

bash (31 chars)

Shelling out to something else:

owl -p"<%<%<$-1`4'-/%.32)2'*-."

(Based on Howard's OWL implementation)

Peter Taylor

Posted 2012-04-09T16:43:15.573

Reputation: 41 901

3

VBA, 57 characters

Sub x(a,b,c)
y=(c-b)/(b-a)
MsgBox y & " " & b-a*y
End Sub

(This is basically the same as the other 'BASIC' functions, but I didn't see any VBA submissions out there already.)

Gaffi

Posted 2012-04-09T16:43:15.573

Reputation: 3 411

You can drop 8 bytes by changing line 3 to Debug.?y;b-a*y – Taylor Scott – 2017-05-31T14:47:31.123

3

This is (non-optimized) code for the unimited register machine, described here: http://www.proofwiki.org/wiki/Definition:Unlimited_Register_Machine

The input should be in register 1,2 and 3, and the output will be in register 1, 2 after the program is done. Non-negative and non-integer numbers are not handled, but inputs 0,7,14 and 2,5,11 are handled correctly.

Zero[8] Trans[2,11] Jump[3,11,7] Succ[11] Succ[8] Jump[11,11,3] Zero[5] Trans[1,12] Jump[2,12,13] Succ[12] Succ[5] Jump[12,12,9] Zero[17] Trans[8,13] Jump[13,17,25] Zero[16] Trans[5,14] Jump[13,14,22] Succ[14] Succ[16] Jump[14,14,18] Succ[9] Trans[16,13] Jump[17,17,15] Zero[6] Zero[20] Jump[9,6,40] Zero[7] Trans[1,21] Jump[20,7,36] Succ[21] Trans[21,19] Trans[19,21] Succ[7] Jump[7,7,30] Trans[21,18] Trans[18,20] Succ[6] Jump[6,6,27] Trans[20,4] Zero[10] Trans[4,15] Jump[2,15,47] Succ[15] Succ[10] Jump[15,15,43] Trans[9,1] Trans[10,2]

EDIT: by removing brackes, and shortening instruction names:

URM 285

Z8 T2,11 J3,11,7 S11 S8 J11,11,3 Z5 T1,12 J2,12,13 S12 S5 J12,12,9 Z17 T8,13 J13,17,25 Z16 T5,14 J13,14,22 S14 S16 J14,14,18 S9 T16,13 J17,17,15 Z6 Z20 J9,6,40 Z7 T1,21 J20,7,36 S21 T21,19 T19,21 S7 J7,7,30 T21,18 T18,20 S6 J6,6,27 T20,4 Z10 T4,15 J2,15,47 S15 S10 J15,15,43 T9,1 T10,2

Per Alexandersson

Posted 2012-04-09T16:43:15.573

Reputation: 243

(+1) But ... "Non-negative and non-integer numbers are not handled" ... I think you mean to say that negative numbers are not handled. (The OP says all input & output is integer.) – r.e.s. – 2012-04-11T10:53:51.797

Ah, did not read that output was integer... – Per Alexandersson – 2012-04-11T11:07:00.670

Should I count this by character count or by the number of instructions? – PhiNotPi – 2012-04-11T13:20:56.510

Maybe count the characters in the edited version... – Per Alexandersson – 2012-04-11T20:32:31.023

2

Fortran 44

read*,i,j,k;k=(k-j)/(j-i);print*,k,j-i*k;end

Input will be in a single line (comma or space separated)

Cray Chapel 59

var i,j,k:int;read(i,j,k);k=(k-j)/(j-i);write(k," ",j-i*k);

Input will be on single line, no newline (add 2 chars for that by using writeln in place of write).

Golflua 44

r=I.r;a,b=r(),r();m=(r()-b)/(b-a);w(m,b-m*a)

Newline delimited input, space delimited output

Kyle Kanos

Posted 2012-04-09T16:43:15.573

Reputation: 4 270

2

Julia, 71 characters

Space delimited input and output.

i,j,k=int(split(readline(STDIN)));println("$(l=div(k-j,j-i)) $(j-i*l)")

Example input and output:

julia> i,j,k=int(split(readline(STDIN)));println("$(l=div(k-j,j-i)) $(j-i*l)")
5 -19 77
-4 1

Piet, 86 60 56 codels (14x4), codel size 10 for better visibility

I could actually shrink down the amount of codels by a whopping 35%. I didn’t expect such a good outcome. Coding this program backwards was, as I expected, quite successful. I doubt it can be shorter than this, but I would be really interested if anyone could find a smaller solution.

The challenge does not state if the program has to stop after showing the result, so my smallest (56 codel) program should be valid. It just loops back to the beginning after showing the result, asking for a new triplet of integers. Due to the tight packing there is no place for the output of two newline characters, but that is no problem with the npiet interpreter, because it always prints a ‘?’ if it awaits input.

There are two possible sizes to build a looped version, but a version that runs only once is only possible in a program that’s at least 64 codels (16x4) big. The versions below show the reason. Maybe it’s also interesting for those who are familiar with Piet.

The final, most tightly packed 56 codel version, with a loop:

Find Rule For A Series 56 codels

Second version (60 codels), with a loop

Find Rule For A Series 60 codels

If the 56 codel version is against the rules, here is the final 64 codel version, running only once:

Find Rule For A Series 64, run once

My first version (86 codels)

Find Rule For A Series 86 codels

Input and output are newline delimited.

Example input and output:

D:\codegolf\npiet-1.3a-win32>npiet ml_series.png
? 5
? -19
? 77
-4
1

For looped versions, looking a bit uglier:

D:\codegolf\npiet-1.3a-win32>npiet ml_series_56_codels.png"
? 5
? -19
? 77
-4
1? 5
? -19
? 77
-4
1? 5
? -19
? 77
-4
1?

I chose newline as delimiter because coding ASCII 10 (\n) obviously needs only 7 codels, compared to ASCII 32 ( ) which needs 8 codels or even ASCII 40 (,) which needs 9 codels.

Coding backwards from the result to the first input is a great way to reduce the codel use for ROL operations. The stack order at the beginning and at the end are known, the rest is easily done by hand.

Here is a text version of the 64 codel program (with stack), in my made-up shorthand. The shorter programs just don’t terminate but loop back to the beginning.

NOP ADD DIV GRT DUP INC END
 0   +   /   >   =   c   ~
PSH SUB MOD PTR ROL OUN
 X   -   %   #   @   N
POP MUL NOT SWI INN OUC
 ?   *   !   $   n   C

                   1
        1    1   2 2     1                   a,b,c: input for series
      5 5  3 3 c c cb  3 3                       D: c-b
    b b bb b bbb b bcD D Da                      E: b-a
   bb b bb b baa a aaa a abE F                   F: D/E, (c-b)/(b-a), mul. const.
  bbb b ba a abb b bbb b bDDFFF    5             G: a*F, a(c-b)/(b-a)
 aaaa a aa a aaa a aaa a aaaaaaG  55 10          H: b-G, b-a*F, add. const.
aaaaa a ab b bbb b bbb b bbbbbbbH HH  H H
n=n==5X1X@3X1X@n2X1X@-3X1X@-/=N*-5X=  + CN~
| |            |     |     || |||\____/ ||
| |            |     |     || |||  |    |+———— output add. const.
| |            |     |     || |||  |    +————— output newline character
| |            |     |     || |||  +—————————— 5 DUP + =10, ASCII for \n
| |            |     |     || ||+————————————— H, add. const.
| |            |     |     || |+—————————————— G
| |            |     |     || +——————————————— output mul. const.
| |            |     |     |+————————————————— F, mul. const.
| |            |     |     +—————————————————— E
| |            |     +———————————————————————— D
| |            +—————————————————————————————— input c
| +——————————————————————————————————————————— input b
+————————————————————————————————————————————— input a

M L

Posted 2012-04-09T16:43:15.573

Reputation: 2 865

2

Q, 36

{a,x[2]-x[1]*a:%[x[2]-x 1;x[1]-x 0]}

usage

q){a,x[2]-x[1]*a:%[x[2]-x 1;x[1]-x 0]}each(0 7 14;2 5 11;2 0 -4;5 -19 77)
1  7 
2  1 
2  -4
-4 1

tmartin

Posted 2012-04-09T16:43:15.573

Reputation: 3 917

1

MoonScript(48 chars, newline delimited input, space delimited output)

r=io.read
a,b=r!,r!
m=(r!-b)/(b-a)
print m,b-m*a

Felix(86 chars, newline delimited input, comma delimited output)

gen r()=>int $ readln stdin;
var a,b=r(),r();
var m=(r()-b)/(b- a);
println(m,b- m*a);

Julia(84 chars, space delimited input, space delimited output)

a,b,c=tuple(map(int,split(readline(STDIN)))...)
m=(c-b)/(b-a)
println("$m $(b-m*a)")

kirbyfan64sos

Posted 2012-04-09T16:43:15.573

Reputation: 8 730

Your Julia solution throws an error.

ERROR: BoundsError()
in indexed_next at tuple.jl:19 (repeats 2 times)
while loading d:\codegolf\series.jl, in expression starting on line 1
 – M L  – 2015-06-14T16:04:13.133

@ML That's weird. Might be something that changed in the newest version of Julia. I'll try it. – kirbyfan64sos – 2015-06-14T16:59:49.470

If I try it out in the console I get the error immediately after the first line. Somehow the line creates a tuple, that’s always (a,b,0)

If I include it via a .jl file then it creates the output, but throws the error if I press enter to get the Julia REPL back.

julia> include("happy_birthday_codegolf.jl")

5 -19 77

-4 1

ERROR: BoundsError() in indexed_next at tuple.jl:19 (repeats 2 times) while loading d:\codegolf\series.jl, in expression starting on line 1

Is there any way to insert line breaks in comments? Sorry for the mess. – M L – 2015-06-14T18:22:08.293

@ML Does putting it in a file and running it via julia file.jl give the same error? – kirbyfan64sos – 2015-06-14T18:26:31.073

I guess it’s not readable in my mess of an answer above. Yes, I tried both the console and including it via a .jl file. “If I include it via a .jl file then it creates the output, but throws the error if I press enter to get the Julia REPL back.” If I run your example via .jl file, then the program waits for some input before the julia> REPL/prompt comes back. – M L – 2015-06-14T19:43:05.850

Funny, now it works. But it spits out two float values instead of integers. julia> include("series.jl") / 5 -19 77 / -4.0 1.0 How about using div(a,b) instead of a/b? – M L – 2015-06-14T19:55:02.720

@ML I think at the time I wrote the program, Julia always used integer division. Maybe. I haven't been following the project too much lately. – kirbyfan64sos – 2015-06-14T21:21:32.113