A list of number modulus their indices in the list

25

A simple one: Take a list of positive integers as input and output the numbers modulus their 1-based index in the list.

If the input integers are {a, b, c, d, e, f, g} then the output should be {a%1, b%2, c%3, d%4, e%5, f%6, g%7} where % is the modulus operator.


Test cases:

10  9  8  7  6  5  4  3  2  1
 0  1  2  3  1  5  4  3  2  1

8 18  6 11 14  3 15 10  6 19 12  3  7  5  5 19 12 12 14  5
0  0  0  3  4  3  1  2  6  9  1  3  7  5  5  3 12 12 14  5

1
0

1  1
0  1

Stewie Griffin

Posted 2017-06-14T21:10:00.967

Reputation: 43 471

Answers

11

Haskell, 20 bytes

($[1..]).zipWith mod

Try it online!

A trick to flip I learned from a golf of Anders Kaseorg.

xnor

Posted 2017-06-14T21:10:00.967

Reputation: 115 687

9

Operation Flashpoint scripting language, 73 bytes

f={l=_this;r=[];i=0;while{i<count l}do{r=r+[(l select i)%(i+1)];i=i+1};r}

Call with:

numList = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
hint format["%1\n%2", numList, numList call f];

Output:

Steadybox

Posted 2017-06-14T21:10:00.967

Reputation: 15 798

1What... this is a thing? – JAD – 2017-06-15T12:35:47.850

2@JarkoDubbeldam Yes. The game allows players to create their own scenarios, and there is an in-game scripting language designed to supplement mission designing. However, since the language is Turing-complete, you can do pretty much whatever you want with it. – Steadybox – 2017-06-15T13:22:42.937

8

Python 2, 35 bytes

i=1
for x in input():print x%i;i+=1

Try it online!

Counts the index up manually, as per a tip of mine.

xnor

Posted 2017-06-14T21:10:00.967

Reputation: 115 687

1

If you can exit with an error (I forget if that's the default) you can shave a couple bytes.

– FryAmTheEggman – 2017-06-14T22:39:15.853

7

Jelly, 2 bytes

%J

Try it online!

Explanation:

%J
 J List 1 .. len(input). This is results in a list of the indexes.
%  Modulo.

Basically, the code modulos the original list by the list of indexes.

Comrade SparklePony

Posted 2017-06-14T21:10:00.967

Reputation: 5 784

2As soon as I saw this question, I thought "that's %J in Jelly, I wonder if anyone has answered with that answer?". I guess someone else had the same idea :-D – None – 2017-06-14T21:49:04.603

1@ais523 You think you were the only one? Think again! – Erik the Outgolfer – 2017-06-15T09:10:27.683

6

R, 27 bytes

x=scan();cat(x%%1:sum(1|x))

saved 5 bytes thanks to @Jarko

saved 4 more thanks to @Giuseppe

saved 2 more thanks to @Taylor Scott

Saved 2 more thanks to @returnbull

Zahiro Mor

Posted 2017-06-14T21:10:00.967

Reputation: 371

35 it is - removed unneeded last paren – Zahiro Mor – 2017-06-15T13:47:18.123

1you don't need the ' ' (space) at the end of cat; that's the default separator – Giuseppe – 2017-06-15T13:51:28.747

2you can drop 2 bytes to get 33 by reducing this down to x<-scan();cat(x%%1:length(x)," ") -- oh and a couple formatting tips, 1) you only need 4 spaces to the left of your code for it to be properly indented and marked 2) you can add a <!-- language-all: lang-r --> flag before your code to have it be highlighted (though this changes little in this example) 3) you do not need the brakets around your language's name 4) oh and you don't need to make a comment when you make edits to a post – Taylor Scott – 2017-06-15T13:57:26.680

2(1) You can use = instead of <- to save a byte.

(2) The specification says "output" rather than "print", so you can probably drop the cat(), saving 5 bytes.

(3) sum(1|x) is one byte shorter than length(x). – rturnbull – 2017-06-16T13:51:14.220

6

R, 24 18 bytes

pryr::f(x%%seq(x))

