[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y ] [Home]
4chanarchives logo
QUICK WRITE A FUNCTION IN YOUR FAVORITE LANGUAGE THAT BY GIVEN
Images are sometimes not shown due to bandwidth/network limitations. Refreshing the page usually helps.

You are currently reading a thread in /g/ - Technology

Thread replies: 225
Thread images: 19
File: 1467625165247.jpg (29 KB, 412x430) Image search: [Google]
1467625165247.jpg
29 KB, 412x430
QUICK

WRITE A FUNCTION IN YOUR FAVORITE LANGUAGE THAT BY GIVEN ARRAY OF TYPE INT THAT WILL PUT ALL 9s AT THE END OF THE ARRAY WHILE KEEPING THE RELATIVE ORDER OF THE OTHER ELEMENTS

IT SHOULD BE AS FAST AS POSSIBLE AND USE AS LITTLE SPACE AS POSSIBLE

OR THIS BIRD IS GONNA STAB YOU

I will start
void sortN(int* a, int aSize) {
int i = 0;
while (a[i] != 9)
++i;
int posN = i;

for (i < aSize; ++i) {
if (a[i] != 9) {
swap(a[i], a[posN]);
++posN;
}
}
}
>>
(defun sage (list &optional acc)
(cond ((endp list) acc)
((= (car list) 9) (sage (cdr list) (cons 9 acc)))
(t (cons (car list) (sage (cdr list) acc)))))
>>
>>55452571
def nineSort(arr):
isNine = lambda x : x == 9
return sorted(arr, key = isNine)
>>
>>55452672
or iteratively and in-place
(defun kisama (list)
(do ((l list) acc)
((endp (cdr l)) (rplacd l acc) list)
(cond ((= (car l) 9)
(rplaca l (cadr l))
(rplacd l (cddr l))
(push 9 acc))
(t (pop l)))))
>>
BIRDMIN NO
>>
>>55452571
n=x=>x.sort(a=>a==9)
>>
File: 1467753304739[1].jpg (27 KB, 412x430) Image search: [Google]
1467753304739[1].jpg
27 KB, 412x430
>>55452899
WERK OR YOU DIE
>>
here's one that's really readable and reasonably fast. 2 or 3 passes needed depending on implementation of append
(define (nines2end list)
(append (filter (λ (elem) (not (= elem 9)))
list)
(filter (λ (elem) (= elem 9))
list)))
>>
File: bread_crumbs[1].jpg (91 KB, 1255x1008) Image search: [Google]
bread_crumbs[1].jpg
91 KB, 1255x1008
>>55452915
i can't program this is all i have
>>
Fear it.

sub endnines {
@j = grep { $_ != 9 } @_;
push @j, 9 while ($#_ > $#j);
return @j
}
>>
>>55452571

use std::prelude::*;
use std::cmp::*;

fn sort(list: &mut [i8]) {
list.sort_by(|a, b| {
if *a == 9 { return Ordering::Greater }
a.cmp(b)
});
}
>>
>>55452571
[A(A~=9) A(A==9)]


fa/g/s don't know about Matlab
>>
>>55453110
+1
>>
>>55452841
I always loved the fact that solutions written in python are the most concise in these threads.
>>
 / / hello world9
>>
File: 1467871737890.jpg (47 KB, 408x426) Image search: [Google]
1467871737890.jpg
47 KB, 408x426
>>55452841
NOT LINEAR COMPLEXITY
YOU ARE GETTING STABBED BOY
>>
push9s = uncurry (++) . partition (<9)

shig.jpg
>>
>>55452571
post test cases next time, maybe in 1st answer :^)
>>
>>55452571
>for (i < aSize; ++i)
Won't compile. Go stab yourself.
>>
>>55453319
Bird, pls
def sort9(some_list):
return list(filter(lambda x: x != 9, some_list)) + list(filter(lambda x: x == 9, some_list))
>>
[CODE]
#include <stdlib.h>
#include <stdio.h>

void check_pointer(void* p)
{
if (!p)
{
printf("Memory allocation failed!");
return exit(-1);
}
}

int *sort_nines_last(int* unsorted_array, int n)
{
int *sorted_array = malloc(sizeof(int)*n);
check_pointer(sorted_array);
int non_nine_pos = 0, nine_pos = n-1;
for (int i = 0; i < n; i++)
{
if (unsorted_array[i] != 9)
sorted_array[non_nine_pos++] = unsorted_array[i];
else
sorted_array[nine_pos--] = unsorted_array[i];
}
return sorted_array;
}

void print_array(int* a, int n)
{
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
}

int main()
{
int a[] = {1, 6, 2, 9, 2, 4, 9, 0, 9, 5, 6, 7, 3, 9, 2, 5, 9, 1, 2};
int n = sizeof a / sizeof a[0];
printf("Unsorted array: "); print_array(a, n); putchar('\n');
printf("Sorted array: "); print_array(sort_nines_last(a, n), n); putchar('\n');

return 0;
}
[/CODE]
>>
>>55453501
Nigger what the fuck.
>>
File: Capture.png (44 KB, 1176x675) Image search: [Google]
Capture.png
44 KB, 1176x675
>>55453378
Yeah, you are right, fixed and optimized
void sortN(int* a, int aSize) {
int i = -1;
while (a[++i] != 9) { };
int posN = i;
for (;i < aSize; ++i)
if (a[i] != 9)
swap(a[i], a[posN++]);
}

