Jump to content
php.lv forumi

Domātājiem!


Bremze
 Share

Recommended Posts

Šis variants: 

0L to 9876543210L by 2013 map(_.toString())filter(a=>(a.distinct.size==a.size && a.contains("2013"))) map println

3.8 sekundes, no kurām 1 sekunde ir to _.toString un 2.4 ir a.distinct

 

Izveidojot ar pieeju kāda ir c++ kodā:

def isUniqueDigits(a:Long):Boolean={
    var b=a;
    var arr=Array(0,0,0,0,0,0,0,0,0,0)
    while (b>0) {
      if (arr((b%10).toInt)==1) return false
      arr((b%10).toInt)=1
      b=b/10
    }
    true    
  }
  
  def contains2013(a:Long):Boolean={
    var b=a
    while (b>0) {
      if (b%10000==2013) return true      
      b=b/10
    }
    false
  }
  
  0L to 9876543210L by 2013 foreach(a=>if (isUniqueDigits(a) && contains2013(a)) println(a))

Laiks:0.42 sekundes - jāpiezīmē, ka tas ir labāks kā c++ kodam.

Link to comment
Share on other sites

Sadalot visu intervālu mazākos intervālos un padodot to izpildīt paralēli: 0.27 sekundes

def isUniqueDigits(a:Long):Boolean={
    var b=a;
    var arr=Array(0,0,0,0,0,0,0,0,0,0)
    while (b>0) {
      if (arr((b%10).toInt)==1) return false
      arr((b%10).toInt)=1
      b=b/10
    }
    true    
  }
  
  def contains2013(a:Long):Boolean={
    var b=a
    while (b>0) {
      if (b%10000==2013) return true      
      b=b/10
    }
    false
  }
  
  var seqOfWorks=for{
    i <- 0L to 9876543210L by 20130000
  } yield i to i+20130000 by 2013  
  seqOfWorks.par.map(_.filter(a=>isUniqueDigits(a) && contains2013(a)).map(println))

Šis viss strādātu vēl ātrāk, ja notiktu Int robežās, jo kā par nelaimi, Scalai ir paralēlu intervālu klase, bet strādā tikai ar int intervāliem.

Link to comment
Share on other sites

neoptimizēta Java:

package fig;

public class Fig 
{
    public static int prepFig (String figString)
    {
	int fig[] = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

	for (int i = 0; i < figString.length (); i++)
            if (++fig[figString.charAt(i) - 48] > 1)
                return 0;
	return 1;
    }
    
    public static void main(String[] args) 
    {
	for (long i = 2013; i <= 9876543210L; i = i + 2013)
	{
            String figString = Long.toString(i);

            if (figString.contains("2013"))
                if (prepFig (figString) == 1)
                    System.out.println(i);
	}
    }
}

0.62 s

 

gan jau ir vērts norādīt CPU, RAM un OS

 

i5-2520M @ 2,50 GHz, 16 GB, Win7-64

Edited by ieleja
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

×
×
  • Create New...