Evaluates to the function:

function (x) 
x%%seq(x)

Which uses seq_along() to create a vector of the same length as x, starting at 1, and then %% to take the modulo.

Default behaviour of seq when presented with a vector is seq(along.with = x) which is the same output as seq_along(x), but 6 bytes shorter.

JAD

Posted 2017-06-14T21:10:00.967

Reputation: 2 898

seq(x) is a handy thing to have around, since I'm always using 1:length(x). – Giuseppe – 2017-06-15T14:08:29.167

@Giuseppe Yeah I was kinda surprised as well. – JAD – 2017-06-15T14:13:10.190

5

05AB1E, 2 bytes

ā%

Try it online! or Try all tests

ā  # Push the range(1, len(a) + 1)
 % # Mod each element in the input by the same one in this list

Riley

Posted 2017-06-14T21:10:00.967

Reputation: 11 345

Interesting, I thought it'd be like DgL%, nice. – Magic Octopus Urn – 2017-06-16T21:07:43.013

@carusocomputing I originally had gL% because I forgot about ā. – Riley – 2017-06-16T21:57:22.450

mind going a bit more in-depth on ā for me? I believe I've never used it is it just like for each but in a 1 to n+1 manner like vy<code>}) but implied vy<code>})? – Magic Octopus Urn – 2017-06-16T21:58:54.203

@carusocomputing it pushes an array with values 1 to the length of the popped array. It's equivalent to gL. TIO

– Riley – 2017-06-16T22:04:20.743

Does it also dupe the input? Or is implicit input now extended automatically to the closest available input? – Magic Octopus Urn – 2017-06-16T22:06:47.643

@carusocomputing Any time something is popped and the stack is empty it will use the next item from the input and keep returning the last item when it runs out of input. – Riley – 2017-06-16T22:13:08.177

5

APL (Dyalog), 5 bytes

⍳∘≢|⊢

Try it online!

 the indices

 of

 the length of the argument

| that modulus

 the argument

Adám

Posted 2017-06-14T21:10:00.967

Reputation: 37 779

Always amazed that a "mainstream" language can be so economical. The APL way seems naturally to be code golf: e.g. (~T∊T∘.×T)/T←1↓⍳R ⍝ primes up to R or life←{↑1 ω∨.∧3 4=+/,¯1 0 1∘.⊖¯1 0 1∘.⌽⊂ω} ⍝ Game of Life – None – 2017-06-14T22:27:06.633

@YiminRong You can do better: Primes to R: (⊢~∘.×⍨)1↓⍳R and GoL (in Version 16.0): K∊⍨⊢∘⊂⌺3 3 where K is a constant. – Adám – 2017-06-14T22:31:41.047

@YiminRong Try the primes finder here!

– Adám – 2017-06-14T22:32:33.587

5

Cubix, 19 bytes

;ww.1I!@s%Ow;)Sow.$

Try it online!

    ; w
    w .
1 I ! @ s % O w
; ) S o w . $ .
    . .
    . .

Watch It Run

A fairly straight forward implementation.

  • 1 push 1 to the stack to start the index
  • I!@ get the integer input and halt if 0
  • s%Ow swap the index up, mod, output result and change lane
  • ;) remove result and increment index
  • Sow push 32, output space and change lane (heading down from o)
  • $O jump the output
  • w;w change lange, remove 32 from stack and change lane onto the I input

MickyT

Posted 2017-06-14T21:10:00.967

Reputation: 11 735

4

Mathematica, 22 bytes

#&@@@Mod~MapIndexed~#&

One more Mathematica approach.

Martin Ender

Posted 2017-06-14T21:10:00.967

Reputation: 184 808

1MapIndexed@Mod is almost good enough :'( – ngenisis – 2017-06-14T22:39:42.633

4

MATL, 4, 3 bytes

tf\

Try it online!

One byte saved thanks to @LuisMendo!

James

Posted 2017-06-14T21:10:00.967

Reputation: 54 537

4