Match me, with my shitty i3
>>
>>55453501
>Fast
>Memory efficient
YOU GONNA GET STABED
>>
>>55453593
Lmfao it's faster than the other solutions and there is plenty of memory nowdays
>>
>>55453614
Sure, match me >>55453555
>there is plenty of memory nowdays
How much memo an embedded controller does have?
>>
>>55453633
About as much as you mom had in her head when you were conceived
>>
>>55453649
Found the CS major
>>
>>55452571

# Ruby (version with "stabby lambda")
no_9 = ->(i) {i!=9}
a = [1,9,5,9,2,9,4]
b = a.select(&no_9).concat a.reject(&no_9)
>>
In Rust:

fn sort9(list: &mut [i64]) {
list.sort_by_key(|&val| val == 9);
}
>>
>>55453054
Happy to see a Perl solution, but I fixed it for you.

Here :
eval unpack u=>q{_<W5B(&5N9&YI;F5S('L*0&H@/2!G<F5P('L@)%\@([email protected]!]($!?.PIP=7-H($!J+"`Y('=H:6QE("@D(U\@3/B`D(VHI.PIR971U<FX@0&H*?0}
>>
>>55453990
Damn didn't think to use sort_by_key()... So wait how does this work exactly?
>>
>>55452571
>In Rust:
>
>fn sort9(list: &mut [i64]) {
>list.sort_by_key(|&val| val == 9);
>}
Wait... won't this just move all 9's up?
>>
>>55453929

Ah, I made a better version.
Should also be faster ..

[1,2,9,5,9,2,9,4].inject([]) { |a,b| b==9 ? a.push(b) : a.unshift(b)}
>>
>>55454025
val == 9 produces a bool.
Together with true > false, all 9's are greater than every other number due to this and are moved to the end of the list.
>>
>>55454024

Hahaha, that looks lyke typcal Perl code to me..

>>55453355

You Haskell fags are the only ones that write more concise code that we Rubyists.. Ó_ô

Is that a Haskell standard library or some "special way" of list processing?
>>
>>55454053
Test it with {9, 9, 9, 9, 0, 5, 3, 9, 9, 0}
sorting it 100000000 times and post time
I am genuinely interested in the speed of that
>>
defmodule Nine do
def main(list) do
Enum.partition(list, fn(x) -> x == 9 end) |> (fn({nines, orig}) -> [orig | nines] end).() |> List.flatten
end
end


iex(10)> Nine.main([1, 2, 3, 7, 4, 8, 3, 7, 4, 9, 3, 9, 9, 9, 3, 2, 5, 1, 0, 9, 8])
[1, 2, 3, 7, 4, 8, 3, 7, 4, 3, 3, 2, 5, 1, 0, 8, 9, 9, 9, 9, 9]
>>
>>55452571
I've been stabbed by this bird so many god damn times
>>
let sep n l =
let (<|>) f (a, b) = (f) a b in
(@) <|> List.partition ((<>) n) l

...

sep 9 [1;2;3;9;0]
=> [1;2;3;0;0]
>>
>>55454224
GET A BOOK AND LEARN TO CODE
>>
>>55454243
[1;2;3;0;0] should read [1;2;3;0;9]
>>
>>55453471
Oh wow. Thats fucking beautiful. Executable pseudocode wins again.
>>
>>55452571
>swap
wouldn't that ruin the relative order of the other elements?
so for example if you have
1241951212
you should get
1231512129

with swap you get
1231251219
or not
?
>>
>>55454691
See >>55453555
>>
>>55454166

Ahh, sorry!
I just found out I messed it up, because if always push values at the new array, I reverse the order of all "non 9" elements..

Here is a new solution, it's even more readable, but I'm not sure about the speed.

[1,2,9,5,9,2,9,4].partition{ |i| i!=9 }.flatten
>>
>>55454718

This solution is very close to the question (logical wise), but it might be a tad slower than this: >>55453929

Because "partition" returns a two-dimensional array (all "true" values at the first slot, all "false" values at the second slot).

"Flatten" take this two-dimensional array and puts is into a new one (one-dimensional).


To be honest, Ruby isn't made for superoptimized code, but for Readability while being "reasonable fast".


If I really think this sorting would be a bottle neck in my code, I would rather use C for this specific task:
>https://www.amberbit.com/blog/2014/6/12/calling-c-cpp-from-ruby/
>>
Typical haskell program
{-# LANGUAGE BangPatterns #-}

(?????)=0
(????????) = null
(?????????) = replicate
(??????????) = 9
(???????????) = head
(????????????) = (==)
(?????????????) = (+)
(??????????????) = tail
(???????????????) = (:)
(????????????????) = 1

(??????)(?)(??)(???)=if(?)then(??)else(???)
(?)(??)=(??)((?)(??))
(???)=(????)(?????)
(????)=(?)(???????)
(???????)(?)(??)(???)=(??????)((????????)(???))((?????????)(??)(??????????))((??????) ((????????????)(??????????)((???????????)(???)))((?) ((?????????????)(??)(????????????????))((??????????????)(???)))((???????????????) ((?\
??????????)(???)) ((?) (??) ((??????????????)(???)))))


Output:
λ> (???) [1,2,4,5,9,9,94,3,345,9,534]
[1,2,4,5,94,3,345,534,9,9,9]
>>
>>55454866
messed up copying, should be
{-# LANGUAGE BangPatterns #-}

(?????)=0
(????????) = null
(?????????) = replicate
(??????????) = 9
(???????????) = head
(????????????) = (==)
(?????????????) = (+)
(??????????????) = tail
(???????????????) = (:)
(????????????????) = 1

(??????)(?)(??)(???)=if(?)then(??)else(???)
(?)(??)=(??)((?)(??))
(???)=(????)(?????)
(????)=(?)(???????)
(???????)(?)(??)(???)=(??????)((????????)(???))((?????????)(??)(??????????))((??????) ((????????????)(??????????)((???????????)(???)))((?) ((?????????????)(??)(????????????????))((??????????????)(???)))((???????????????) ((???????????)(???)) ((?) (??) ((??????????????)(???)))))
>>
>>55454872
??
???
???
What?
>>
Here is the assignment in Pajeet Java.

package stuff;

import java.util.Random;

public class ArraySortOnNine {


public int[] sortOnNine(int[] array) {
int nines = 0;
for (int i = 0; i < array.length; i++)
if (array[i] == 9)
nines++;
int[] nine = new int[nines];
int[] normal = new int[array.length - nines];

int j = 0;
for (int i = 0; i < array.length; i++)
if (array[i] != 9)
normal[j++] = array[i];

for (int i = 0; i < nine.length; i++)
nine[i] = 9;

return concat(normal, nine);
}

public void printArray(int[] test) {
for (int i = 0; i < test.length; i++) {
System.out.print(test[i] + ",");
}
System.out.println("");
}

public void arraySwap(int index1, int index2, int[] array) {
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}

public int[] concat(int[] a, int[] b) {
int aLen = a.length;
int bLen = b.length;
int[] c = new int[aLen + bLen];
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
}


It can do 100 000 arrays with length 10 in about 5000 millis.
>>
>all these shitty solutions taking linear extra space
>some of them actually taking quadratic time
/g/ is full of Pajeets as expected
>>
>>55454898
The haskell one posted earlier actually does not. The cons cells of the input list become garbage at the same time as new ones are constructed for the output, so it runs in constant space.
>>
>>55454919
You're supposed to modify the input, not return a new one, so the Haskell version is already disqualified.
>>
>>55454971
Ok, instead you can take as input a mutable cell (IORef) containing the list to be modified. Then use the described algorithm and put it in the IORef.

Before doing that you need to put a dummy value in the IORef so that it doesn't keep references to the old list.
>>
File: faster.jpg (8 KB, 259x194) Image search: [Google]
faster.jpg
8 KB, 259x194
#include <stdio.h>
#include <stdlib.h>

void swap(int* array, int left, int right) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}

void sortnine(int* array, int size) {
int left = 0;
int right = size - 1;

while(1) {
while(left < size && array[left] != 9) {
left++;
}
while(right >= 0 && array[right] == 9) {
right--;
}
if(left >= right) {
break;
}
swap(array, left, right);
}
}

void printarray(int* array, int size) {
int n;

for(n = 0; n < size; n++) {
printf("%d ", array[n]);
}
}

int main(void) {
int array[] = {3,9,4,5,1,1,1,9,0,7};
int size = sizeof(array) / sizeof(int);

sortnine(array, size);
printarray(array, size);

return EXIT_SUCCESS;
}


Super fast C master race
>>
>>55452859
What the hell do those symbols even mean? Lisp is indecipherable.
>>
>>55454994
That will take linear space.
>>
>>55455031
>I don't know common procedures and keywords from this language's standard library, therefore nobody can understand it
>>
>>55455039
No it won't, for the same reasons as the algorithm that doesn't use an IORef
>>
>>55455041
>You have to memorize dozens of obtuse abbreviations and syntax (or lack thereof) before you can make any sense of the code, because fuck readability amirite?
>>
function arrayshit(arr) {
var arr_9 = [];
var arr_new = [];
for(var i=0; i<arr.length; i++) {
if(arr[i] !== 9) {
arr_new.push(arr[i]);
} else if(arr[i] === 9) {
arr_9.push(arr[i]);
}
}
arr_new = arr_new.concat(arr_9);
console.log(arr_new);
}


arrayshit([1,4,3,9,5,9,4,9,2,9,3,4,6]);
// output [ 1, 4, 3, 5, 4, 2, 3, 4, 6, 9, 9, 9, 9 ]


in JS
>>
>>55455025
>while keeping the relative order of the other elements
welp I guess you're dead
>>
>>55453355
/thread
>>
function toTheBack(arr){
let filtered = arr.filter(num => num != 9);
for(var counter= filtered.length; counter < arr.length; counter++)
filtered.push(9)
return filtered;
}


First filters out the 9s, then checks the diff in size(i.e. how many 9s have been filtered out), then adds that amount of 9s to the end.
>>
>>55453355
*(!=9)
>>
>>55452985
[USER WAS STABBED FOR THIS POST]
>>
>>55454892
Slow
>>55455025
Using var++ and not ++var
Also run it 100000000 and show time
>>
>>55455090
NO PLEASE I DIDN'T REA-
>>
//Method call
pushToEnd(array, 9);

// Method
public static void pushToEnd(int[] array, int target) {
int count = 0;

for(int i = 0; i < array.length; i++) {
if(array[i] != target) {
array[count++] = array[i];
}
}

while (count < array.length) {
array[count++] = target;
}
}
>>
>>55455602
Probably should have just shown the whole thing like this in the first place:
public static void main(String[] args) {

int[] array = { 1, 2, 9, 3, 4, 9, 5, 6, 9, 7, 8 };

System.out.println("Order before:");
for(int i=0; i<array.length;i++){
System.out.print(array[i]);
}

System.out.println();
pushToEnd(array,9);
System.out.println();

System.out.println("Order after:");
for(int i=0; i<array.length;i++){
System.out.print(array[i]);
}

}

public static void pushToEnd(int[] array, int target) {
int count = 0;

for(int i = 0; i < array.length; i++) {
if(array[i] != target) {
array[count++] = array[i];
}
}

while (count < array.length) {
array[count++] = target;
}
}
>>
def ninesToEnd(arr):

for i in range(len(arr)):
if arr[i] == 9:
arr.append(arr.pop(i))

return arr
>>
Clojure:

(sort-by #(= % 9) input)

Why would u use anything else?
>>
def put_nines_in_the_lines(a):
out_array = [el for el in a if el!=9]
out_array+=[9 for i in range(len(a) - len(out_array))]
return out_array

still don't know how to linecode
>>
stand back

template<class Container>
void move_to_end(Container &container, typename Container::value_type value)
{
const auto size = container.size();
for(typename Container::size_type i = 0; i < size; ++i)
{
if(container[i] != value) continue;

for(auto j = i + 1; j < size; ++j)
{
if(container[j] == value) continue;

std::swap(container[i], container[j]);
break;
}
}
}


0.284891s for 1M repetitions
>>
void sort_nine(size_t n, int arr[static n])
{
int *ptr, *sav;

for (ptr = arr, sav = ptr; ptr < arr + n; ++ptr) {
if (*ptr != 9) {
*sav = *ptr;
++sav;
}
}

for (; sav < ptr; ++sav) {
*sav = 9;
}
}
>>
File: pearl_cockatiel.54220935_std.jpg (221 KB, 681x1000) Image search: [Google]
pearl_cockatiel.54220935_std.jpg
221 KB, 681x1000
pls no bird... I'm too cute to die :3 :3
>>
My java implementation:
 
int[] result = new int[input.length];
int count =0;
int indexCount = 0;
for(int i=0;i<input.length;i++){
if(input[i] != 9){
result[indexCount] = input[i];
++indexCount;
}else{
++count;
}
}

for(int i=indexCount ;i<input.length;i++){
result[i] = 9;
}

return result;



Wrote it here on a phone. Pls r8
>>
File: hahahaha.gif (774 KB, 600x533) Image search: [Google]
hahahaha.gif
774 KB, 600x533
Let's did it:
N = 50
L = np.random.randint(0, 100, N)
L[np.random.choice(np.arange(N),int(0.2*N))] = 9
print(L)

nines_count = 0
i = 0
j = 0
while i < len(L) - nines_count and j < len(L):
if L[j] == 9:
nines_count += 1
elif j == 0 or j > i:
L[i] = L[j]
i += 1
j += 1
print(nines_count)
L[-nines_count:] = 9
print(L)
>>
>>55456022
Doesn't that have horrible run time?
>>
>>55456114
What? It's O(n).
Also, the cache locality is fine.
>>
@echo off
Shutdown -s
>>
>>55452571
<sound of me outsourcing it to India>
>>
>>55455844
see >>55453319
>>
>>55455930
SLOW

>>55456022
That's some fast shit
.5 for 100M repetitions
>>
File: everytim.jpg (25 KB, 250x250) Image search: [Google]
everytim.jpg
25 KB, 250x250
>>55455145
fuck......
>>
>>55456264
idk what settlings ideone uses, ill give some results in a bit from my own machine
>>
>>55456343
I am testing with -o3
>>
>>55456376
alright on my own shitty 2.2GHz machine i get 0.109006s
>>
>>55452571
def s(l:List[Int]) ={
l.filter(_ != 9) ++ l.filter(_ == 9)
}
>>
void sortN(int *a, int aSize)
{
int i, j=aSize-1, k;

for (i = 0; i < j; i++)
if (a[i] == 9)
{
for (; a[j] == 9; j--);

for (k = i; k < j; k++)
a[k] = a[k+1];
a[j] = 9;
}
}
>>
>>55456563
1.6 sec
>>55456513
How many runs and which algh is yours
>>
>>55452571
test
>>
>>55456584
1M runs of >>55455930
>>
>>55456599
int a;
>>
>>55456611
So about 10 seconds for 100m runs. You can do better anon.
>>
>>55456584
>1.6 sec
Are you retarded?
>>
File: Capture.png (35 KB, 1081x733) Image search: [Google]
Capture.png
35 KB, 1081x733
>>55456650
Testing it on 100m runs
>>
>>55456632
undoubtably, though i went by the "quick" in the op, so i didnt look too much into the problem outside of the naive solution
>>
>>55452571
N-NO BIRDO I-I-I D-DON'T HOW PROGRAM

W-WAIT NO STOP NOO AAAAAAAAAHHH
>>
>>55456708
I am OP, your function is with complexity O(n^2) while mine is O(n)
>>
>>55452571
public function sortArray(ar):array
{
for (i = 0; i < ar.length - 1; i++)
{
if (ar[i] == 9)
{
ar.splice(i, 1)
ar.push(9)
}
}
}

As3 master race!
>>
>>55456761
i thought you meant quick as in the time it takes to write it
>>
>>55455811
Fug, I'm such a pajeet, just realized this doesn't work for arrays with consecutive nines. This should work and is still linear, but not as concise:

def ninesToEnd(arr):

no_nine_arr = list()
nine_arr = list()

for n in arr:
if n != 9:
no_nine_arr.append(n)
else:
nine_arr.append(n)

return no_nine_arr + nine_arr
>>
def f(xs: Array[Int]) = { val (y, n) = xs.partition(9 ==); n ++ y }
>>
(defn sort9
[numbers]
(letfn [(nine? [n] (= 9 n))]
(concat (remove nine? numbers) (filter nine? numbers))))
>>
>not using best language
{(⍵∼9),⍵/⍨⍵=9}
>>
>>55456911
You missed a _
>>
>>55457158
It's not mandatory in that situation.
>>
>>55457117
Sorry, I don't speak jihad
>>
>fast as possible
>little space as possible
lol
Join[Cases[#2, Except[9]], Array[9 &, #1]] &[Count[#, 9], #] &
>>
>>55457319
Even shorter version
Join[Cases[#, Except[9]], Cases[#, 9]] &
>>
>>55457293
Your loss.
>>
>>55457180
Oh that's cool. Not sure how readable it is though.
>>
R doesn't have any easy/efficient way to modify vectors in place. Best you can do is preallocate and assign as you go.

input <- c(9, 9, 9, 9, 0, 5, 3, 9, 9, 0)
inputVec <- input == 9
output <- rep(0,length(input))
output[1:sum(!inputVec)] <- input[!inputVec]
output[(sum(!inputVec)+1):length(input)] <- 9


7.64 seconds on 1M repeats.
>>
>>55453372
>using the smiley with a carat nose
>>
>>55457517
>using the smiley without a carat nose
>>
def ninesAtEnd(array):
result = []
numNines = 0

for num in array:
if num != 9:
result.append(num)
else:
numNines += 1

for i in range(numNines):
result.append(9)

return result
>>
>>55456684
hi hawkie
>>
>>55457528
.... as you should
>>
>>55457536
>camelcasing in python
kill yourself
>>
>>55456684
Ok, new try:

void sortN(int *a, int aSize)
{
int i, j, k;
bool c = true;

for (i = 0; c && i < aSize - 1; i++)
if (a[i] == 9)
{
c = false;
for (j = i+1; j < aSize; j++)
if (a[j] != 9)
{
a[i] = a[j];
a[j] = 9;
c = true;
break;
}
}
}
>>
>>55457661
>not camelcasing
enjoy your wasted horizontal space
>>
>>55453110
faglab wins
>>
>>55457663
Even slower
Hitting 2.5
Try something with linear complexity
>>
Currynigger code coming thru
    public static void main (String[] args){
int[] input = {8, 4, 8, 9, 7, 2, 9, 9, 9, 7, 6};
for (int i:ninesAtEnd(input)){
System.out.print(i);
}
}

public static int[] ninesAtEnd(int[] input){
int[] output = new int[input.length];
int currentIndex = 0, numberOfNines = 0;

for (int number: input){
if (number != 9){
output[currentIndex] = number;
currentIndex += 1;
} else {
numberOfNines += 1;
}
}
for (int i=0; i < numberOfNines; i++){
output[currentIndex + i] = 9;
}
return output;
}
>>
>>55453110
c(input[!input==9],input[input==9])


turns out the R equivalent kills my previous attempt in >>55457488. 2.15 seconds for 1M runs.
>>
>>55452571
What have you been doing today?
Oh you've only got that much done?
Well,m we need to get project X out the door ASAP, so I'm going to need you to stay back and do this assignment for me.

Thanks...
>>
>>55453471
you don't need list for anything
def sort9(some_list):
return filter(lambda x: x != 9, some_list) + filter(lambda x: x == 9, some_list)
>>
>>55453501
And you guys keep telling me how godly C++ is...
>>
>>55457976
off yourself
>>
>>55457976
That's C
Also there are way better solutins like
>>55456563
or
>>55453555

The first is 45% faster than the second
>>
>>55453471
>>>55453319
>Bird, pls
>def sort9(some_list):
> return list(filter(lambda x: x != 9, some_list)) + list(filter(lambda x: x == 9, some_list))

I STOLE THIS CODE AND PASSED IT THROUGH GOOGLE TENSORFLOW. I AM GOD! FUCK BIRDS!
>>
>>55452571
Not my favorite language but anyway:

function [ar1] = nines(ar)
ar1=[ar(ar~=9) ar(ar==9)];
end
>>
public static int[] sortNines(int[] ss_array) {
int j = 0;
int nineMarker = 0;
for (int i = 0; i < ss_array.length - nineMarker; i++) {
if (ss_array[i] == 9) {
for (int k = i; k < ss_array.length - 1; k++) {
ss_array[k] = ss_array[k + 1];
}
ss_array[ss_array.length - 1] = 9;
i--;
nineMarker++;
} ;
}
return ss_array;
}^:
>>
>>55457678
>camelCasing
Enjoy your designated shitting streets.
>>
>>55457735
OK, this time i've counted all non-nines, put them at beginning, and put nines at end.

void sortN(int *a, int aSize)
{
int i, j, k;

for (i = 0; i < aSize; i++)
if (a[i] != 9)
k++;

if (k == aSize)
return;

for (i = 0, j = 0; i < aSize && j < k; i++)
if (a[i] != 9) {
a[j] = a[i];
j++;
}

for (i = k; i < aSize; i++)
a[i] = 9;
}


Any advice.
>>
pushNines = # //. {pre___, 9, post__} -> {pre, post, 9} &


Mathematica has nice pattern matching capabilities.
>>
>>55458472
I come up with this:

void sortN(int *a, int aSize)
{
int i, j;

for (i = 0, j = 0; i < aSize; i++)
if (a[i] != 9) {
a[j] = a[i];
j++;
}
for (i = j; i < aSize; i++)
a[i] = 9;
}
>>
>>55452571
These degraded in quality quickly.
>>
>>55452859
>in-place
Don't think you know what that means.
>>
>>55458839
rplaca and rplacd are as in-place as you can get in Lisp.
>>
def g(i = ''):
return (''.join([c + 'o' + c if c.lower() in 'aieou' else c for c in i])).upper()

print g(raw_input(' > '))
>>
>>55457905
You do need list() in Python3 senpai :^*
>>
uncurry (++) . partition (9 /=)
>>
  static int[] sort9(int[] array)
{
return array.OrderBy(x => x == 9).ToArray();
}
>>
>>55459929
Is it not beautiful?
>>
>>55452571

Clumsy solution.

#!/usr/bin/env perl
use strict;
use warnings;

use Data::Printer;

my @input = qw/9 9 9 1 2 2 2 3 4 9 5 6/;
my @output = grep /[0-8]/, @input;

push @output, 9 for @output..@input;

p @output;
>>
>>55460739

Balls - pretend that's @output..@input-1...
>>
File: 1457993687021.jpg (37 KB, 680x453) Image search: [Google]
1457993687021.jpg
37 KB, 680x453
>>55460739
>regex for sorting ints
i mean i'm sure it works, but

why did you do that
>>
>>55460760

Permanent, crippling regex-related psychosis.
>>
>>55454102
That's brilliant. Gotta love Rust
>>
>>55456189
Found the skid who thinks shortcuts can be viruses
>>
>>55460760
because it isn't really sorting.
>>
Is it cheating to use a linked list for this?
>>
>>55453990
You shouldn't have added that semicolon to the end of your expression.
>>
>>55461340
What part of "USE AS LITTLE SPACE AS POSSIBLE" do you not understand?
>>
>>55461633
I'd happily take O(n) time with O(n) additional space over O(nlgn) with O(1) additional space in many contexts.
>>
>>55461557
I'm not returning anything, sort_by_key mutates the array itself
>>
>>55452571
easy
>>55455065
Let me show you a better way
function rr(arr) {
return arr.reduceRight(function(a,v){
if(v !== 9) a.unshift(v);
else a.push(v);
return a;
},[]);
}
>>
>>55452571

O(n)
λ> let f = foldr (\x xs -> if x == 9 then xs ++ [x] else x:xs) []
λ> f [1,2,3,4,9,1,2,9,3]
[1,2,3,4,1,2,3,9,9]
>>
>>55452571
void remove9(std::list<int>& zalist){
auto it=zalist.begin();
for ( ; it != zalist.end(); ++it){
if(*it==9){
auto there=it;
++it;
break;
}
}
for( ; it != zalist.end(); ++it){
if(*it!=9){
*there=*it;
++there;
}
}
for( ; there != zalist.end(); ++there){
*there=9;
}
}
>>
def sort_9_in_place(array):
index = 0

for n in array:
if n != 9:
array[index] = n
index += 1

while index < len(array):
array[index] = 9
index += 1


twink friend of mine coded this
>>
my array doesn't have any 9s in it

:^)
>>
File: file.png (33 KB, 1688x606) Image search: [Google]
file.png
33 KB, 1688x606
No int type and while being as short as possible and being as fast as possible are usually mutually exclusive, I usually go for readability.

MoonScript.

sortArray = (arr) ->
sorted = [e for e in *arr when e != 9]
nines = [e for e in *arr when e == 9]

table.insert sorted, 9 for _ = 1, #nines

sorted

arr = {1, 9, 3, 9, 7, 7, 9, 9, 2}

print "[%s]"\format table.concat arr, ", "
print "[%s]"\format table.concat (sortArray arr), ", "
>>
void sortN(int arr[], int aSize)
{
for (int i = 0; i < aSize; i++)
{
if (arr[i] == 9)
{
for (int j = i; j < aSize; j++)
{
arr[j] = arr[j + 1];
}
arr[aSize - 1] = 9;
}
}
}


t. CS Major
>>
>>55462224
nice insertion sort
>>
in pseudocode using sleepsort:

for eachNum in length(list):
if list[eachNum] is 9:
sleep(length(list))
else:
sleep(eachNum)
>>
>>55462316
What's that output for the following list?
[100 9]
>>
>>55462414
[100, 9]

Note that I'm iterating over the length of the list, not the list itself.

[100] gets sleep(1), [9] gets sleep(2).
>>
def end_niner(thing):
for i in thing:
if i == 9:
fuck = thing.pop(thing.index(i))
thing.append(fuck)
print(thing)


Pls no stabbu
>>
>>55462448
>>55462414
i mean if you want to quibble it's not a true sleepsort, since i'd have to implement it as something like
sleep <- function(x,y)
wait(x)
return(y)
>>
>>55462448
>>55462481
Wouldn't it sleep 100 for the 100 and 2 for the 9?
>>
>>55462513
oh shit I'm dumb, nevermind
>>
>>55452841
Just started learning functional python and I don't understand how this works.

The lambda takes an input and returns the subset of it that equals to 9.

But when you're sorting the array, why does sorting it by that subset result in all the 9s being at the end?
>>
void move9s(int **a, int n)
{
int *r = calloc(n, sizeof(int));
int b = 0, e = n-1;
for (int i = 0; i < n; ++i) {
if (*a[i] == 9)
r[e--] = *a[i];
else
r[b++] = *a[i];
}
*a = r;
}


Not in place but linear time.
>>
>>55462513
This might help, as a more complete version:
newSleep <- function(time,num) {
wait(time)
return(num)
}
for (eachNum in seq(1,length(list)) ) {
if (list[eachNum] == 9) {
newSleep(length(list), list[eachNum])
} else {
newSleep(eachNum, list[eachNum])
}
}

I mean obviously I'm leaving out a ton of implementation details on newSleep, but you should get the idea.
>>
File: bird stealing knife.gif (2 MB, 300x173) Image search: [Google]
bird stealing knife.gif
2 MB, 300x173
bird stealing knife.gif
Is here to stop you, evil black bird with knife.

Go, people. You are free/safe now.
>>
>>55462543
that's not what the lambda does.
isNine = lambda x : x == 9
creates a function with one argument that returns True if that argument == 9 and False otherwise and sets the variable isNine to be that function.
isNine(4) -> False
isNine(9) -> True
the last line sorts the array with isNine as the key to sort by. It's not looking at the value of the numbers when it's sorting, just that True/False value given by isNine. False < True so all the non-nine numbers go before the nines in arr.
>>
>>55462543
>The lambda takes an input and returns the subset of it that equals to 9.
No, it takes a single value and returns a boolean of whether it equals 9.

Then, the sorted function applies that lambda to every value.
>>
>>55462620
Aaah, that's a very clever solution!

Thanks for the explanation
>>
>>55462620
>the last line sorts the array with isNine as the key to sort by. It's not looking at the value of the numbers when it's sorting, just that True/False value given by isNine. False < True so all the non-nine numbers go before the nines in arr.
that seems like it would be very sensitive to the sorting algorithm used
>>
>>55462676
what I mean is, an algorithm that potentially swaps the position of items with the same key would destroy the order in this case where the key is a boolean
>>
>>55462676
>>55462695
The python spec guarantees that the sort is stable.
It's a concise solution but it's also relatively slow because the sort is probably O(nlgn).
>>
>>55462723
Ah, ok.
>>
Why has no one shopped this yet
>>
File: 242941_v1.jpg (26 KB, 500x375) Image search: [Google]
242941_v1.jpg
26 KB, 500x375
>>55462734
fuck, forgot image
>>
linear time, constant space, someone already did it like this too
but this is the best way

void fun(int* a, int n)
{
int i, j;

for (i = 0, j = 0; j < n; i++, j++)
{
if (a[j] == 9)
j++;
a[i] = a[j];
}
while (i < n)
a[i++] = 9;
}
>>
>>55452571
y'all aren't thinking with pointers.
void plan9(int *array, int n){
int nines = 0;
while (--n) nines += *array++ == 9, *(array - nines) = *array;
while (nines--) *array-- = 9;
}
>>
>>55463314
or, since others are going for single letter vars to look even smaller...

void plan9(int *x, int n){
int c = 0;
while (--n) c += *x++ == 9, *(x - c) = *x;
while (c--) *x-- = 9;
}
>>
>>55452571
>>> from itertools import chain
>>> def g(i):
... x = (_ for _ in i if _ != 9)
... y = (_ for _ in i if _ == 9)
... return chain(x, y)


Generators. Fit in cache lines, and take the same amount of time as iterating.
>>
>>55463426
Huh shit, nobody else chained generators. Y'all are fags. You should at least TRY to use the best feature of the language.
>>
>>55452571
void sortN(int *a, int size)
{
int i=0, n=0;

for( ; i < size-n; )
{
if(a[i] == 9)
{
++n;
a[i] = a[i + n];
}
else
{
++i;
}
}

for(; i < size; ++i)
{
a[i] = 9;
}
}

There's probably a better way...
>>
>>55463542
>There's probably a better way...
>>55463379
same strategy, fewer branches, one less temp.
>>
File: am3.jpg (32 KB, 640x480) Image search: [Google]
am3.jpg
32 KB, 640x480
>>55462471
def end_niner(thing):
return [thing.append(thing.pop(thing.index(i))) for i in thing if i == 9]


made it shorter.

Could it be done like this using a lambda?
>>
>>55456072
Roughly what I was thinking only difference being I was going to use C#. Too lazy to write it on my phone.
>>
>>55463629
>allocating a list to return

Nigga you already have the data. Why copy it?
>>
>>55463994
Huh, hadn't thought about that

So what, just get rid of the return?
>>
>>55463994
side effects
>>
>>55464025
>>55464028
G E N E R A T O R S

See >>55463426
>>55463464
>>
File: f127fb2f53673f6e37edc204.jpg (273 KB, 800x535) Image search: [Google]
f127fb2f53673f6e37edc204.jpg
273 KB, 800x535
>>55452571

def nines_at_end(items):
return [i for i in items if i != 9] + [9] * items.count(9)


Easy peasy, Japanesey
>>
>>55464121
>allocating a list
All these amateur python """programmers"""

Bet y'all are in fucking web dev.
>>
>>55464151
What would you do then, oh mighty neckbeard?
>>
>>55464184
See>>55464078
>>
>>55464151
I'm in embedded and only use Python for testing and PoC-ing. Incidentally, I do like to use yield, but I'm too lazy to memorize all the built-ins. I wrote none of the Python solutions. I hate that I feel a need to justify myself on a Brazilian bonsai BBS.
>>
10 print fuck da crow-lice
20 goto 10
>>
File: 1456421123829.jpg (49 KB, 512x384) Image search: [Google]
1456421123829.jpg
49 KB, 512x384
B-but the language I know doesn't do shit like that.
>>
>>55452571
Is swap a native function in C?
>>
#include <vector>
#include <algorithm>
int main()
{
using namespace std;
vector<int> arr = {0,1,2,9,1,9,9,4,5,6,1,9};
stable_partition(begin(arr),end(arr),[](int a) -> bool { return a != 9; });
return 0;
}
>>
>>55454024
Don't run this! It deleted my home folder! Fuck you 4chan!
>>
Here's one for a linked list, hopefully the bird doesn't know the difference.
(define (addnines alist)
(define (inner alist rope nines)
(if (= rope 0)
(append alist nines)
(inner alist (- rope 1) (cons 9 nines))))
(inner alist (length alist) '()))
>>
function phpbait ($number) {
$number = array();

while($number == 9) {

unset($number['9']);
$number['9'] = $number;
}
print_r($number);
}


}
>>
>>55465252
Ayy lmao just misinterpreted the question entirely, that one writes as many nines as there are items in the list.

Here's one that does what OP meant:
(define (allnines alist)
(define (inner alist iter nines)
(if (null? iter)
(append alist nines)
(if (= 9 (car iter))
(inner alist (cdr iter) (cons 9 nines))
(inner alist (cdr iter) nines))))
(inner alist alist '()))
>>
>>55452571
Dude this code is fucking wrong, you got stabbed.
>>
fucking nerds
>>
>>55452571
>
while (a[i] != 9)
++i;

Someone please explain to me how this isn't an infinite loop if a[i] doesn't contain a 9? Like wouldn't it just run off out of the array bounds, and not stop until it hit a 9 randomly in ram or ran out of ram to look through entirely?
>>
>>55452571
ninesort ns = filter (/=9) ns ++ filter (==9) ns
>>
>>55463464
>Huh shit, nobody else chained generators
bull-fucking-shit

>>55457117
>>55456534
>>55453110
>>55457832
>>
>>55452571
Fail
If 9 is in the original elements all elements following that 9 will be overwritten.
>>
>>55453355
>>55459929
you forgot
import Data.List
>>
>>55452571
OH FUCK

def bird(l):
for i,n in enumerate(l):
if n == 9:
del l[i]
l.append(n)
>>
>>55461693
Or you can take O(n) time with without any extra memory
>>
>>55465066
>running code that you dont underatand
Kys
>>
File: Capture.png (36 KB, 1156x657) Image search: [Google]
Capture.png
36 KB, 1156x657
>>55465806
Yeah forgot about that, fixed
void sortN(int* a, int aSize) {
int i = -1;
while (a[++i] != 9 && i<aSize) { };
int posN = i;
for (;i < aSize; ++i)
if (a[i] != 9)
swap(*(a+i), a[posN++]);
}

>>55466420
Nope it works fine
>>
>>55469412
>Windoze 10
Kys
Thread replies: 225
Thread images: 19

banner
banner
[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y] [Home]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
If a post contains personal/copyrighted/illegal content you can contact me at [email protected] with that post and thread number and it will be removed as soon as possible.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com, send takedown notices to them.
This is a 4chan archive - all of the content originated from them. If you need IP information for a Poster - you need to contact them. This website shows only archived content.