text:
Double, XOR and do it again
We define the function g as g(n) = n XOR (n * 2) for any integer n > 0.
Given x > 0, find the smallest integer y > 0 such that gk(y) = x for some k > 0.
Example
x = 549

549 = 483 XOR (483 * 2)     (as binary: 1000100101 = 111100011 XOR 1111000110)
483 = 161 XOR (161 * 2)     (as binary:  111100011 =  10100001 XOR  101000010)

Which means that g2(161) = 549. We can't go any further, as there is no n such that g(n) = 161. So, the expected output for x = 549 is y = 161.
Rules

You are not supposed to support invalid entries. A pair (y, k) is guaranteed to exist for the input value x.
This is code-golf, so the shortest answer in bytes wins!

Test cases
     3 -->     1
     5 -->     1
     6 -->     2
     9 -->     7
    10 -->     2
    23 -->    13
    85 -->     1
   549 -->   161
   960 -->    64
  1023 -->   341
  1155 -->   213
  1542 -->     2
  9999 -->  2819
 57308 --> 19124
 57311 -->   223
983055 -->     1

Related OEIS: A048274 which is the sequence a(n) = g(n)

Java 8, 68 57 53 52 bytes
n->{for(int i=0;i<n;)i-=(i*2^i)==n?n=i:-1;return n;}

-5 bytes thanks to @OlivierGrégoire.
Try it online.
Explanation:
n->{                 // Method with integer as both parameter and return-type
  for(int i=0;i<n;)  //  Loop `i` in the range (1,n)
    i-=(i*2^i)==n?   //   If `i*2` XOR-ed with `i` equals `n`
        n=i          //    Set `n` to `i`, and set `i` to 0 to reset the loop
       :             //   Else:
        -1;          //    Increase `i` by 1 to go to the next iteration
  return n;}         //  Return `n` after the entire loop

n->{for(int i=0;i<n;)i-=(i*2^i)==n?n=i:-1;return n;} (52 bytes). Sorry ^^'

@OlivierGrégoire Even smarter, thanks!

for(int i=0;n>i-=i+i^i^n?-1:n=i;);?

@Titus I'm afraid that's not going to work in Java (although I have used that approach in my iterative JavaScript answer). In Java i+i^i^n? is not a boolean, so it won't even compile. In addition, n>i-=... will need parenthesis (n>(i-=...)), and n=i isn't allowed in the else-clause of the ternary-if, only in the if-clause (this last one I don't know why, but that's what it is in Java unfortunately).

@KevinCruijssen "and n=i isn't allowed in the else-clause of the ternary-if". Because Java would parse it as (i-=(i*2^i)!=n?-1:n)=i which is illegal.

@OlivierGrégoire Ah, so that's why. Still, that's pretty stupid.. When would (contains_ternary_if)=i ever be valid to begin with. Java should just parse it differently imho.

Python 2, 54 53 bytes
f=lambda n:next((f(i)for i in range(n)if n==i^i*2),n)

Try it online!

JavaScript, 53 bytes
f=x=>(i=0,y=(G=x=>x&&(i^=x&1)+2*G(x>>1))(x),i?x:f(y))

G is g^-1, which set i to 0 if success, set i to 1 if failed.

This was the approach I tried to use although I came up with a 50-byte version: f=n=>(g=n=>n<2?0/!n:n%2+2*g(n/2^n%2))(n)?f(g(n)):n. Sadly the boring approach is 12 bytes shorter.

Pyth, 13 12 10 bytes
Saved 1 byte thanks to @MrXcoder, and 2 more bytes following their suggestion
fqQ.W<HQxy

Try it online
Explanation:
fqQ.W<HQxyZZT   Implicit: Q=eval(input()), trailing ZZT inferred

f               Return the first T in [1,2,3...] where the following is truthy
   .W       T     Functional while - loop until condition is true, starting value T
     <HQ            Condition: continue while iteration value (H) less than input
        xyZZ        Body: xor iteration value (Z) with double (y) iteration value (Z)
 qQ               Is the result of the above equal to input?

You can drop the trailing T for 12 bytes.

R, 73  65 bytes
f=function(x){for(i in 1:x)if(x==bitwXor(i,i*2)){i=f(i);break};i}

Try it online!
Thanks a lot Giuseppe (-8) due to your tweaks, so simple yet very effective

as opposed to a previous answer of yours, because this function is recursive, you do need the f= since the function needs to be bound to f to work properly. That being said, nice work, and take a +1 from me!

you can also do some re-jiggering of your logic and get this to 65 bytes

JavaScript, 38 36 bytes
f=(n,x=n)=>x?x^x+x^n?f(n,--x):f(x):n

Try it online - Starts throwing overflow errors somewhere between 9999 & 57308.

Jelly, 8 7 bytes
Use ⁺¿ to return the last non-zero element (thanks Dennis for -1 byte)
^Ḥ)i$⁺¿

Try it online!
Brute force wins again :(

^Ḥ)i$⁺¿ saves a byte.

And it's 2x slower.

C (gcc), 57 56 55 51 bytes

Saved a byte thanks to ceilingcat; != ~ -.
Saved a byte five bytes thanks to Rogem; making use of the ternary expression and gcc quirks.

X(O,R){for(R=1;R;O=R?R:O)for(R=O;--R&&(R^2*R)-O;);}

Try it online!

for(R=1;R;O=R?R:O) saves a byte.

R=O; at the end seems to be unnecessary, saving you another 4 bytes.