Starry, 75 70 bytes

      +`  , + +   *    +  + +      +*   +    *  .               + + .'

Try it online!

Explanation

This is an infinite loop that keeps reading numbers from the input and increasing a counter initiallized at 1. For each pair of input and counter, the modulus is computed and printed.

To end the loop when input has been exhausted, the following trick is used. When no more input is available, trying to read one more number gives a 0. Thus, we divide the read number by itself, and if it is 0 the program ends with an error. Else we discard the result and continue.

      +              Push 1. This is the initial value of the counter
`                    Mark label
  ,                  Read number from input and push it. Gives 0 if no more input
 +                   Duplicate top of the stack
 +                   Duplicate top of the stack
   *                 Pop two numbers and push their division. Error if divisor is 0
    +                Pop (discard) top of the stack
  +                  Swap top two numbers
 +                   Duplicate top of the stack
      +              Push 1
*                    Pop two numbers and push their sum. This increases the counter
   +                 Rotate stack down, to move increased counter to bottom
    *                Pop two numbers and push their modulus
  .                  Pop a number and print it as a number
               +     Push 10
 +                   Duplicate top of the stack
 .                   Pop a number (10) and print it as ASCII character (newline)
'                    If top of the stack is non-zero (it is, namely 10) go to label

Luis Mendo

Posted 2017-06-14T21:10:00.967

Reputation: 87 464

3

Brachylog, 9 bytes

l⟦₁;?↔z%ᵐ

Try it online!

Explanation

l⟦₁          [1, ..., length(Input)]
   ;?↔z      Zip the Input with that range
       %ᵐ    Map mod

Fatalize

Posted 2017-06-14T21:10:00.967

Reputation: 32 976

3

Japt, 5 4 bytes

®%°T

Try it


Explanation

     :Implicit input of array U
®    :Map over the array
%    :Modulo of the current element
°T   :T (0, initially) incremented by 1

Shaggy

Posted 2017-06-14T21:10:00.967

Reputation: 24 623

1I think you can save a byte with ®%°T (actually, you could still use Y there if you wanted) – ETHproductions – 2017-06-15T11:00:10.293

Aha. Thanks, @ETHproductions. – Shaggy – 2017-06-15T11:02:13.713

3

R, 22 bytes

pryr::f(x%%1:sum(x|1))

R performs 1:length(x) before doing the modulus.

Shayne03

Posted 2017-06-14T21:10:00.967

Reputation: 347

Nice find with sum(x|1)! – JAD – 2017-06-15T12:51:01.503

1Just found out that using seq() instead of seq_along() does the same thing. So that is a few bytes shorter again. – JAD – 2017-06-15T13:02:07.100

1I was going to tell you that, but I didn't have the rep to comment. Glad you figured it out. – Shayne03 – 2017-06-15T13:12:04.863

2

Python 2, 42 bytes

lambda l:[v%(i+1) for i,v in enumerate(l)]

Try it online!

totallyhuman

Posted 2017-06-14T21:10:00.967

Reputation: 15 378

You can remove the space before the for – Beta Decay – 2017-06-14T21:19:39.087

41 bytes: lambda l:[v%-~i for i,v in enumerate(l)] – ovs – 2017-06-14T21:24:32.153

2Or, lambda l:[v%i for i,v in enumerate(l,1)]. – xnor – 2017-06-14T21:26:42.337

2

Mathematica, 21 bytes

#~Mod~Range@Length@#&

Try it online!

or 20 bytes (by Martin)

#~Mod~Range@Tr[1^#]&

J42161217

Posted 2017-06-14T21:10:00.967

Reputation: 15 931

