functional way doing array stuff/ lambda functions

Namal via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Dec 14 03:45:50 PST 2015


On Sunday, 13 December 2015 at 01:01:07 UTC, cym13 wrote:

> That's because you want to modify it in product passing it by 
> ref.

Hmm, that seems different to c++.


On Sunday, 13 December 2015 at 11:37:50 UTC, cym13 wrote:

>
> As cryptic as it is this means that the range you passed to 
> reduce is empty. Reduce needs it not to be because as I said it 
> needs a seed and as you didn't pass one explicitely as argument 
> it tries to take the first element of the range (and fails 
> obviously). You can either pass it a seed explicitely or add a 
> non-empty check before the return.


Here is the full code, where I changed the product function. 
Sorry, I don't understand what the difference now and why it 
crashes.

import std.stdio, std.array, std.algorithm;


int product(const ref int[] arr){

	/*int p = 1;
	foreach(i;arr)
		p*=i;
  	return p;*/
  	
  	return arr.reduce!((a, b) => a*b)();

}


int [] prim_sieve(int n){

	bool [] T;
	T.length = n;
	T[0] = true;
	T[1] = true;
	
	for(int i = 2; i*i <= T.length-1;++i){
		for(int j = i*i;j<T.length; j+=i)
			T[j] =true;
	}
	int[] v;
	foreach(int i,t;T)
		if(t==false)
			v~=i;
	return v;
}

int[] prim_factors(int n, const ref int[] P){
	
	int[] v;
	
	for(int i; P[i]*P[i]<=n;++i){
		while(n%P[i]==0){
			v~=P[i];
			n/=P[i];
		}
	}
	if(n>1)
		v~=n;
		
	return v.dup.sort.uniq.array;

}


void bubblesort(ref int[2][] v){

	size_t n = v.length;
	do{
		int newn = 1;
		for(int i = 0;i<n-1; ++i){
			if(v[i][1]>v[i+1][1]){
				auto temp = v[i];
				v[i] = v[i+1];
				v[i+1] = temp;
				newn = i+1;
			}
		}
		n=newn;	
	}
	while(n>1);
}



void main(){
	
	int[] P = prim_sieve(500);
	
	int[2][] v;
	
	foreach(k;1..100001){
		auto t = prim_factors(k,P);
		v~= [k,product(t)];
	}
	
	bubblesort(v);
	
	writeln(v[9999][0]);
}


More information about the Digitalmars-d-learn mailing list