Z80Golf, 22 bytes
00000000: 1600 1803 4216 007a b830 097a 82aa b828  ....B..z.0.z...(
00000010: f314 18f3 78c9                           ....x.

Port of @KevinCruijssen's Java answer
Example with input of 9-Try it online!
Example with input of 85-Try it online!
Assembly:
;d=loop counter
;b=input and output
f:
	ld d,0
	jr loop
	begin:
	ld b,d
	ld d,0
	loop:
		ld a,d
		cp b
		jr nc,end	; if d==b end
		ld a,d
		add d		; mul by 2
		xor d
		cp b
		jr z,begin	; if (d*2)^d==b set b to d
		inc d
		jr loop
	end:
	ld a,b
	ret

Assembly example for calling the function and printing the result:
ld b,9 ; input to the function, in this case 9
call f
add 30h ; ASCII char '0'
call 8000h ; putchar
halt

If you make a the loop counter instead of d, then you can replace the ld d,0 instructions by xor a both times, which saves two bytes.

JavaScript (Node.js), 48 45 38 bytes
f=(n,i=0)=>i<n?i*2^i^n?f(n,i+1):f(i):n

-7 bytes thanks to @Neil creating a recursive version of my iterative version below. Doesn't work for large test cases.
Try it online.

Iterative 45 bytes version that works for all test cases:
n=>{for(i=0;i<n;)i-=i*2^i^n?-1:n=i;return n;}

Port of my Java answer.
-3 bytes thanks to @Arnauld.
Try it online.

You can do i-=i*2^i^n?-1:n=i (but unfortunately not in Java).

@Arnauld Figured something was possible for the boolean in Java to just 1 in JS. Thanks!

38 bytes written recursively (doesn't work for larger inputs): f=(n,i=0)=>i<n?i*2^i^n?f(n,i+1):f(i):n

Jelly, 11 9 bytes
BÄḂṛḄß$Ṫ?

Try it online!
Tips: Use recursive function instead of loops.

Very fast, unfortunately loses to the brute force approach.
Note that:

For x > 0, f(x) > x.
popcount(f(x)) is even, where popcount(n) is the number of bits set in n.
If n has even popcount, then there exists x such that  f(x) = n.
Let B(x) be the binary representation of x, and Ṗ(l) be the list l with last element removed. Then B(x) is the accumulated XOR of Ṗ(B(f(x))).

So, we repeatedly:

Compute its binary representation (B)
then take the accumulated XOR (use ^\ or ÄḂ, they have the same effect).
Check if (?) the tail (last element) (Ṫ) of the accumulated XOR is nonzero (odd popcount)

If so, convert the binary list back to decimal and recurse.
If not, returns the input (ṛ).

9 bytes: B^\⁸Ḅß$Ṫ?

K (ngn/k), 32 26 bytes
{$[*|a:2!+\2\x;x;2/-1_a]}/

Try it online!
{ } is a function with argument x
/ applies it until convergence
$[ ; ; ] if-then-else
2\x binary digits of x (this is specific to ngn/k)
+\ partial sums
2! mod 2
a: assign to a
*| last - reverse (|) and get first (*)
if the above is 1, x will be returned
otherwise:
-1_a drop the last element of a
2/ decode binary

Java (JDK 10), 78 bytes
int g(int n){return f(n)%2<1?g(f(n)/2):n;}int f(int x){return 1>x?0:x^f(x/2);}

Try it online!

JavaScript (Node.js), 40 bytes
f=n=>g(n)%2?n:f(g(n)/2)
g=x=>x&&x^g(x/2)

Try it online!
Thanks Shaggy for -1 bytes.
Port of my Jelly answer.
Finally there is a language where this approach is shorter (oops). (I tried Python and Java, it doesn't work)
Can anyone explain why I can use /2 instead of >>1?

x/2 works because of arithmetic underflow. Any IEEE 754 number will eventually be evaluated as 0 when divided by 2 enough times. (And the decimal part is simply ignored when XOR'd, so this does not affect the result.)

40 bytes

@Shaggy Surprised that it works. I know it works for Python and Lua etc., but not Javascript.

The false returned on the last iteration is implicitly cast to 0 by the bitwise XOR operator.

@Shaggy In fact, no false is involved. JS && behaves almost identically to Python/Lua and.

Ruby, 39 bytes
f=->x,y=x{y<1?x:x==y^y*2?f[y]:f[x,y-1]}

Try it online!
As expected for the recursive version, complains about "stack level too deep" on the latter test cases.

Forth (gforth), 71 bytes
: f 0 begin 2dup dup 2* xor = if nip 0 else 1+ then 2dup < until drop ;

Try it online!
Explanation
0                 \ add an index variable to the top of the stack
begin             \ start an indefinite loop
  2dup            \ duplicate the top two stack items (n and i)
  dup 2* xor =    \ calculate i xor 2i and check if equal to n
  if nip 0        \ if equal, drop n (making i the new n) and use 0 as the new i
  else 1+         \ otherwise just increment i by 1
  then            \ end the if-statement
  2dup <          \ duplicate the top two stack items and check if n < i
until             \ if previous statement is true, end the loop
drop              \ drop i, leaving n on top of the stack

Perl 6, 44 bytes
{({first {($^a+^2*$a)==$_},^$_}...^!*).tail}

Try it
Expanded:
{  # bare block lambda with implicit parameter $_

  (
    # generate a sequence

    # no need to seed the sequence with $_, as the following block will
    # default to using the outer $_
    # $_,

    { # parameter $_

      first
        {  # block with placeholder parameter $a

          ( $^a +^ 2 * $a ) # double (numeric) xor
          == $_             # is it equal to the previous value
        },

        ^$_  # Range up to and excluding the previous value ( 0..^$_ )
    }

    ...^  # keep doing that until: (and throw away last value)

    !*    # it doesn't return a trueish value

  ).tail  # return the last generated value
}

Prolog (SWI), 44 bytes
A-R:-between(1,A,B),A is B xor(B*2),B-R;R=A.

Try it online!

PHP, 49 bytes
Based on Kevin Cruijssen's answers.
for($x=$argn;$x>$i-=$i*2^$i^$x?-1:$x=$i;);echo$x;

Run as pipe with -nr or try it online.

F#, 92 bytes
let rec o i=
 let r=Seq.tryFind(fun x->x^^^x*2=i){1..i-1}
 if r.IsNone then i else o r.Value

Try it online!
Recursively checks through the numbers from 1 to i-1. If there's a match, check for a smaller for that number. If there's no match, return the input number.

C, 62 bytes
Based on Kevin Cruijssen's Java:
int n(int j){for(int i=0;i<j;)i-=(i*2^i)==j?j=i:-1;return j;}
To test:
#include <stdio.h>
int n(int j);
#define p(i) printf("%6d --> %5d\n", i, n(i))
int main(void)
{
    p(3);
    p(5);
    p(6);
    p(9);
    p(10);
    p(23);
    p(85);
    p(549);
    p(960);
    p(1023);
    p(1155);
    p(1542);
    p(9999);
    p(57308);
    p(57311);
    p(983055);
}

When run, the test program outputs:
     3 -->     1
     5 -->     1
     6 -->     2
     9 -->     7
    10 -->     2
    23 -->    13
    85 -->     1
   549 -->   161
   960 -->    64
  1023 -->   341
  1155 -->   213
  1542 -->     2
  9999 -->  2819
 57308 --> 19124
 57311 -->   223
983055 -->     1

C, 54 bytes
Only works with C89 or K&R C:
n(j){for(i=0;i<j;)i-=(i*2^i)==j?j=i:-1;return j;}

int n(int j){for(int i=0;j>i-=i*2^i^j?-1:j=i;);return j;} Do these 57 bytes work?

Wolfram Language (Mathematica), 58 bytes
Min[{#}//.x_:>Select[Range@#,MemberQ[x,#|BitXor[#,2#]]&]]&

Try it online!
Starts with a list containing just the input. Iteratively replaces the list by all integers that are either already in it, or map into it by the double-and-xor operation. Then //. says to do this until reaching a fixed point. The answer is the least element of the result.


text:
Get duplicates from an array
So, I have an array
['a', 42, 'b', 42, 'a']

I want to alert users to the fact that 42 and 'a' appear in it twice.
some_function(['a', 42, 'b', 42, 'a'])

should return
['a', 42]

Write some code to extract the duplicates from an array.

It should accept an array as input.
The array can have multiple types of object.
Duplication should be defined as per the language's standard equality function (examples are from ruby).
It outputs an array of the duplicated items.
The order of the returned items is irrelevant.
Duplicates should only appear in the returned array once.
Golf rules, do it in the smallest number of bytes.

Test cases
[1,2,3] => []

[1,2,3,2,1] => [1,2]

[1.0, 2, 2.0, 1.0] => [1, 2] or [1.0, 2.0] or [1, 2.0] or [1.0, 2]

[1, '1', '1.0'] => []

[nil, nil, false, false, true, true] => [nil, false, true]

Can the array have other arrays in it?

Suggested test case: [1, 1, 1, 2, 2] , so that one element is repeated more than once

"The array can have multiple types of object." Is this intended to exclude languages that do not allow arrays to have more than one type of object?

[1.0, 2, 2.0, 1.0] could be interpreted as having only one duplicate: 1.0, if one considers the integer 2 and which might be a non-integer 2.0 to be not equal. Since this is intended to allow for different types.

"standard equality function" seems hard to define, and will probably lead to different results in different languages.

@ngm There's no doubt about it, results will vary by language, particularly with cross-type checking. I noted that in the question, also that my test cases are results belong to Ruby, which has duck typing and some cross-type equality rules.

Some languages have more than one equality function (for example: Java have Object.equals and ==, JS have === and ==, Python have == and is, and it's 100% opinion-based which one is more "standard").

Some older possible-duplicate-targets: Non Unique Elements -- problem: allow snippet, which is normally not allowed; Removing unique elements from string -- problem: limit possible languages.

Python 2, 39 38 bytes
lambda l:{v for v in l if~-l.count(v)}

Try it online!

Python 3, 37 bytes
lambda l:[*map(l.remove,{*l})]and{*l}

Try it online!

Brachylog, 9 bytes
ọ{tℕ₂&h}ˢ

Try it online!
Explanation
ọ           Occurrences
 {     }ˢ   Select:
     &h       The elements…
  tℕ₂         …which occur at least 2 times

05AB1E, 8 bytes
{γʒg≠}€н

Try it online!
Explanation
{γ       # Sort input and split into chunks of identical elements
  ʒg≠}   # Keeps chunks of length != 1
      €н # Map with the first element of each chunk

Wow! That output really takes you through the stages of the process.

@AJFaraday I left the -d argument by accident but it's an amazing tool to understand what happens on the stack when you're learning 05AB1E :-)

I'm beginning to understand how you could actually learn such a language ;)

Not sure if it's a valid output format with the empty item present, but 6 bytes. Maybe you see something to golf or pretty-print it and still save bytes?

@KevinCruijssen That's an interesting take. I'm not quite sure it's a valid output (none of the other answers are leaving empty items in the array). You could add õK at the end to remove those empty arrays (only solution AFAIK to remove empty items from an array) but you'd end up at 8 bytes as well.

@Kaldo Yeah, I was afraid removing the empty items would be at least 2 bytes. And I doubt any of the other parts can be shorter with this approach. Ah well, will post it as an alternative solution in that case.

Pyth, 5 bytes
{.-Q{

Try it here!
How it works?

{.-Q{ – Full program.
    { – Deduplicate.
 .-Q  – And apply bagwise subtraction between the input Q and the above.
{     – Deduplicate the result.

Javascript ES6, 48 bytes
a=>[...new Set(a.filter((b,c)=>a.indexOf(b)<c))]

Test cases

f=
a=>[...new Set(a.filter((b,c)=>a.indexOf(b)<c))];

tests=[
    [1,2,3],
    [1,2,3,2,1],
    [1.0, 2, 2.0, 1.0],
    [1, '1', '1.0'],
    [undefined, undefined, false, false, true, true],
    [1,2,1,1,1,2,1,2,2,1,1]
]
console.log(tests.map(b=>f(b)))

Nice, it's simpler than mine!

MATL, 13 12 bytes
"GX@&)m?6Mvu

Try it online!
Thanks to Luis Mendo for saving a byte!
using m is the only way I could use mixed-type equality checking. Takes input as a row cell array.
		% (implicit input x)
"		% for loop:
GX@&)		% push input and index, then get x(i) and x(-i),
                % where x(-i) means "x excluding element at index i"
    m		% ismember -- true if x(i) is in x(-i)
     ?		% if true
      6M	% get x(i)
	v	% concatenate with prior results
	 u	% and take unique values
		% implicit end of if
		% implicit end of for loop
		% implicit end of program, output results as cell array

actually, using the third output of u might work, trying that approach now.

ugh never mind, u only works for arrays or cell arrays of strings :-(

I should work for mixed char-numeric content, but there's a bug. It will corrected in the next release

Nice approach! This should work, 1 byte fewer: "GX@&)m?6Mvu

@LuisMendo ah, didn't know X@ worked like that!

The bug in u is now corrected. It will be applied in the next release

[R], 58 bytes
function(x)x[duplicated(x)]

(My original code was nonsense.)
This works with an array input (in R an "atomic vector") but all the elements have to have the same type, or will be coerced to the most general type.
This also works with a list input (the only way in R an "array"-ish object can have elements of different types) which is what the challenge seems to want. The list elements can be other lists, atomic vectors, matrices, data frames - anything, really.
But then the "equality" function used by duplicated is fairly strict and won't give the same answers as the challenge test cases indicate, which is a flaw in the challenge specs and not this answer.

function(x)x[duplicated(x)] ?

@JayCe OK, so yours is shorter, idiomatic, and actually works. But where's your three paragraph essay?

ahah ! Don't be too hard on yourself :) I agree with your comment on the "equality" definition and I wouldn't have thought of testing this on lists.

Jelly, 4 bytes
œ-QQ

Try it online!
The last test case ([None, None, False, False, True, True]) isn't possible in Jelly.

Javascript (ES6), 51 bytes
a=>[...new Set(a.sort().filter((v,i)=>v===a[i+1]))]

run on tio.
Try it:

a=a=>[...new Set(a.sort().filter((v,i)=>v===a[i+1]))]

console.log(a([1,2,3]));
console.log(a([1,2,3,2,1]));
console.log(a([1.0, 2, 2.0, 1.0]));
console.log(a([1, '1', '1.0']));
console.log(a([null, null, false, false, true, true]));
console.log(a([1,1,1,3,2,3,2,3,4]));

On PPCG, submission have to either be functions or programs, but not snippets, unless specifies otherwise. Currently, your answer is a snippet, but you can easily fix that by appending a=> to your code, therefore making it a function. Other than that, nice first answer! Welcome to PPCG!

@Mr.Xcoder, thanks, will do, I was following the python / etc answers above.

Check this ltio link

@LuisfelipeDejesusMunoz, of course! thanks.

@mazzy, good point, fixed :o

@Mr.Xcoder It is actually prepending.

@Adobalsium Yeah of course, just a small brainfart :) Sorry

PHP, 75 bytes
function a($b){return array_unique(array_diff_assoc($b,array_unique($b)));}

Try it online!

Powershell, 38 32 bytes
($args|group|?{$_.count-1}).Name

Try it online, thanks AdmBorkBork
using:

save the code to a file get-duplicates.ps1
run .\get-duplicates.ps1 'a' 42 'b' 42 'a' 42

Known issues: Powershell supress $null value. Result of
 .\get-duplicates.ps1 $null $null $false $false $true $true

is False, True without null.

32 bytes Try it online!

Welcome to PPCG! Nice to see another PowerSheller around.

Thanks, @AdmBorkBork. I cannt open Try it online link. can you post code in comment?

($args|group|?{$_.count-1}).Name

If you have some problems with TIO you can report in talk.tryitonline.net .

Java (JDK 10), 77 bytes
l->{java.util.Set.copyOf(l).forEach(l::remove);return l.stream().distinct();}

Try it online!

Japt -h, 7 bytes
â £kX â

Try it online!
Explanation:
â £kX â
â         // Get all unique items from the input
  £       // Map X through the results
   kX     //   Remove X from the input
      â   //   Get unique items
-h        // Return the last item

Crystal, 42 bytes
def f(a)a.reject{|x|a.count(x)<2}.uniq
end

Try it online!
Sometimes, when you can't get the desired results, the problem can be solved... by running your code in a different language.
Initially, I tried solving this in Ruby, but ironically, despite the OP's statement that all test cases correspond to Ruby comparison rules, the above code when run in Ruby actually fails for the third test case, as both uniq and array intersection operator use stricter equality checks. However, it passes all tests in Crystal (which shares most of its syntax with Ruby) at the expense of having to declare it as a defined function (-> proc would be longer in Crystal).
As a bonus, here is the golfier Ruby-only version of the code (doesn't pass test 3):
Ruby, 33 bytes
->a{a.reject{|x|a.count(x)<2}|[]}

Try it online!

Gaia, 4 bytes
:uDu

Try it online!
: duplicates the input, u uniquifies it, D retrieves the multiset difference between the two and u uniquifies the result.

Husk, 4 bytes
uṠ-u

Try it online!
Explanation
     -- input, e.g. [2,1,1,3,2,2]
   u -- remove duplicates: [2,1,3]
 Ṡ-  -- subtract this from original list: [2,1,1,3,2,2] - [2,1,3] = [1,2,2]
u    -- remove duplicates: [1,2]

Physica, 33 bytes
->a:Set@Filter[->e:a.count@e>1;a]

Try it online!

Haskell, 33 bytes
nub.((\\)<*>nub)
import Data.List

Try it online! Port of my Husk answer.
The point-free version given above is equivalent to f x=nub$x\\nub x which is one byte longer.

Haskell, 50 bytes
([]#)
a#(x:r)=([x|any(==x)r,all(/=x)a]++a)#r
a#_=a

Try it online! Alternative without imports.

Stax, 5 bytes
═H+U(

Run and debug it
Explanation:
cu|-uJ Full program, unpacked
cu     Copy and make unique
  |-   Remove each element once
    u  Make unique again
     J Join by space. 'm' would be equally long, but as F has a lower charcode, it can be packed better.

Retina, 23 22 bytes
Lmsl`(.+)(?=.+^\1$)
D`

Try it online! Explanation:
Lmsl`(.+)(?=.+^\1$)

List duplicated lines. The m modifier allows the ^ and $ to match the start and end of a line in the lookahead. The s modifier allows us to look ahead past newlines using just .+. The l modifier automatically anchors the match to whole lines. I can't use the p flag though as the match could be more than one line at once, however the next stage will deal with that.
D`

Deduplicate that list.

Proton, 32 bytes
l=>set(v for v:l if~-l.count(v))

Try it online!
Port of TFeld's Python answer. Could be shorter but {...} apparently doesn't work for setcomps.

Red, 46 bytes
func[b][foreach c unique b[alter b c]unique b]

Doesn't work for numbers in different representation as float or string.
Try it online!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Find unique elements based on a given key
Input
Take a list of values xi each paired with a key yi.
[(x1, y1), (x2, y2), ...]

Output
Return a list L containing only values from the set {xi}.

The length of L must be equal to the number of unique keys k in the set {yi}.
For each unique key k there must be a value from {xi} that has key k.

Details

Standard loopholes disallowed.
You can assume all values in the input will be nonnegative integers.
There may be duplicate values and keys.
You can assume there is at least one value/key pair in the input.
If you prefer to take two lists of equal length as input (one for values, one for keys) that is fine.
You may not take any other input.
The order of the list you output does not matter.
The xi you choose for each key does not matter.

For example, with input [[0, 0], [1, 3], [2, 3]] you can return either [0, 1] or [0, 2] or any permutation of these.
Examples
[[1, 2], [3, 2], [3, 0]]  -> [1, 3] or [3, 3]
[[7, 2], [7, 0], [7, 1]]  -> [7, 7, 7]
[[4, 0], [4, 0], [9, 1], [5, 2]]  -> [4, 9, 5]
[[9, 1], [99, 10], [5, 5], [0, 3]]  -> [9, 99, 5, 0]

Fewest bytes wins.

Can I take input in the form key value key value key value ...?

@wastl Yes you can

What if your language doesn't support Maps containing the same keys? Can we take two arrays as keys and values as input? Or create our own custom Map that does take multiple values as input (or perhaps a list of key-value pairs)?

@KevinCruijssen If you prefer to take two lists of equal length as input that is fine. Is this what you mean? I don't know what you mean about "Maps".

@dylnan Ah, that was indeed what I meant, thanks. Read past it. And "maps" is the term for key-value pairs in Java, not sure if it's called differently in other languages.

@KevinCruijssen "maps" is how I learnt it, some languages like Perl call them hashes (short for hash maps I guess), and the currently popular term seems to be dictionaries or dicts.

Python 2, 34 bytes
lambda a,b:dict(zip(b,a)).values()

Try it online!
Takes input as list of values and list of keys.
Generate dictionary, swapping keys and values, which leaves only unique y values. Return all corresponding x values

You can save 3 bytes if you reverse the order of the input arguments (the question doesn't prescribe a specific order) and take and pass them as variadic arguments: https://tio.run/##K6gsycjPM/qfYxvzPycxNyklUSvRKiUzuUSjKrNAQytRU1OvLDGnNLVYQ/N/QVFmXolCjka0kY4CEBnE6ihEG@ooGANRrCYXXNZQx9BAx1THGCRtqWNpCWQbxGr@BwA

Jelly, 2 bytes
Ḣƙ

Try it online!
Takes two lists of equal length, first is keys, second is values.

J, 4 bytes
{./.

How?
The left argument x is a list of key, the right one y- a list of values
/. groups y according x
{. takes the first element of each group
Try it online!

Clojure, 20 18 bytes
(comp vals zipmap)

This takes lists of values and keys as arguments, in that order.

Stax, 5 bytes
╠HB%§

Run and debug it
Takes two arrays, first values, then keys.
Explanation:
cu:I@J Full program, unpacked
cu     Push a unique copy of the keys.
  :I   Indices of the unique elements
    @  Index the values array
     J Join by space
       Implicit output

Python 3, 42 bytes
lambda a,b:[dict(zip(b,a))[q]for q in{*b}]

Try it online!
a = values
b = keys

JavaScript (ES8), 43 bytes
Takes input as 2 distinct lists in currying syntax (values)(keys).
v=>k=>v.filter(o=(x,i)=>o[j=k[i]]?0:o[j]=1)

Try it online!

Today's JavaScript lesson: functions are arrays.

@Jakob More precisely, functions are objects. At the end of the first test case, o looks like { [Function: o] '0': 1, '2': 1 }.

Haskell, 49 47 bytes
map fst.nubBy((.snd).(==).snd)
import Data.List

Try it online! Input as a list of tuples, e.g. [(1, 2), (3, 2), (3, 0)].

Input as list of lists (49 bytes)
map(!!0).nubBy(\a b->a!!1==b!!1)
import Data.List

Try it online!

Husk, 4 bytes
ṁhüt

Try it online!
How?

ṁhüt – Full program.
  üt – Group by tail (the lists without the first element).
ṁh   – Map heads (the lists without the last element) and concatenate the results.

R, 30 bytes
function(x,y)x[!duplicated(y)]

Try it online!

Japt, 8 bytes
â £VgUbX

Japt Interpreter
Thanks to Shaggy for saving 1 last byte
Completely reworked the logic. Takes some cues from Luis' answer, but I think it's still improved. Now takes input as two lists, keys, values. Apparently I'm still short of optimal though.
Explanation:
â £         For each unique Key X
     Ub     find the first index in "keys"
       X    which is equal to X
   Vg       then take the "value" with the same index

12 bytes. You might be able to save a few bytes by taking the keys & values as separate inputs.

There is an 8 byte solution if you want to try for it.

The ¥ isn't needed ;)

@Shaggy Indeed! I had been wondering what the difference between the overloads of b were, didn't notice at all that only one of them took a function.

And that's the 8 solution I had in mind now, nicely done. Incidendtally, you could reverse the inputs and it would still be 8 bytes: Vâ £gVbX.

Ruby, 27 bytes
->a,b{b.zip(a).to_h.values}

Try it online!
Takes input as two arrays (the footer transforms the original test cases into this format).

05AB1E, 4 bytes
DÙkè

Take two input lists: first the values, then the keys.
Try it online or verify all test cases.
Explanation:
D        # Duplicate the values-list
 Ù       # Get all unique items of the values-list
         #  i.e. [0,0,1,0,2] → ['0','1','2']
  k      # Get all (first) indices of these unique values
         #  i.e. [0,0,1,0,2] and ['0','1','2'] → [0,2,4]
   è     # And use this index to get the key from the keys-list
         #  i.e. [0,2,4] and [4,4,9,5,4] → [4,9,4]

Julia 0.6, 36 34 32 bytes
A->values(Dict(y=>x for(x,y)=A))

Try it online!
(shaved off two bytes thanks to @JonathanFrech)
(another two bytes by replacing ∈ with = in comprehension)
The input format specified in the question [[1, 2], [2, 7]] works as it is in Julia as an array of arrays containing (potential) key value pairs, the only thing to take care of is that the key comes second and value first.

Slight change, for the same bytecount,
A->values(Dict((y,x)for(x,y)∈A))

Try it online!

Welcome to PPCG! I am in no way familiar with Julia, but it seems to me you may be able to shave off two bytes by removing both square brackets.

Thank you. I had assumed the brackets were always necessary for comprehensions, but seems they're optional when they're used as an argument. Good suggestion, especially for a non-Julia user! :)

I am assuming it is some sort of tuple comprehension (coming from Python). As a general tip, TIO has a copy wizard which allows you to easily compose a PPCG submission (link icon in the upper right corner, circumvents problems like the leading space in your current post). With small golfs like mine it is not absolutely necessary, but generally I would advise to credit golfing improvements from other users.

Ah, I was just wondering how everyone's submissions were in a uniform format, whether there was some automation tool I didn't know about. I was using the link icon, but lazily stopped scrolling at the Markdown one, and didn't realize there was one specifically for PPCG. (And noted about the crediting part, will do.)

Julia 0.6, 29 26 19 bytes
values∘Dict∘zip

Try it online!
Point-free style. Takes input as an array of keys and an array of values.

Older solution:
29 26 bytes
v\k=values(Dict(zip(k,v)))

Try it online!
-3 bytes using operator syntax instead of lambda
Takes input as an array of values and an array of keys.

Java 8, 82 bytes
A lambda from a stream of int[] pairs to java.util.Collection<Integer>.
m->m.collect(java.util.stream.Collectors.toMap(a->a[1],a->a[0],(a,b)->a)).values()

Try It Online

MATL, 9 bytes
viiQ(5Mu)

Try it online!
Probably suboptimal, but hey, it works!
Uses the facts that (a) input is guaranteed to have only non-negative integers, (b) MATL extends an array of you try to assign to an index that doesn't exist.
v - create an empty array in the stack
i - get array of values
iQ - get array of keys, increment by 1 (so the minimum value is 1, not 0, since MATL indexing is 1-based)
( - assignment indexing - use the array of keys as indices and assign the values to those indices (if any keys are repeated, only the last value remains in that location)
5M - gets the last input of the last call - which would be the array of indices we used
u) - take a unique list of those indices, index with that list, and leave that result (which is a list of values of unique keys) in the stack

Japt, 24 20 16 8 bytes
-4 bytes thanks to @Shaggy
Takes input as key, values
â £VgUbX

Try it online!

Japt, 20 18 bytes
r@bY <Z?X:XpVgY}[]

Try it online!

A few quick tips/hints to help you golf this further: 1 Reverse the inputs, 2 Check the Unicode shortcuts.

Thanks @Shaggy I'm still reading all the methods from the docs and d trying to adapt. I'll golf this even more in a couple of hours

There is an 8 byte solution if you want to try for it.

Instead of m@A?B:C} k¥B, you may want to try k@A} m@C :-)

Pyth, 7 bytes
hMhM.ge

All testcases.

Perl 5 -pa, 24 bytes
%a=@F;$_=join$/,values%a

Try it online!
Takes input in the format key value key value key value ....
TIO footer is only to separate test cases.

C-Sharp, 63 bytes
object _(int[][]p)=>p.GroupBy(i=>i[1]).Select(g=>g.First()[0]);

Returns an enumerable of integers.

Wolfram Language (Mathematica), 25 bytes
#&@@#&@@@#~GatherBy~Last&

Try it online!

Perl 6, 25 bytes
{.unique(:as(*[1]))[*;0]}

Try it
Expanded:
{  # bare block lambda with implicit parameter $_

  .unique(  # find the unique results (implicit method call on $_)

    :as(    # use this code to compare
      *[1]  # the second value (WhateverCode lambda)
    )

  )[        # index into that
    *;      # all in the top level
    0       # only the first value from each
  ]
}

Well done. I'm always shocked by the conciseness of Perl 6.

Perl 6, 12 bytes
{%$_.values}

Try it online!
Coerces the given list to a Hash and then returns the values. This works on both a list of pairs, and a list of key, value, key, value....

Rust, 81 bytes
|a,b|b.zip(a).collect::<std::collections::HashMap<_,_>>().into_iter().map(|v|v.1)

Try it online!
Takes two iterators, returns an iterator.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Rounding Numbers
Task
Given a number between 0 and 1 and another integer, print the approximated value of the first number rounded off to the specified number of digits given by the second integer. For example, if the input is 0.3212312312 , 2 then the output is:
0.32

Rules

The number of digits after the dot should always equal the second input integer.
The input will always be ([)number from 0-1 , integer above 0(])
Predefined round functions are allowed.
The first input number will not have any trailing 0's
Always use a dot for input and output. Commas are not allowed.
Fractions are allowed as output with the notation number/number but try to just use a decimal notation.

[Trailing zero rule removed due to that i should have been faster]

Rounding should always be done to the closest number so up if above 4 and down if under 5.

Testcases
Input: 0.31231231231 , 1
Output:
0.3
Input: 0.1, 10
Output:
0.1000000000
Input: 0.01231231231 , 9
Output:
0.012312312
Scoring:
This is code-golf. Shortest answer in bytes wins.
Suggestion for making this challenge better are appreciated. Have fun golfing!
EDIT:
definition of this challenge by Francisco Hahn: shortest way to round a float X with precision N on each language
Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 166330; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}

<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Very closely related, potential duplicate. Since my vote is a hammer, I won't vote to close as yet.

@AdmBorkBork It is closely related but not a duplicate as that one allows for other number ranges. Thanks for showing this to me though.

@AdmBorkBork That question is about rounding to significant figures, rather than decimal places.  This doesn't need any sort of handling for numbers like 0.0001.

@AdmBorkBork as far as i see the other question handles significative values of the float, this one doesn't, but i can see this post as something like shortest way to round a float X with precision N on each language

Will the first number ever include trailing 0s? (e.g. 0.80)

@Shaggy It won't, ill add that to my challenge

(1) can 0 or 1 appear in the input? If so, are they provided with trailing .?

@user202729 added, thanks.

It is inadvisable to use "try" in a challenge specification. Either require it or do not require it.

Will we ever get something that rounds to 1, such as 0.999, 1?

"Rounding should always be done to the closest number so up if above 4 and down if under 5." Most languages use the round-to-even standard (2.5 rounds to 2). If you enforce this requirement, I'm not sure any of the proposed solutions are correct.

Suggestion: test cases with rounding

Suggested test case: 0.02675, 4 (Breaks many existing answers)

@12Me21: As noted on said answers, 0.02675 is not a "real" number; the actual value is 0.02674999999999..., so rounding down is correct here, regardless of rounding strategy.

@ShadowRanger of course 0.02675 is a real number (that unfortunately can't be represented accurately in binary). Requiring that 0.02675 should always be rounded down doesn't make much sense IMO. If you use a language that's clever enough to realize it should be rounded up when working in base-10, then you shouldn't be punished for it. I'd say optional rounding in case of floating point inaccuracies is the way to go here. 0.15 ≠ 0.1499....

@StewieGriffin: My point is not that it should do anything. I'm trying to point out that rounding down in such a language is correct (because the value isn't actually at the midway point), not that the (almost non-existent) set of languages with decimal based floating point should be penalized if they (correctly) round their exact values up. Really, making any sort of rounding guarantees near the midway point is a problem; as Benjamin notes, most languages use round-half-even as a strategy, so leaving the "ends in exactly 5" case as implementation dependent is probably the way to go.

@StewieGriffin: My other comments are a little more clear; sorry for being misleading in this one. In the languages that use IEE-754 binary64 floating point (the vast majority), 0.02675 doesn't exist, and they approximate it with a slightly smaller number. Defining rounding rules excessively strictly will effectively limit responses to languages with decimal floating point (and for many of them, bloat the answers since they default to binary64 and need libraries for decimal, e.g. Java's BigDecimal and Python's decimal).

If you choose to edit the spec after you already got answers, you should at least notify the answers that got invalid with a comment. (Trailing zeroes should be added with for example 0.1, 10. invalidates quite a few answers that rely on round builtins)

APL (Dyalog Unicode), 1 byteSBCS
Anonymous tacit infix function (actually just a built-in). Takes number of decimals as left argument and fraction as right argument.
⍕

Try it online!
Documentation for dyadic ⍕ ("Format By Specification").

I like how you treat that built-in so formally over TIO...

I'm not sure if this fits the challenge as this requires a f as input instead of a , (atleast on TIO)

@LucH APL is usually used in an interactive session (REPL). TIO's Code area contains the actual definition(s) while Input is the session where the "user" uses the function f.

JavaScript (Node.js), 18 bytes
a=>b=>a.toFixed(b)

Try it online!

lol,  this is just nice :)

Japt, 2 bytes
xV

Try it online!
x is the builtin for rounding to n decimals. We pass in V (Second input).

Okay... I don't  think this can be beat lol.

Dang it! Too slow!

https://tio.run/##y0osKPn/vyLs/38DPQNDI2MoUtBRMAIA maybe use that notation for input in your tio as your current version wasn't according to the challenge rules. (code is the same, just changed the input)

@LucH - that's irrelevant in Japt each comma or newline separated item is a separate input.

Fails on 0.02675, 4

The challenge requires it to round up to 0.0268

@12Me21 Good spot, a trailing 5 should indeed be rounded up. I don't know why japt rounds it down.

Japt, 2 bytes
Takes input as an array of 2 numbers.
rx

Try it
reduces the array by rounding the first number to the number of decimals specified by the second.

Japt just seems to be too good for this challenge.

Upvoting this answer because it is smaller than the other Japt answer: this one uses only lowercase characters.

PHP, 47 39 bytes
function a($b,$c){return round($b,$c);}

Try it online!

How many languages are you going to golf this in? ;)

@LucH 2 is nothing try seeing Leaky's 10 answer combo :D

@LucH The challenge is too easy. xD sorry

@LuisfelipeDejesusMunoz https://codegolf.stackexchange.com/questions/120052/try-to-make-a-square that one was easy and it blew up so that's why i also made this one.

Are you sure you can pass the arguments like that toa  php script?, it is my understanding that the values has to be on the $argv array as arguments for the script.

@LuisfelipeDejesusMunoz $argv acording to the documentation the php script needs the input on $argv. About the function you can short a few bits by using echo instead of return

Python 2, 24 bytes
-4 bytes thanks to ovs
lambda a,b:"%%0.%sf"%b%a

Try it online!

Fails on 0.02675, 4

@12Me21: Not relevant, since 0.02675 doesn't actually exist as an exact value in IEEE 754 binary64 floating point (which most languages use as the basis for floating point math; you'll get the same issues with Java, JavaScript, C#, C [compiler dependent], etc.). The closest value is something like 0.02674999999999999947, with 0.02675 being a convenient shorthand. Floating point math is broken from a human perspective

24 bytes

@ovs: Using more modern formatting (i.e. the str.format method, not printf-style formatting), you can get it down to 16 bytes (doesn't even require a lambda). My second solution for Python 3 will work identically in Python 2.7 (and only require two more bytes on Python 2.6, to add indices to the formatting placeholders).

Python 3 (produces rounded float, no trailing zeroes), 5 bytes
round

Try it online!
Python's built-in round function is defined to do exactly what the OP wants in the summary edited in later "round a float X with precision N", though without appending trailing zeroes (because it's still returning a float, and floats don't include information about their formatting).
Python 3 (produces string form), 16 bytes
'{:.{}f}'.format

Try it online!
Formatting operations can use a nested specifier to allow one argument to define the precision of the other. Doesn't print it, but returns a formatted string with the specified precision.
Python 3 (prints string), 30 bytes
lambda a,b:print(f'{a:.{b}f}')

Try it online!
Python 3.6+ f-strings save some characters here (couldn't use them without the wrapping function since we wouldn't know the names to use). Mostly included to demonstrate f-strings (obviously longer than other solutions).

Note: The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

@12Me21: This is a problem in any language based on IEEE binary floating point. If 2.675 doesn't really exist, it's just a shorter spelling of 2.6749999999999999996 or whatever, then you've rounded correctly. Python isn't unique here, it's just up front about the problem in the docs, where many languages don't bother to mention it.

PHP, 28 Bytes
Try it online
Code
<?=round($argv[0],$argv[1]);

Forth (gforth), 26 bytes
Assuming decimal is on top of the floating point stack and precision is on the integer stack
: f dup 2 + swap 1 f.rdp ;

Try it online!
Explanation
f.rdp takes a float and 3 arguments from the integer stack:

the width of the output (answer uses n+2 to account for 0 and decimal point)
the number of digits after the decimal (answer uses n)
the required number of significant figures in the input (answer uses 1, because floats with less significant figures are outputted in exponential notation)

Code explanation
dup 2 + swap 1        \ place n+2 n and 1 on top of the stack
f.rdp                 \ formats output

Stax, 1 bytes
j

Run and debug it
In stax, j is a built-in instruction that performs the required rounding.

T-SQL, 24 bytes
SELECT STR(f,20,d)FROM t

Per our input standards, input is taken via pre-existing table t with float f and integer d.
The function STR() is shorter and more convenient than either a CAST or a ROUND.
You didn't specify, so I assumed that 20 digits would be more than sufficient. If not, that hard-coded value can be increased.

Java (JDK 10), 21 bytes
n->d->n.setScale(d,4)

Try it online!
I would have loved to have submitted n->n::setScale (14 bytes) but alas, there is no default rounding, so we get ArithmeticException when rounding is required...

MATL, 13 bytes
i'%.'j'f'hhYD

Try it online!
Explanation:
i              % Grab first input: 0.32315
 '%.'j'f'      % Push the literal: ['%.' second input as string 'f'], where the input
               % specifies the number of decimals
         YD    % printf('%.sf',x)  where s is the second input, and x is the first

hh seems to be missing from the explanation. Also, I think you can remove i if you change the input order

R, 40 36 bytes
function(x,n)format(round(x,n),ns=n)

Try it online!
(-4) thanks to digEmAll

You can use partial matching for arguments, i.e. nsmall=n can be shortened to ns=n

Julia 0.6, 51 bytes
(x,d)->(y=string(round(x, d));y*"0"^(d-endof(y)+2))

Try it online!
With trailing zeros as per the questions's "Trailing zeroes should be added with for example 0.1, 10" condition.
Julia's @printf can only take constant X values in %.Xf format strings (%.4f, etc.), so instead this code manually pads the required number of zeros if the rounded value has less than d digits after the decimal place.
First, store the rounded number as a string in y. Then, the number of digits after decimal point in y is length(y) - 2 (- 2 because the inputs are between 0 and 1, so there's one initial digit and then a decimal point to subtract). endof(y) is just a shorter way to write length(y) (at least for Julia v0.6).
Then, subtract this from the required number of digits d. Then, (d-(endof(y)-2)) (= (d-endof(y)+2)) tells you how many digits are missing in the output (if any). Use that in "0"^(d-endof(y)+2) to get "0" repeated that many times, and then append that to y with the string * (concatenate) operator.

Julia 0.6, 5 bytes
round

Try it online!
Without trailing zeros, conforming to the summary "shortest way to round a float X with precision N on each language".

Could you use two printf like this 43 bytes R solution?

Doesn't seem possible, unfortunately. The problem is that Julia's @printf parses its format string at compile time (for doing some type system magic), and as such requires the whole format string to be a compile-time constant. There are external packages to allow C-style or Python-style full-fledged format strings, but nothing builtin as of now.

Thanks for the clarification -  I get now what you meant by constant above. Too bad!

74 Bytes Python 2.7
lambda x,y:str(x)[:y+2]if int(str(x)[y+2])<5else float(str(x)[:y+2])+.1**y

Messy but I think it works for all the scenarios.

Welcome to PPCG! :)

It fails if the y is greater than the precision of x: https://tio.run/##PYzBCsIwEETvfsVSCGTTUJqCl2K/RD1E2sVCbEOyQvP1MRHxNrx5Mz7xc9@GTNMtO/t6zBYOncbIQR54HVM73FeCdWP5Q5Xg5by4uAC53f6Lr4ttZ5RKebZsYSo7/2aJJx/KAzQkQoEiNiBAVkUDSVUDIuS@MxpM/wE

Tcl, 31 bytes
proc R x\ n {format %.*f $n $x}

Try it online!

Perl 6, 18 bytes
{$^a.base(10,$^b)}

Try it

05AB1E, 10 bytes
.ò0¹²g-Ì∍J

.ò is the builtin that already gives the answer for most test cases. 0¹²g-Ì∍J is to correctly append trailing zeroes if necessary.
Try it online.
.ò          # Round the second decimal input to the integer first input amount of decimals
            #  i.e. 10 and 0.1 → 0.1
            #  i.e. 1 and 0.67231 → 0.7
0           # Literal '0'
 ¹          # Get the first integer input
  ²g        # Get the length of the second decimal input
    -       # Subtract them from each other
     Ì      # Increase it by 2 for the "0." part
            #  i.e. 10 and 0.1 → 10-3+2 → 9
            #  i.e. 1 and 0.67231 → 1-7+2 → -8
      ∍     # Extend the "0" to a size of that length
            #  i.e. "0" and 9 → "000000000"
            #  i.e. "0" and -8 → ''
       J    # Join everything together
            #  i.e. 0.1 and "000000000" → 0.1000000000
            #  i.e. 0.7 and '' → 0.7

Octave, 28 bytes
@(x,y)printf(['%.',y,'f'],x)

Try it online!
Takes the first input as a number and the second as a string. Creates a formatting string: %.yf by concatenation, where y is the input that specifies the number of decimals. x is the input number that will be printed.

R, 42 bytes
function(x,n)sprintf(paste0("%.",n,"f"),x)

Try it online!
Failed attempt at outgolfing DS_UNI's shorter R answer.
Even worse:
R, 43 bytes
function(x,n)sprintf(sprintf("%%.%if",n),x)

Try it online!

Kotlin, 19 bytes
"%.${b}f".format(a)

Try it online!

By default, submissions should be either a function or a full program. This is just a snippet that needs predefined variables a and b.


text:
Golfing Chain (Cops' Thread)
This is a Cops and Robbers challenge. For the Robbers' thread, go here.
The Cops have three tasks.
1) Pick a sequence from the OEIS.
2) Pick a language (this is suggested to be a golflang, but doesn't have to be) that, when given input n, outputs A(n) (where A(n) is the sequence chosen) using all usual code-golf rules.
Call this language LA and code CA.
For example, Jelly and Jelly_code.
3) Then, pick a different language (this is suggested to be a non-golflang, but doesn't have to be) and write code that takes no input and outputs code CA, again following all usual code-golf rules. (Note: this can be obfuscated code and doesn't necessarily need to be golfed, but the longer this code is the easier it will be for the robbers to crack your submission.)
Call this language LB and code CB.
For example, Python and Python_code.
The Cop's submission to this challenge is the sequence (specified whether 0- or 1-indexed), the name of the two languages LA and LB (and which one solves which part), and the byte-count of CB only. Keep the actual code of both parts, and the length of CA, secret.
For the Cop, links to documentation for LA and LB, or an interpreter (or a TIO link, since that includes both), are appreciated but not required.
The Robber's challenge is to select a Cops' entry and write code CC in the same LB language that outputs some code in the same LA language that solves the original OEIS task. The length of CC can be no longer than the length of CB as revealed by the cop (though may be shorter). Note: The code produced by CC does not have to match CA.
For our example, this means that the Robber has to write Python code that outputs Jelly code that solves the original OEIS sequence, and that Python code has to be no longer than the length revealed by the Cop.
Winning conditions
Answers that have not been cracked in a week can have their solutions revealed, at which point they are considered Safe. Note that if you don't reveal your solution after a week, it can still be cracked. The Cop with the shortest Safe answer wins.

Reminds me of https://codegolf.stackexchange.com/q/128065/46066

Do we keep the OEIS sequence secret?

@juniorRubyist No, the Cop must state which sequence they used, and whether it's 0- or 1-indexed.

OEIS A000041, cracked by ETHproductions
Let's try it the other way around: golflang generates non-golflang.

a(n) = number of partitions of n (the partition numbers).

a(n) (0-indexed) is returned by a JavaScript function (ES6)
The program that outputs the JS function is written in Jelly
The length of the Jelly program is 35 bytes

Intended solution

    Jelly: “¦ṚoIwƭ- ḊFæSḂ¥¶Ẉ|ḊJƓƝʋnrB⁾’b28+40Ọ

    which outputs

    JS: C=(A,B=A)=>A<0?0:A?B?C(A,B-1)+C(A-B,B):0:1

Cracked. That was quite fun, although I seem to have lost a couple of hours :-)

@ETHproductions Nice! My JS solution was using a restricted range of characters so that it can be compressed as a base-28 integer on the Jelly side.

@ETHproductions Man, I should have spent more time optimizing the JS code. Here is a 31-byte solution. ¯\(ツ)/¯

OEIS 000035, cracked by betseg
The problem is solved in Proton.
The Proton code is output by Python.
The length of the Python program is 13 bytes.
Really easy one for starters (if you know Proton :D). Zero-indexed.
Intended Solution

 Python: print("(2%)")
 Proton: (2%)
 Though I decided to let n=>n%2 be short enough because dyadic/monadic function shortcuts are not documented.

Really easy one if you know a language which appears to have precisely zero documentation. Yeah, great.

Why is the link to A34 ...

cracked

@user202729 fixed thanks

@PeterTaylor precisely zero there's enough here for you to solve it...

OEIS A048272, cracked by DJMcMayhem

Number of odd divisors of n minus number of even divisors of n (1-indexed).

The program that outputs a(n) is written in 05AB1E.
The program that outputs the 05AB1E program is written in Brain-Flak + the -A flag.
The length of the Brain-Flak program is 198 bytes (the byte count does not include the flag).

Note that I could probably easily golf the Brain-Flak program by using stack-manipluation tricks and other kolmogorov-complexity tricks I am aware of, but I wanted to keep this simple as my first submission. Good luck, robbers!
What I had in mind

 05AB1E: ÑÈD<)O(O
 Brain-Flak: (((((((((((()()()){}){}){({}[()])}{}())[((((()()()){}){}())){}{}])((((()()()){}){}())){}{})[((((()()()){}){})()){}{}])(((()()()){})){}{}())(()()()()){})(((((()()()()){}){}){}()){}){})((()()())){}{})

Cracked

@DJMcMayhem :( I just finished

@DJMcMayhem Nice! I'll try something a bit harder next.

OEIS A000034 (cracked by H.PWiz)

1, 2, 1, 2, 1, 2, 1, 2, …
Period 2: repeat [1, 2]; a(n) = 1 + (n mod 2).

a(n) is the output of a Haskell answer, which is the output of a 32-byte Malbolge answer.

Cracked

OEIS A000668, cracked by Lynn

Mersenne primes (of form 2p-1 where p is a prime)

a(n) is outputted by a Jelly full program.
n is 1-indexed.
The Jelly program is printed by a Triangularity program, whose length is 38 bytes.

Different strategy: solve the sequence in a golflang and output the program in an esolang.
Intended solution

 Jelly code
Triangularity code

Are you sure the length is correct? The docs say a Triangularity program must have length 2*n^2 - 1 which can't be 38.

@Lynn That refers to character count, not byte count.

Cracked!

OEIS A055642, cracked by Lynn

Number of digits in decimal expansion of n

This is probably too easy, but it took me a while so I hope someone out there will be just as disappointed as I was when I finally figured it out :D

The program that writes out a(n) is written in 05AB1E
The program that prints the 05AB1E program is written in TeX
The TeX program is 6 bytes long

What I had in mind:

 Sg as 05AB1E code
Sg\bye as TeX code

Cracked?

@Lynn yes. How disappointed were you?


text:
Golfing Chain (Robbers' Thread)
This is a Cops and Robbers challenge. For the Cops' thread, go here.
The Cops have three tasks.
1) Pick a sequence from the OEIS.
2) Pick a language (this is suggested to be a golflang, but doesn't have to be) that, when given input n, outputs A(n) (where A(n) is the sequence chosen) using all usual code-golf rules.
Call this language LA and code CA.
For example, Jelly and Jelly_code.
3) Then, pick a different language (this is suggested to be a non-golflang, but doesn't have to be) and write code that takes no input and outputs code CA, again following all usual code-golf rules. (Note: this can be obfuscated code and doesn't necessarily need to be golfed, but the longer this code is the easier it will be for the robbers to crack your submission.)
Call this language LB and code CB.
For example, Python and Python_code.
The Cop's submission to this challenge is the sequence (specified whether 0- or 1-indexed), the name of the two languages LA and LB (and which one solves which part), and the byte-count of CB only. Keep the actual code of both parts, and the length of CA, secret.
The Robber's challenge is to select a Cops' entry and write code CC in the same LB language that outputs some code in the same LA language that solves the original OEIS task. The length of CC can be no longer than the length of CB as revealed by the cop (though may be shorter). Note: The code produced by CC does not have to match CA.
For our example, this means that the Robber has to write Python code that outputs Jelly code that solves the original OEIS sequence, and that Python code has to be no longer than the length revealed by the Cop.
Winning conditions
The Robber with the most cracked solutions wins.

Brain-Flak, 90 bytes by Mr. Xcoder
((((((((((()()()){}){}){({}[()])}{}())[(((()()()){})){}{}()]))){}{}()()())([][][]){})[][])

Try it online!
This outputs:
ÑÉ·<O

First 05AB1E answer!
How does it work?
Let's say we have 24 as input.
Ñ       # Divisors.
        # Stack: [1, 2, 3, 4, 6, 8, 12, 24]
 É      # Odd?
        # Stack: [1, 0, 1, 0, 0, 0, 0, 0]
  ·     # Double
        # Stack: [2, 0, 2, 0, 0, 0, 0, 0]
   <    # Decrement
        # Stack: [1, -1, 1, -1, -1, -1, -1, -1]
    O   # Sum
        # Stack: -4

The brain-flak code mostly just uses tricks to push large numbers in few bytes. It was very convenient (and unintentional) that the ASCII values are mostly increasing:
209
201
183
60
79

It's also nice that 60 * 3 ~=~ 183 so tripling it and adding a few can save a ton of bytes.
((((((

    # Push 79
    ((((()()()){}){}){({}[()])}{}())
    # Minus 19 (60)

    [(((()()()){})){}{}()])
    # Push that two extra times
    ))

    # Push that ^ (60) Plus the two extras popped (60 + 120 == 180)...
    {}{}
    # + 3 (183)
    ()()())

    # Plus stack-height * 3 * 2 == 3 * 3 * 2 == 18 (201)
    ([][][]){})

    # Plus stack-height * 2 == 4 * 2 == 8 (209)
    [][])

oh nice my 05AB1E program was 8 bytes. idk any of the 05AB1E builtins /shrug :P

Here's 80

Here's 72

Jelly, 34 bytes by Arnauld
Managed a byte shorter than his solution!
“`Ḃ|⁴ʂⱮdÐỌK_ƬƬfıæh’ṃ“fnk1()+-,=>?:

Try it online!
This outputs the JS function
f=(n,k=1)=>n>=k?f(n-k,k)+f(n,k+1):1>n

which computes A000041 (0-indexed; nn(0) returns true in place of 1).

TeX by Simon Klaver
g\bye

prints g, which computes the length of the input in 05AB1E.

Malbolge, 32 bytes by Lynn
('%$:?>7[5|981Uv.uQrq)Mnmm$Hj4ED

Try it online!
That prints the following haskell function:
gcd 2

Try it online!
I used this online tool to generate the Malbolge

I used the same tool :) I was hoping not many people know about it.

Python, 13 bytes by HyperNeutrino
print"n=>n%2"

Try it online!

Triangularity by Mr. Xcoder, 36 bytes
... ...
..  "..
.aẒ;Ba.
1ÇP$#Ṁ"

Try it online!
Prints Jelly code:
..
.aẒ;Ba.
1ÇP$#Ṁ

Try the Jelly code online! It's quite slow.

Most definitely not what I was thinking of but congrats! I'll include the intended solution in my answer shortly.


text:
Block partition a string
Inspiration.
Consider a list l, consisting of numbers. Define a block operation at index i on the list l to be the act of moving 3 consecutive elements starting from i in l to the end.
Example:
l, i (1-indexing) -> l (after applying block operation at index i)
[1,2,3,4,5], 1 -> [4,5,1,2,3]
[1,2,3,4,5,6,7], 3 -> [1,2,6,7,3,4,5]

Given a list consisting of only 0 and 1, your challenge is to partition it so that zeros are at the front, and ones are at the back, using only block operations. Output should be the indices in the order they are applied on the list.
Because this is impossible for the list [1,0,1,0], the list length is guaranteed to be at least 5.
Test cases (1-indexing)
(there are other valid outputs)
[1,1,1,0,0] -> [1]
[0,1,0,1,0] -> [1,2,1,1]
[0,0,0,1,1,1,0,0,0] -> [4]

Use this script to generate more test cases. (only input. The rplc ' ';',' part is used to replace spaces with commas in the output)
Winning criteria
code-challenge is the main winning criteria, and fastest-code is the tie-breaker. In particular:

The solution with the shortest output length (least number of block operations) with the test case (n_elem = 500, random_seed = {secret value}) wins. You should be able to run your solution to completion with the test case (n_elem = 500, random_seed = 123456).
In case of ties, the solution that can handles the largest power-of-2 value of n_elem with random_seed = {secret value} within 10 seconds (for me) wins.
In case of ties, the solution that takes less time on that test case wins.

Sandbox post. (note) I have a linear-time linear-space solution, but it has huge constant factor, besides it's not easy to implement. It's possible to reduce the constant factor but then it's even harder to implement.

(disclaimer: I have solved the linked challenge)

Just to clarify, the output does not need to be the shortest possible output?

@JungHwanMin Correct.

A checker implementation in C++ using rope. A naive implementation by Leaky.

So do we only need to optimize the output for n=500?

@l4m2 I chosen n=500 fairly arbitrarily, but I expect that if the solution works well for n=500, it should be able to work reasonably well with other ranges of n. Of course it should work correctly for all values of n.

@user202729 Your winning criticia is different for different n, so a pure rule winner would need to treat n=500 as a different calculating method

@l4m2 What else I can do? Can I say "a secret value of n in range 500...1000"?

Note: I accidentally revealed the secret test case. So I changed it. Scores on all posts updated accordingly.

Python 3, (0.397 n + 3.58) steps
1000-point polynomial regression by numpy.polyfit.

Number of steps for version 1: 0.0546 n² + 2.80 n - 221
Number of steps for version 2: 0.0235 n² + 0.965 n - 74
Number of steps for version 3: 0.00965 n² + 2.35 n - 111
Number of steps for version 4: 1.08 n - 36.3
Number of steps for version 5: 0.397 n + 3.58

Secret test case score for version 1: 14468
Secret test case score for version 2: 5349
Secret test case score for version 3: 4143
Secret test case score for version 4: 450
Secret test case score for version 5: 205

def partite(L):
	endgame5 = [9,9,1,9,0,0,1,9,
		0,1,0,1,0,1,1,9,
		0,0,1,0,0,0,1,0,
		0,0,0,1,0,0,0,9]
	endgame6 = [9,9,2,9,1,1,2,9,0,2,0,0,1,2,2,9,
		0,1,2,1,0,1,2,1,0,1,0,2,1,1,0,9,
		0,0,1,0,1,0,1,1,0,0,0,0,1,1,1,1,
		0,0,2,2,0,0,2,2,0,0,0,0,0,0,0,9]
	endgame = [9,9,3,9,2,2,3,9,1,0,3,0,2,0,3,9,0,1,3,3,2,2,3,0,1,0,1,0,2,1,0,9,
		0,0,2,1,0,0,2,2,1,0,1,2,0,0,0,2,0,1,3,3,3,3,3,0,1,1,1,1,1,3,0,9,
		0,0,0,0,1,0,1,1,1,0,3,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,0,2,0,1,0,
		0,0,2,0,0,0,2,0,0,0,2,0,0,0,2,0,0,0,3,0,3,0,3,0,3,0,2,3,3,0,0,9]
	offset = 1
	steps = []
	def update(L,steps,ind):
		steps.append(offset + ind)
		if 0 <= ind and ind+3 < len(L):
			return (steps,L[:ind]+L[ind+3:]+L[ind:ind+3])
		else:
			print(offset,ind,L)
			raise
	if len(L) == 5:
		while endgame5[L[0]*16+L[1]*8+L[2]*4+L[3]*2+L[4]] != 9:
			steps, L = update(L,steps,endgame5[L[0]*16+L[1]*8+L[2]*4+L[3]*2+L[4]])
		return steps
	if len(L) == 6:
		while endgame6[L[0]*32+L[1]*16+L[2]*8+L[3]*4+L[4]*2+L[5]] != 9:
			steps, L = update(L,steps,endgame6[L[0]*32+L[1]*16+L[2]*8+L[3]*4+L[4]*2+L[5]])
		return steps
	if 1 not in L:
		return []
	while len(L) > 7 and 0 in L:
		wf_check = len(L)
		while L[0] != 0:
			pos = [-1]
			wf_check2 = -1
			while True:
				i = pos[-1]+1
				while i < len(L):
					if L[i] == 0:
						pos.append(i)
						i += 1
					else:
						i += 3
				assert len(pos) > wf_check2
				wf_check2 = len(pos)
				space = (pos[-1]-len(L)+1)%3
				ind = -1
				tail = pos.pop()
				i = len(L)-1
				while i >= 0:
					if tail == i:
						while tail == i:
							i -= 1
							tail = pos.pop() if pos else -1
						i -= 2
					elif i < len(L)-3 and L[i+space] == 0:
						ind = i
						break
					else:
						i -= 1
				if ind == -1:
					break
				steps, L = update(L, steps, ind)
				pos = pos or [-1]
			if L[0] == 0:
				break
			pos = [-1]
			while L[0] != 0:
				pos = [-1]
				found = False
				for i in range(1,len(L)):
					if L[i] == 0:
						if i%3 == (pos[-1]+1)%3:
							pos.append(i)
						else:
							found = found or i
				if found > len(L)-4:
					found = False
				if not found:
					break
				triple = []
				for i in range(1,len(L)-1):
					if L[i-1] == 1 and L[i] == 1 and L[i+1] == 1:
						triple.append(i)
					if len(triple) > 3:
						break
				space = (pos[-1]-len(L)+1)%3
				if space == 0:
					if found >= 2 and found-2 not in pos and found-1 not in pos:
						# ... _ 1 _ [0] 0 ...
						if found-2 in triple:
							triple.remove(found-2)
						if found-3 in triple:
							triple.remove(found-3)
						if L[-1] == 1:
							steps, L = update(L, steps, found-2)
							steps, L = update(L, steps, len(L)-4)
							steps, L = update(L, steps, len(L)-4)
						elif triple:
							steps, L = update(L, steps, found-2)
							if found < triple[0]:
								triple[0] -= 3
							steps, L = update(L, steps, triple[0]-1)
							steps, L = update(L, steps, len(L)-4)
						else:
							break
						assert L[-3] == 0
					elif found >= 1 and found-1 not in pos and found+1 not in pos:
						# ... _ 1 [0] _ 0 ...
						if found-2 in triple:
							triple.remove(found-2)
						if L[-2] == 1 and L[-1] == 1:
							steps, L = update(L, steps, found-1)
							steps, L = update(L, steps, len(L)-5)
							steps, L = update(L, steps, len(L)-5)
						elif triple:
							steps, L = update(L, steps, found-1)
							if found < triple[0]:
								triple[0] -= 3
							steps, L = update(L, steps, triple[0]-1)
							steps, L = update(L, steps, len(L)-5)
						elif L[-1] == 1:
							steps, L = update(L, steps, found-1)
							steps, L = update(L, steps, len(L)-4)
							steps, L = update(L, steps, len(L)-4)
							steps, L = update(L, steps, len(L)-4)
						else:
							break
						assert L[-3] == 0
					else:
						break
				elif space == 1:
					# ... 1 1 [0] 0 ...
					if found >= 2 and found-2 not in pos and found-1 not in pos:
						if found-2 in triple:
							triple.remove(found-2)
						if found-3 in triple:
							triple.remove(found-3)
						if triple:
							steps, L = update(L, steps, found-2)
							if found < triple[0]:
								triple[0] -= 3
							steps, L = update(L, steps, triple[0]-1)
							steps, L = update(L, steps, len(L)-5)
						elif L[-2] == 1 and L[-1] == 1:
							steps, L = update(L, steps, found-2)
							steps, L = update(L, steps, len(L)-4)
							steps, L = update(L, steps, len(L)-5)
						else:
							break
						assert L[-2] == 0
					else:
						break
				else:
					if found+1 not in pos and found+2 not in pos:
						# ... 0 [0] _ 1 _ ...
						if found+2 in triple:
							triple.remove(found+2)
						if found+3 in triple:
							triple.remove(found+3)
						if L[-2] == 1 and L[-1] == 1:
							steps, L = update(L, steps, found)
							steps, L = update(L, steps, len(L)-5)
						elif L[-1] == 1:
							steps, L = update(L, steps, found)
							steps, L = update(L, steps, len(L)-4)
							steps, L = update(L, steps, len(L)-4)
						elif triple:
							steps, L = update(L, steps, triple[0]-1)
							if triple[0] < found:
								found -= 3
							steps, L = update(L, steps, found)
							steps, L = update(L, steps, len(L)-5)
						else:
							break
						assert L[-1] == 0
					elif found >= 1 and found-1 not in pos and found+1 not in pos:
						# ... 0 _ [0] 1 _ ...
						if found+2 in triple:
							triple.remove(found+2)
						if L[-1] == 1:
							steps, L = update(L, steps, found-1)
							steps, L = update(L, steps, len(L)-4)
						elif triple:
							steps, L = update(L, steps, triple[0]-1)
							if triple[0] < found:
								found -= 3
							steps, L = update(L, steps, found-1)
							steps, L = update(L, steps, len(L)-4)
						else:
							break
						assert L[-1] == 0
					else:
						break
			if L[0] == 0:
				break
			if 0 in L[::3]:
				assert L[::3].index(0) < wf_check
				wf_check = L[::3].index(0)
			steps, L = update(L, steps, 0)
		assert L[0] == 0
		offset += L.index(1)
		del L[:L.index(1)]
		continue
	if 0 in L:
		offset -= 7-len(L)
		L = [0]*(7-len(L))+L
		assert(len(L) == 7)
		while endgame[L[0]*64+L[1]*32+L[2]*16+L[3]*8+L[4]*4+L[5]*2+L[6]] != 9:
			steps, L = update(L,steps,endgame[L[0]*64+L[1]*32+L[2]*16+L[3]*8+L[4]*4+L[5]*2+L[6]])
	return steps

Try it online!

Python 3, ~179 steps for n=500 (on average)
A heuristic greedy approach. Kinda slow but still works. Uses an optimal solver for small sizes.
def incomplete_groups(l):
    r = 0
    ones = 0
    for x in l:
        if x == "1":
            ones += 1
        else:
            if ones % 3:
                r += 1
            ones = 0
    # Ones at the end don't count as an incomplete group.

    return r

def move(l, i):
    return l[:i] + l[i+3:] + l[i:i+3]

def best_pos(l, hist):
    r = []
    cleanup = incomplete_groups(l) == 0

    candidates = []
    for i in range(len(l) - 3):
        block = l[i:i+3]
        if block == "111" and cleanup:
            return i
        elif block == "111":
            continue

        new = move(l, i)
        bad_start = i < 3 and "10" in l[:3]
        candidates.append((new not in hist, -incomplete_groups(new), bad_start, block != "000", i))

    candidates.sort(reverse=True)
    return candidates[0][-1]

def done(l):
    return list(l) == sorted(l)

class IDAStar:
    def __init__(self, h, neighbours):
        """ Iterative-deepening A* search.

        h(n) is the heuristic that gives the cost between node n and the goal node. It must be admissable, meaning that h(n) MUST NEVER OVERSTIMATE the true cost. Underestimating is fine.

        neighbours(n) is an iterable giving a pair (cost, node, descr) for each node neighbouring n
        IN ASCENDING ORDER OF COST. descr is not used in the computation but can be used to
        efficiently store information about the path edges (e.g. up/left/right/down for grids).
        """

        self.h = h
        self.neighbours = neighbours
        self.FOUND = object()

    def solve(self, root, is_goal, max_cost=None):
        """ Returns the shortest path between the root and a given goal, as well as the total cost.
        If the cost exceeds a given max_cost, the function returns None. If you do not give a
        maximum cost the solver will never return for unsolvable instances."""

        self.is_goal = is_goal
        self.path = [root]
        self.is_in_path = {root}
        self.path_descrs = []
        self.nodes_evaluated = 0

        bound = self.h(root)

        while True:
            t = self._search(0, bound)
            if t is self.FOUND: return self.path, self.path_descrs, bound, self.nodes_evaluated
            if t is None: return None
            bound = t

    def _search(self, g, bound):
        self.nodes_evaluated += 1

        node = self.path[-1]
        f = g + self.h(node)
        if f > bound: return f
        if self.is_goal(node): return self.FOUND

        m = None # Lower bound on cost.
        for cost, n, descr in self.neighbours(node):
            if n in self.is_in_path: continue

            self.path.append(n)
            self.is_in_path.add(n)
            self.path_descrs.append(descr)
            t = self._search(g + cost, bound)

            if t == self.FOUND: return self.FOUND
            if m is None or (t is not None and t < m): m = t

            self.path.pop()
            self.path_descrs.pop()
            self.is_in_path.remove(n)

        return m

def h(l):
    """Number of groups of 1 with length <= 3 that come before a zero."""
    h = 0
    num_ones = 0
    complete_groups = 0
    incomplete_groups = 0
    for x in l:
        if x == "1":
            num_ones += 1
        else:
            while num_ones > 3:
                num_ones -= 3
                h += 1
                complete_groups += 1
            if num_ones > 0:
                h += 1
                incomplete_groups += 1
            num_ones = 0

    return complete_groups + incomplete_groups

def neighbours(l):
    inc_groups = incomplete_groups(l)
    final = inc_groups == 0

    candidates = []
    for i in range(len(l) - 3):
        left = l[:i]
        block = l[i:i+3]
        right = l[i+3:]
        cand = (1, left + right + block, i)

        # Optimal choice.
        if final and (block != "111" or i >= len(l.rstrip("1"))):
            continue

        candidates.append(cand)

    candidates.sort(key=lambda c: c[2], reverse=True)

    return candidates

def is_goal(l):
    return all(l[i] <= l[i+1] for i in range(len(l)-1))

opt_solver = IDAStar(h, neighbours)

def partite(l):
    if isinstance(l, list):
        l = "".join(map(str, l))
    if len(l) < 10:
        return [i + 1 for i in opt_solver.solve(l, is_goal)[1]]
    moves = []
    hist = [l]
    while not done(l):
        i = best_pos(l, hist)
        l = move(l, i)
        moves.append(i+1)
        hist.append(l)
    return moves


text:
Rememebere tehe vowelese!
Input
A string of printable ASCII characters, for example:
This is an example string.

Output
For every consonant (BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz) that is not followed by a vowel (AEIOUaeiou) add the last vowel before it, in lowercase.
Consonants before the first vowel are left as-is:
Thisi isi ana examapale seterinigi.

Test cases
AN EXAMPLE WITH A LOT UPPERCASE (plus some lowercase)
=> ANa EXAMaPaLE WITiHi A LOTo UPuPEReCASE (pelusu some lowerecase)

And here comes a **TEST** case with 10% symbols/numbers(#)!
=> Anada here comese a **TESeTe** case witihi 10% siyimiboloso/numuberese(#)!

This is an example string.
=> Thisi isi ana examapale seterinigi.

abcdefghijklmnopqrstuvwxyz
=> abacadefegehijikiliminopoqorosotuvuwuxuyuzu

A pnm bnn
=> A panama banana

Tell me if you need more test cases!
=> Telele me ifi you neede more tesete casese!

Scoring
As this is code-golf, the answer with the lowest byte-count in each language wins (no answer will be accepted).

So, should the inserted vowels be always lowercase, while the text might be both uppercase and lowercase?

Can the output be in the form of a list/array?

@EriktheOutgolfer Yes, I did not want uppercase where we need lowercase, but it would have overcomplicated the challenge if one had to check the case of adjacent letters

@Bobawob A list of characters/length-1-strings is ok, but not something like ["a","na","b","e"]

Can we insert the last vowel with the same case it has. for example hEllo => hElElo

@LuisfelipeDejesusMunoz No

Eat healthy kids, try A pnm bnn!

what about cases where there is no vowel to copy? e.g. strengths

Does anyone else think "How Italians" needs to go in the title somewhere?

@SeanC Consonants before the first vowel are left as-is

Seeing as 05AB1E is actually winning an iterative-truth-table-based  challenge someone needs to poke Jelly... I feel like that would easily beat my 33 byte crapshow.

@StewieGriffin A mn a pln a cnl pnmn!

Retina, 48 bytes
i`(?<=([aeiou]).*?[^\W\d_aeiou])(?![aeiou])
$l$1

Try it online! Explanation: The lookahead searches for a point not followed by a vowel, while the lookbehind searches for an immediately preceding consonant and a previous vowel, which is then inserted in lower case.

JavaScript (ES6), 108 105 bytes
(Saved 3 bytes thanks to @Shaggy.)
f=s=>(t=(s+=' ').replace(/[aeiou]|[a-z][^aeiou]/ig,r=>r[1]?r[0]+v.toLowerCase()+r[1]:v=r,v=''))!=s?f(t):s

Searches for vowels or for consonants with no following vowel:
/[aeiou]|[a-z][^aeiou]/ig

(We don't need to search for consonants explicitly, because vowels are excluded based on the /[aeiou]|....)
Vowels are stored in v, and consonants with no following vowel have v inserted:
r[1]?r[0]+v.toLowerCase()+r[1]:v=r

(If r[1] exists, we've matched on a consonant plus non-vowel.)
If nothing has been changed, we return the input.  Otherwise, we recurse on the replaced string.

f=s=>(t=(s+=' ').replace(/[aeiou]|[a-z][^aeiou]/ig,r=>r[1]?r[0]+v.toLowerCase()+r[1]:v=r,v=''))!=s?f(t):s

console.log(f('A pnm bnn'));
console.log(f('abc'));
console.log(f('AN EXAMPLE WITH A LOT UPPERCASE (plus some lowercase)'));
console.log(f('And here comes a **TEST** case with 10% symbols/numbers(#)!'));
console.log(f('This is an example string.'));
console.log(f('abcdefghijklmnopqrstuvwxyz'));
console.log(f('Tell me if you need more test cases!'));

This is even better. I really need to look at regex

+1 smart idea to use replace over map + join

Based of yours an (almost) working version without recursion: s=>s.replace(/[aeiou][^a-z]*([a-z](?![aeiou]))+/gi,s=>s.replace(/(?!^)./g,a=>a+s[0].toLowerCase())) I can't seems to have issues with sequences of non-letters though

Recursion certainly simplifies things here.

(s+=' ') should save a few bytes.

I was trying to use $ in the RegEx instead of having to append the space but was too tired to get it to work.

I tried the same thing!  But that seemed to require testing for a vowel explicitly, because r[1] would be undefined.

A-ha! Of course! Damned sleep deprivation!

This uses the $, but it adds 2 bytes.  Maybe it can be optimized:  f=([c,...s],v='')=>c?(/[aeiou]/i.test(c)?v=c:/^[a-z]([^aeiou]|$)/i.test(c+s)?c+v.toLowerCase():c)+f(s,v):''

Python 2, 134 119 bytes
def f(s,v=''):u=s[:1];return s and u+v*(u.isalpha()-g(u)-g((s+u)[1]))+f(s[1:],[v,u.lower()][g(u)])
g='aeiouAEIOU'.count

Try it online!
EDIT: 15 bytes thx to Lynn

I fiddled with it a little for 119 bytes.

@Lynn: Love the <vowels>.count.

sed 4.2.2, 64 bytes
:
s/(([aeiou])[^a-z]*[b-df-hj-np-tv-z])([^aeiou]|$)/\1\l\2\3/I
t

Try it online!

I'll be honest, my goal here is just to try to beat perl by a couple of bytes. Let's see if it holds :)

Perl 5, 68 67 59 bytes
perl -pe '$v="[aeiou])";1while s/($v[^a-z]*[b-z]\K(?<!$v(?!$v/\L$1/i'

Here's a great example of the usefulness of \K, and I can't believe I didn't know about this feature before Dom Hastings pointed it out.
I haven't been able to get the right behavior with just using s///g, so an actual loop seems necessary. (It's possible that the right use of a look-behind assertion could work without an explicit while -- but I haven't found it.)

Nice approach! Wasn't able to come up with anything better, but managed to get 6 bytes off: Try it online!

@DomHastings: Even shorter (down to 58 bytes) by factoring out [aeiou]) to variable: Try it online!

Standard ML, 225 223 bytes
str o Char.toLower;fun?c=String.isSubstring(it c)"aeiou"fun g(x,l)$d=(fn l=>if Char.isAlpha$andalso not(?d)then if? $then(it$,l)else(x,l^x)else(x,l))(l^str$)fun f$(c::d::r)=f(g$c d)(d::r)|f$[c]= #2(g$c c);f("","")o explode;

Try it online!
Less golfed:
val lower = str o Char.toLower

fun isVowel c = String.isSubstring (lower c) "aeiou"

(* c is the current char, d is the next char, x is the last vowel and l the accumulator
   for the resulting string *)
fun g (x,l) c d =
    if Char.isAlpha c andalso not (isVowel d)
    then if isVowel c
         then (lower c, l^str c)
         else (x, l^str c^x)
    else (x, l^str c)

fun f t (c::d::r) = f (g t c d) (d::r)
  | f t [c] = #2(g t c #"d")

val h = f ("","") o explode;

Try it online!

wow, ML golf looks really interesting! I love it and the use of the $ variable name.

@Lynn I wrote a tip about identifier renaming some time ago and planned to write one about it as well, but haven't gotten around doing so yet.

JavaScript ES6, 115 bytes
Saves 8 bytes thanks to @ETHProductions
s=>[x="",...s].map((i,j)=>(r=/[aeiou]/i).test(i)?x=i:/[a-z]/i.test(i)&&!r.test(s[j]||1)?i+x.toLowerCase():i).join``

I have managed to inflate this more in the process of golfing it O_o but it also fixes a bug
s=>[x="",...s].map(             // Create a new array with x storing last vowel
                                // This also offsets indexes by one so rel to original str refers to next char
   (i,j)=>                      // Going through each char...
      (r=/[aeiou]/i).test(i)?   // If it's vowel, store it in x
          x=i:
      /[a-z]/i.test(i)          // If a letter (thats not a vowel excluded by above)
         &&!r.test(s[j]||1)?    // Test if next char is *not* vowel
         i+x.toLowerCase():i    // If it isn't, then add the most recent vowel after
    ).join``                    // Combine back to string

@RickHitchcock oh shoot totally forgot about ending char, fixing asap

@RickHitchcock ok fixed

Ah, yes thanks for the golf @ETHproductions

Japt -P, 28 bytes
ó@\ctX ©\VtYÃËè\v ?P=D:D¬qPv

Try it online!
Unpacked & How it works
UóXY{\ctX &&\VtY} mD{Dè\v ?P=D:Dq qPv

UóXY{           }  Split the string between any two chars that don't satisfy...
     \ctX &&\VtY     The first char is a consonant and the second is a non-vowel
mD{                And map...
   Dè\v              If this item is a vowel...
       ?P=D            Assign it to P and return as-is
           :Dq qPv     Otherwise, split the item into chars and join with P lowercased
                       (P starts with "", so beginning consonants are not affected)

-P                 Join with ""

The ó function wins over any kind of regexes.

Nice one, ya beat me :D.

Nicely done - I gave myself severe brainache with this one!

JavaScript, 88 82 Bytes
Done with a single regular expression:
Original Version (88 Bytes):
s=>s.replace(/(?<=([aeiou]).*?(?![aeiou])[a-z])(?=[^aeiou]|$)/gi,(_,c)=>c.toLowerCase())

Updated Version (82 Bytes) after looking at Neil's regular expression:
s=>s.replace(/(?<=([aeiou]).*?[^\W\d_aeiou])(?![aeiou])/gi,(_,c)=>c.toLowerCase())

var tests = {
  "AN EXAMPLE WITH A LOT UPPERCASE (plus some lowercase)":
    "ANa EXAMaPaLE WITiHi A LOTo UPuPEReCASE (pelusu some lowerecase)",
  "And here comes a **TEST** case with 10% symbols/numbers(#)!":
    "Anada here comese a **TESeTe** case witihi 10% siyimiboloso/numuberese(#)!",
  "This is an example string.":
     "Thisi isi ana examapale seterinigi.",
  "abcdefghijklmnopqrstuvwxyz":
    "abacadefegehijikiliminopoqorosotuvuwuxuyuzu",
  "A pnm bnn":
     "A panama banana",
  "Tell me if you need more test cases!":
     "Telele me ifi you neede more tesete casese!"
};

for ( test in tests )
{
  var result = (s=>s.replace(/(?<=([aeiou]).*?[^\W\d_aeiou])(?![aeiou])/gi,(_,c)=>c.toLowerCase()))(test);
  console.log( result === tests[test], result );
}

JavaScript (Node.js), 146 143 132 127 125 bytes
(a,v="")=>[...a].map((b,i)=>(w=/[aeiou]/i).test(b)&&(v=b)?b:w.test(a[i+1]||b)||!b.match(/[a-z]/i)?b:b+v.toLowerCase()).join``

Try it online!

SWI-Prolog, 593 bytes
a(S,D):-atom_chars(S,D).
g(_,[],_,-1).
g(E,[E|_],R,R).
g(E,[_|T],I,R):-N is I+1,g(E,T,N,R).
c(A,E):-g(E,A,0,R),R > -1.
v(X):-a('AEIOUaeiou',X).
c(X):-a('BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz',X).
d([_],_,R,R).
d([H|T],_,I,R):-v(V),c(V,H),!,d(T,H,I,[H|R]).
d([H,N|T],V,I,R):-c(C),c(C,H),v(W),c(W,N),!,d([N|T],V,I,[H|R]).
d([H,N|T],V,I,R):-c(C),c(C,H),v(W),\+c(W,N),string_lower(V,LV),!,d([N|T],V,I,[LV,H|R]).
d([H|T],V,I,R):-!,d(T,V,I,[H|R]).
r([],Z,Z).
r([H|T],Z,A):-r(T,Z,[H|A]).
r(S,D):-r(S,D,[]).
m(X,R):-a(X,O),r(O,P),r([''|P],Q),d(Q,'',I,[]),r(I,J,[]),atomic_list_concat(J,R).

Used only built-in predicates (without regex or list manipulating library).
Usage:
?- m('A pnm bnn').
'A panama banana'
true .

Perl 6,  75 73 71  69 bytes
{({S:i/.*(<[aeiou]>).*<-[\W\d_aeiou]><()><![aeiou]>/$0.lc()/}...*eq*).tail}

Try it
{({S:i{.*(<[aeiou]>).*<-[\W\d_aeiou]><()><![aeiou]>}=$0.lc}...*eq*).tail}

Try it
{({S:i{.*(<[aeiou]>).*<:L-[_aeiou]><()><![aeiou]>}=$0.lc}...*eq*).tail}

Try it
{({S:i{.*(<[aeiou]>).*<:L-[_aeiou]><(<![aeiou]>}=$0.lc}...*eq*).tail}

Try it
Expanded:
{  # bare block lambda with implicit parameter $_

  (
    # generate a sequence

    {  # code block used to generate the values

      S               # substitute (not in-place)
      :i              # :ignorecase
      {

          .*              # start at end of string

          ( <[aeiou]> )   # store the previous vowel in $0

          .*

          <:L - [_aeiou]> # letter other than a vowel

          <(              # ignore everything before this

                          # this is where `$0.lc` gets inserted

          # )>            # ignore everything after this

          <![aeiou]>      # not a vowel (zero width lookahead)

      } = $0.lc       # replace with lowercase of the earlier vowel
    }

    ...    # keep generating until:

    * eq * # there are two equal strings (no changes)

  ).tail   # get the last value
}

TSQL, 500 bytes
 CREATE TABLE i (i CHAR(999)); INSERT i VALUES ('The rain in Spain stays mainly in the plain')
 DECLARE @w CHAR(999)=(SELECT i FROM i),@r VARCHAR(999)='';WITH d(n,c,i,q)AS(SELECT n,SUBSTRING(@w,n,1),CHARINDEX(SUBSTRING(@w,n,1),'AEIOUaeiou'),CHARINDEX(SUBSTRING(@w,n,1),'BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz')FROM(SELECT DISTINCT number n FROM master..[spt_values]WHERE number BETWEEN 1 AND LEN(@w))D)SELECT @r=@r+f.c+LOWER(COALESCE(CASE WHEN f.q<>0 AND COALESCE(d2.i,0)=0 THEN SUBSTRING(@w,(SELECT MAX(n)FROM d WHERE i<>0 AND n<f.n),1)END,''))FROM d f LEFT JOIN d d2 ON f.n=d2.n-1 SELECT @r

Table i is used for input

Assuming input to be present in a certain variable is generally not allowed. Can this be adapted to be a function instead?

@Laikoni solution updated to match given rules

Haskell, 142 130 bytes
""&
import Data.Char
v=(`elem`"aeiouAEIOU")
s&(x:y:z)|v y=x:s&(y:z)
s&(x:y)|v x=x:[toLower x]&y|isAlpha x=x:s++s&y|1>0=x:s&y
_&x=x

Try it online!
The initial ""& is a partial application of the (&) function defined later on, and is placed so oddly to make TIO count the bytes in ""&, but not count the bytes that, in a full program, would be needed to assign that to any named value.

Less golfed:
import Data.Char (isAlpha, toLower)

vowel :: Char -> Bool
vowel = (`elem`"aeiouAEIOU")

replace :: String -> String
replace = go "" -- start by carrying no extra vowel
  where go _ "" = ""
        -- special case for "anything followed by vowel" so later cases can ignore next character
        go s (x:y:more) | vowel y = x : go s (y:more)
        go s (x:xs) | vowel x = x : go [toLower x] xs -- update the vowel we're carrying
                    | isAlpha x = x : s ++ go s xs -- non-vowel letter not followed by a vowel
                    | otherwise = x : go s xs -- some non-letter junk, just include it and carry on

There really ought to be a way to do this more concisely with a fold instead of recursion, but I couldn't figure it out.

Here is a very hacky way of defining a header such that f does not appear in the body: Try it online!

There are two unnecessary spaces in v = ( and you can define g as an infix operator.

Putting the base case g _""="" in last position saves a byte: g _ x=x (two bytes if you switch to infix as Laikoni suggests).

Per our conventions you'd need to add parenthesis around ""& to make it an function.

Python 3, 125 bytes
lambda s,v='[^aeiouAEIOU':sub(f'(?<={v}\W\d])(?={v}]|$)',lambda m:sub(f'{v}]','',s[:m.end()])[-1:].lower(),s)
from re import*

Try it online!
Python 3.6 allows us to (ab)use f-strings to reuse our set of vowels (and for four more characters saved, the beginning of an inverted regex character class) cheaply (a f prefix on each string, then {v} as needed, instead of the '+v+' you'd need with concatenation, or the [^aeiouAEIOU you'd insert literally.
The regex that matches no characters, just a position, avoids issues with the non-overlapping matches normal regexes require, and removes the need to backreference any part of the match; all we use the match object for is to get the slice index we use to find the prior vowel.
Partially de-golfed, it would be something like:
import re

def get_last_vowel(string):
    '''
    Returns the lowercase version of the last vowel in a string if
    the string contains any vowels, otherwise, return the empty string
    '''
    try:
        *restvowels, lastvowel = re.sub(r'[^aeiouAEIOU]', '', string)
    except ValueError:
        lastvowel = ''  # No vowels in string
    return lastvowel.lower()

def rememebere_tehe_vowelese(string):
    '''Inserts the lowercased last vowel seen after any consonant not followed by a vowel'''
    return re.sub(r'(?<=[^aeiouAEIOU\W\d])(?=[^aeiouAEIOU]|$)',
                  lambda match: get_last_vowel(string[:match.end()]),
                  string)

05AB1E, 34 bytes
vyžMylåil©1V}žPylåžM¹N>èå_Y&&i®«}J

Try it online!

I take that back I can only shave 3 bytes off this monstrosity... I think I could shave the boolean down, but there MUST be 3 cases. 1 for vowels. 1 for consonants. 1 for the case that a digit/symbol exists.

v                                 # For each...
 y                                # Push current element.
  žM                              # Push lower-case vowels (aeiou).
    ylå                           # Lower-case current element is vowel?
       i©1V}                      # If so, put it in register, set Y to 1.
            žP                    # Push lower-case consonants (b...z)
              ylå                 # Is current char a consonant?
                 žM¹N>èå_         # Push vowels again, is input[N+1] NOT a vowel?
                         Y        # Did we ever set Y as 1?
                          &&      # All 3 previous conditions true?
                            i®«}  # Concat the current vowel to the current char.
                                J # Join the whole stack.
                                  # '}' isn't needed here, b/c it's implied.
                                  # Implicit return.

Red, 276 bytes
func[s][v: charset t:"AEIOUaeiou"c: charset
u:"BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"b:
parse s[collect[any keep[thru c opt v]keep thru end]]p:""foreach
c b[either find t e: last c: to-string c[p: e][parse c[any[copy p v
| skip]]if find u e[append c lowercase p]]prin c]]

Try it online!
Readable:
f: func [ s ] [
   v: charset t: "AEIOUaeiou"
   c: charset u: "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"
   b: parse s [
       collect [ any keep [ thru c opt v ]
       keep thru end ]
   ]
   p: ""
   foreach c b [
       e: last c: to-string c
       either find t e [ p: e ][
           parse c [ any [ copy p v | skip ] ]
           if find u e [ append c lowercase p ]
       ]
       prin c
   ]
]

Powershell, 104 bytes
based on Neil's regular expression.
[regex]::Replace($args,'(?i)(?<=([aeiou]).*?[^\W\d_aeiou])(?![aeiou])',{"$($args.Groups[1])".ToLower()})

save it as get-rememebere.ps1. Script for testing:
$test = @"
AN EXAMPLE WITH A LOT UPPERCASE (plus some lowercase)
And here comes a **TEST** case with 10% symbols/numbers(#)!
This is an example string.
abcdefghijklmnopqrstuvwxyz
A pnm bnn
Tell me if you need more test cases!
"@

$expected = @"
ANa EXAMaPaLE WITiHi A LOTo UPuPEReCASE (pelusu some lowerecase)
Anada here comese a **TESeTe** case witihi 10% siyimiboloso/numuberese(#)!
Thisi isi ana examapale seterinigi.
abacadefegehijikiliminopoqorosotuvuwuxuyuzu
A panama banana
Telele me ifi you neede more tesete casese!
"@

$result = .\get-rememebere.ps1 $test
$result -eq $expected
$result

Isn't this only a snippet? I mean, powershell has input, so you can't assume input is in $t. Relevant meta post: https://codegolf.meta.stackexchange.com/a/8731/78123

Yabasic, 180 bytes
A full program which takes input from STDIN and outputs to STDOUT
Line Input""s$
x$="AEIOUaeiou"
For i=1To Len(s$)
c$=Mid$(s$,i,1)
?c$;
If InStr(x$,c$)Then
v$=c$
Else
a=Asc(Upper$(c$))
If a>64And a<91And!InStr(x$,Mid$(s$,i+1,1))Then?v$;Fi
Fi
Next

Try it online!