Tr[1^#] for Length@#. – Martin Ender – 2017-06-14T21:33:37.237

that one doesn't work on mathics, so I'm keeping them both – J42161217 – 2017-06-14T21:40:44.253

You are missing a # as the second last character in your first answer. – Ian Miller – 2017-06-15T00:26:48.457

2

Haskell, 22 bytes

zipWith(flip mod)[1..]

Try it online!

Also: flip(zipWith mod)[1..].

nimi

Posted 2017-06-14T21:10:00.967

Reputation: 34 639

2

Excel VBA, 59 46 Bytes

Golfed

Anonymous VBE Immediate window funtion that takes a space ( ) delimited array string as input from range [A1] and output the numbers modulus their 1-based index in the starting list to the VBE immediate window

For Each n In Split([A1]):i=i+1:?n Mod i;:Next

Input / Output:

[A1]="10 9 8 7 6 5 4 3 2 1" ''# or manually set the value
For Each n In Split([A1]):i=i+1:?n Mod i;:Next
 0  1  2  3  1  5  4  3  2  1 

Old Subroutine version

Subroutine that takes input as a passed array and outouts to the VBE immediate window.

Sub m(n)
For Each a In n
i=i+1
Debug.?a Mod i;
Next
End Sub

Input / Ouput:

m Array(10,9,8,7,6,5,4,3,2,1)
 0  1  2  3  1  5  4  3  2  1 

Ungolfed

Option Private Module
Option Compare Binary
Option Explicit
Option Base 0 ''# apparently Option Base 1 does not work with ParamArrays

Public Sub modIndex(ParamArray n() As Variant)
    Dim index As Integer
    For index = LBound(n) To UBound(n)
        Debug.Print n(index) Mod (index + 1);
    Next index
End Sub

Input / Output:

Call modIndex(10,9,8,7,6,5,4,3,2,1)
 0  1  2  3  1  5  4  3  2  1 

Taylor Scott

Posted 2017-06-14T21:10:00.967

Reputation: 6 709

1

CJam, 9 bytes

{_,,:).%}

Anonymous block that expects an array on the stack and replaces it by the output array.

Try it online!

Explanation

{       }    e# Define block
 _           e# Duplicate
  ,          e# Length
   ,         e# Range, 0-based
    :)       e# Add 1 to each entry
      .%     e# Vectorized modulus

Luis Mendo

Posted 2017-06-14T21:10:00.967

Reputation: 87 464

1

J, 9 bytes

>:@i.@#|[

1 ... n | original list

| is mod

Jonah

Posted 2017-06-14T21:10:00.967

Reputation: 8 729

1

C, 52 bytes

i;f(n,l)int*l;{for(i=0;i++<n;)printf("%d ",*l++%i);}

Try it online!

Steadybox

Posted 2017-06-14T21:10:00.967

Reputation: 15 798

1

JavaScript (ES6), 22 bytes

a=>a.map((x,y)=>x%++y)

Shaggy

Posted 2017-06-14T21:10:00.967

Reputation: 24 623

1

AWK, 13

{print $1%NR}

Try it online.

Digital Trauma

Posted 2017-06-14T21:10:00.967

Reputation: 64 644

1

tcl, 35

lmap l $L {puts [expr $l%[incr i]]}

demo

sergiol

Posted 2017-06-14T21:10:00.967

Reputation: 3 055

1

GNU APL 1.2, 9 bytes

(⍳⍴R)|R←⎕

APL operates from right to left, hence the parentheses.

R←⎕ assigns user input to vector R.

⍴R gives the length of the vector; ⍳⍴R gives a vector with all numbers from 1 to that length (so the indices).

| is the mod operator (a|b yields b%a). APL operates on arrays, so the code snippet a vector containing each element from the user's input mod its index.

Arc676

Posted 2017-06-14T21:10:00.967

Reputation: 301

1

Pari/GP, 22 bytes

a->[a[n]%n|n<-[1..#a]]

Try it online!

alephalpha

Posted 2017-06-14T21:10:00.967

Reputation: 23 988

1

Pyth, 5

.e%bh

Online test.

    hk     # 1-based index of (implicit) lambda variable
   b       # element
  %        # element mod (1-based index)
.e    Q    # enumerated map over (implicit) input

Digital Trauma

Posted 2017-06-14T21:10:00.967

Reputation: 64 644

1

Octave, 19 bytes

@(n)mod(n,1:nnz(n))

Try it online!

An anonymous function that takes n as input, and performs element-wise modulus with the list 1, 2, 3.

Stewie Griffin

Posted 2017-06-14T21:10:00.967

Reputation: 43 471

1

Braingolf, 18 bytes

V1R&,{v.m1+v%}&,=;

Try it online!

Explanation

V1R&,{v.m1+v%}&,=;  Implicit input from commandline args
V1R                 Create stack2, push 1 to it, and return to stack1
   &,               Reverse stack1
     {.......}      Foreach loop, runs for each item in stack1
      v             Switch to stack2
       .m           Duplicate last item on stack and move duplicate to stack1
         1+         Increment last item on stack
           v%       Return to stack1, pop last 2 items and push modulus result
              &,    Reverse stack1
                =   Output stack1
                 ;  Suppress implicit output

Skidsdev

Posted 2017-06-14T21:10:00.967

Reputation: 9 656

1

Java 8 / C#, 39 bytes

a->{for(int i=0;i<a.length;a[i]%=++i);}

Try it here.

Also works in C# by replacing -> with => and length with Length:

a=>{for(int i=0;i<a.Length;a[i]%=++i);}

Try it here.

Explanation:

a->{                       // Method with integer-array parameter and no return-type
  for(int i=0;i<a.length;  //  Loop over the indexes of the array (0-indexed)
      a[i]%=++i            //   And replace every integer with itself mod (1+i)
  );                       //  End of loop
}                          // End of method

Modifies the input-array, hence the lack of a return.

Kevin Cruijssen

Posted 2017-06-14T21:10:00.967

Reputation: 67 575

1Essentially what I'd do in C# +1, could also comment about it working for C# too if you change -> to => and capitaliselength. – TheLethalCoder – 2017-06-15T08:22:44.803

1

Ruby, 25 bytes

->x{x.map{|y|$.+=1;y%$.}}

Try it online!

ymbirtt

Posted 2017-06-14T21:10:00.967

Reputation: 1 792

1

Common Lisp, 57 bytes

(defun m(l &aux(i 0))(mapcar(lambda(x)(mod x(incf i)))l))

Try it online!

Renzo

Posted 2017-06-14T21:10:00.967

Reputation: 2 260

1

Perl 6, 7 bytes

*Z%1..*

Test it

Expanded:

*      # WhateverCode lambda (this is the parameter)
Z[%]   # zipped using infix modulus operator (&infix:«%»)
1 .. * # Range starting from 1 (doesn't stop)

Brad Gilbert b2gills

Posted 2017-06-14T21:10:00.967

Reputation: 12 713

0

Python 3, 46 bytes

lambda x:[0]+[x[i]%i for i in range(1,len(x))]

Simples ;)

Beta Decay

Posted 2017-06-14T21:10:00.967

Reputation: 21 478

Shouldn't it be range(1,len(x)+1)? But then you're better off doing range(len(x)) and doing lambda x:[x[i]%-~i for i in range(len(x))]. – Erik the Outgolfer – 2017-06-15T09:17:34.503

@EriktheOutgolfer Well you could do that if you want an IndexError... – Beta Decay – 2017-06-15T09:39:42.713

Does not raise any error for me. – Erik the Outgolfer – 2017-06-15T09:43:27.807

Oh, and your solution, including my golf, is also compatible with Python 2. – Erik the Outgolfer – 2017-06-15T09:44:32.087

0

Go, 68 bytes

Go isn't hopelessly defeated (kinda is, but nvm that) because it has that nice range which is the equivalent of Python's enumerate().

func f(l[]int)(r[]int){for i,v:=range l{r=append(r,v%(i+1))};return}

Try it online!

totallyhuman

Posted 2017-06-14T21:10:00.967

Reputation: 15 378

0

PHP, 37 bytes

<?foreach($_GET as$v)echo$v%++$k." ";

Try it online!

Output separeted by an underscore

PHP, 35 bytes

<?foreach($_GET as$v)echo$v%++$k,_;

Try it online!

Jörg Hülsermann

Posted 2017-06-14T21:10:00.967

Reputation: 13 026

0

Python, 41 bytes

f=lambda l,i=1:l and[l[0]%i]+f(l[1:],i+1)

Try it online!

A recursive solution. One byte longer than using enumerate. Other attempts:

f=lambda l,i=1:l and[l.pop(0)%i]+f(l,i+1)
f=lambda l,i=0:l[i:]and[l[i]%-~i]+f(l,i+1)
f=lambda l:l and f(l[:-1])+[l[-1]%len(l)]

The last one really wants to use pop but the order of evaluation is wrong.

xnor

Posted 2017-06-14T21:10:00.967

Reputation: 115 687

Save five bytes by printing with def f(a,m=1):print a[m-1]%m;f(a,m+1), but I see that still does not beat your 35 byte full program solution. – Jonathan Allan – 2017-06-14T22:09:02.773

0

Perl 6, 18 bytes

{map (*+1)R%*,.kv}

Accepts the list as its sole argument.

Sean

Posted 2017-06-14T21:10:00.967

Reputation: 4 136

0

Perl6, 22 21 bytes

say $_%++$ for @*ARGS

And a more readable version:

# Store initial index state
# The "++$" in the golf version increments an anonymous state variable for this.
my $index = 0;
# Iterate over the command-line arguments
for @*ARGS -> $number {
    # Increment the current index
    $index++;
    # Print out the result for this element
    say $number % $index;
}

Usage:

perl6 whatever-you-named-it.p6 [space-separated numbers go here]

Note that if we don't need to actually print the output, we can remove the initial say, saving 4 bytes to bring the total down to 17.

Daria

Posted 2017-06-14T21:10:00.967

Reputation: 1

0

k, 12 bytes

{(1+!#x)!'x}

Try it online.

zgrep

Posted 2017-06-14T21:10:00.967

Reputation: 1 291

0

Aceto, 12 bytes

%pLI
ILOM
ri

It's a bit hard to see because there's no line break after the result is printed. Input is taken one number at a time, seperated by linebreaks.

Explanation:

Read a line and cast it to an integer:

ri

Load quick storage (initially an empty string) and increment it (autocasts to int; --> 1)

IL

Calculate and print modulo, load quick storage again, increment and save it:

%pLI
   M

Go back to the start:

  O

Example in- and output:

10
0
9
1
8
2
7
3
6
1
5
5
4
4
3
3
2
2
1
1

For one byte the output can look nicer:

%pLI
ILnM
riO

L3viathan

Posted 2017-06-14T21:10:00.967

Reputation: 3 151

0

Actually, 6 bytes

;ru@♀%

Try it online!

Explanation:

;ru@♀%
;ru     push [1, len(L)]
   @♀%  modulo of pairs from each list ([L[0]%1, L[1]%2, ...])

Mego

Posted 2017-06-14T21:10:00.967

Reputation: 32 998

0

Ruby, 40 bytes

->q{q.each_with_index.map{|n,i|n%(i+1)}}

marmeladze

Posted 2017-06-14T21:10:00.967

Reputation: 227

0

Swift 4, 18 bytes

zip(a,1...).map(%)

Alexander - Reinstate Monica

Posted 2017-06-14T21:10:00.967

Reputation: 481

0

Clojure, 25 bytes

#(map mod %(rest(range)))

(range) generates an infinite sequence of integers starting from 0, rest drops the first, and mapping with multiple sequences applies the operation to corresponding elements (and stops with the shorter sequence).

MattPutnam

Posted 2017-06-14T21:10:00.967

Reputation: 521

0

jq, 28 characters

to_entries[]|.value%(.key+1)

Sample run:

bash-4.4$ jq 'to_entries[]|.value%(.key+1)' <<< '[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]'
0
1
2
3
1
5
4
3
2
1

Try in jq‣play

For +5 characters you can enclose all the code in brackets and ask for compact output to get JSON output. But that not seems to be required.

manatwork

Posted 2017-06-14T21:10:00.967

Reputation: 17 865

0

NewStack, 3 bytes

ᵢ%ṅ

The breakdown:

ᵢ    Append user's input to the stack
 %ṅ  Mod stack by 1-based index of each element

Graviton

Posted 2017-06-14T21:10:00.967

Reputation: 2 295