Thread: Other ways of doing that.

Results 1 to 10 of 10
  1. #1 Other ways of doing that. 
    Registered Member

    Join Date
    Jan 2013
    Posts
    485
    Thanks given
    58
    Thanks received
    132
    Rep Power
    248
    Well I had this recent question today which I've got a solution for, but I am really interested in other ways to do this, FOLLOWING the question rules.
    Basically, you have a number, with any amount of digits.

    We need to count how many "valid" pairs the number has.
    A valid pair is when you subtract the biggest digit in a pair by the lowest digit in a pair and it is <= 3.

    For exmaple, this number has 3 valid pairs: 6854

    Why?

    5 - 4 = 1
    8 - 5 = 3
    8 - 6 = 2

    All of them are <= 3.

    Rules: You can only use loops and variables or anything else besides built-in java functions which will do the whole job for you, well you can use Math class though, well you get what I mean.

    My solution:


    Code:
    	
    		int a = 8654;
    		int digit1 = 0, digit2 = 0;
    		int sum = 0;
    		int min, max;
    		while (a > 0) {
    			digit1 = getInt(a);
    			digit2 = getInt((int)Math.floor(a / 10));
    			max = Math.max(digit1, digit2);
    			min = Math.min(digit1, digit2);
    			if (max - min <= 3) {
    				sum++;
    			}
    			a /= 10;
    		}
    		System.out.println(sum);
    Method:

    Code:
    	static int getInt(int n) {
    		double holder = (double) n / 10;
    		int am = n / 10;
    		return ( (int) ((holder - am) * 10));
    	}
    Can you solve the same thing, with another way? note, int a can be any number, it must every entered number besides max integer.
    Also it must be positive.
    Reply With Quote  
     

  2. #2  
    Renown Programmer

    Join Date
    Dec 2010
    Posts
    2,876
    Thanks given
    508
    Thanks received
    1,898
    Rep Power
    5000
    i started coding this last night but its very slow [Java] hi rune-kids - Pastebin.com
    never talk to me or my wife's son ever again
    Reply With Quote  
     

  3. Thankful users:


  4. #3  
    Registered Member

    Join Date
    Jan 2013
    Posts
    485
    Thanks given
    58
    Thanks received
    132
    Rep Power
    248
    Quote Originally Posted by based_bass View Post
    i started coding this last night but its very slow [Java] hi rune-kids - Pastebin.com
    lol you dont need to return how many numbers have 3 minor pairs, u need to return how many minor pairs a number will have, so it must work with any number u give the program.
    Reply With Quote  
     

  5. #4  
    q.q


    Join Date
    Dec 2010
    Posts
    6,519
    Thanks given
    1,072
    Thanks received
    3,535
    Rep Power
    4752
    this from project eular?


    here's my solution

    Code:
    public class PairCount {
    
    	public static void main(String args[]) {
    		PairCount pc = new PairCount();
    		System.out.println("num: 6854 pairs: " + pc.getPairs(6854));
    	}
    
    	final int MAX_DIFF = 3;
    
    	public int getPairs(int number) {
    		int pairs = 0;
    		String num = String.valueOf(number);
    		for (int i = 0; i < num.length() - 1; i++) {
    			int val1 = num.charAt(i);
    			int val2 = num.charAt(i + 1);
    			int diff = Math.abs(val1 - val2);
    			if (diff <= MAX_DIFF)
    				pairs++;
    		}
    		return pairs;
    	}
    }
    ezmode, didn't really test it beyond your number so may not be completely working
    Reply With Quote  
     

  6. #5  
    Programmer, Contributor, RM and Veteran




    Join Date
    Mar 2007
    Posts
    5,147
    Thanks given
    2,656
    Thanks received
    3,731
    Rep Power
    5000
    Quote Originally Posted by JonyFX View Post
    Code:
    	static int getInt(int n) {
    		double holder = (double) n / 10;
    		int am = n / 10;
    		return ( (int) ((holder - am) * 10));
    	}
    Can be turned into just: "n % 10"

    Only other thing I'd pick over with the main bit of your code is the scope of the variables: digit1,digit2,min and max can be declared inside the loop, rather than outside.
    .
    Reply With Quote  
     

  7. #6  
    Registered Member

    Join Date
    Jan 2013
    Posts
    485
    Thanks given
    58
    Thanks received
    132
    Rep Power
    248
    Quote Originally Posted by Graham View Post
    Can be turned into just: "n % 10"

    Only other thing I'd pick over with the main bit of your code is the scope of the variables: digit1,digit2,min and max can be declared inside the loop, rather than outside.
    Doesn't declaring object name over and over waste memory?
    That's that I got told in the c# course.
    Reply With Quote  
     

  8. #7  
    Programmer, Contributor, RM and Veteran




    Join Date
    Mar 2007
    Posts
    5,147
    Thanks given
    2,656
    Thanks received
    3,731
    Rep Power
    5000
    Quote Originally Posted by JonyFX View Post
    Doesn't declaring object name over and over waste memory?
    Ah, I can see where you or your teacher might have got this misconception - but it isn't the case. The declaration itself is done statically at compile time - it isn't done at runtime (at least in the majority of languages, perhaps there are some oddball languages out there where this isn't the case.) Putting the declaration inside a for loop which iterates 10 times doesn't mean the declaration happens 10 times - it still happens once.

    Well, I say "happens" - what's really going on is that space is being reserved in the stack frame for the variable. The stack frame itself is allocated upon entering the method, and freed upon leaving it. This actually means it doesn't matter where you actually declare the variable - ultimately the stack frame is the same size (although maybe some optimising compilers use the scope to determine if a variable can use the same 'slot' as another, rather than running LVA, so perhaps this isn't quite true but even so it still means it's best to use tighter scopes. Also to complicate matters even further, a good compiler will put variables in registers where possible, where it doesn't really make sense to talk about RAM being allocated at all - cos the registers are just fixed bits of memory within the CPU itself.).

    So in the majority of cases you should give your variables as narrow a scope as possible - because it makes absolutely no difference to memory usage and/or speed.

    However, there are a few cases where you might want looser scopes - e.g. you probably want to do:

    Code:
    int x;
    x = someLongRunningCalculation();
    for (...) {
      // use x in each iteration
    }
    rather than:

    Code:
    for (...) {
      int x;
      x = someLongRunningCalculation();
      // use x in each iteration
    }
    (Although even here it might even be possible that a smart compiler could turn the latter into the former. Also here I split the declaration & assignment just to emphasise they are two different things - even though you can do the shorthand of int x = blah, it's really doing int x; x = blah.)

    Here's a simple example showing the bytecode generated is identical regardless of the scope of "b":

    Code:
    ~% cat A.java 
    public class A {
    	public void a() {
    		int a = 0;
    		for (;;) {
    			int b = a++;
    			System.out.println(b-10);
    		}
    	}
    
    	public void b() {
    		int a = 0, b;
    		for (;;) {
    			b = a++;
    			System.out.println(b-10);
    		}
    	}
    }
    ~% javac A.java
    ~% javap -c A
    Compiled from "A.java"
    public class A {
      public A();
        Code:
           0: aload_0       
           1: invokespecial #1                  // Method java/lang/Object."<init>":()V
           4: return        
    
      public void a();
        Code:
           0: iconst_0      
           1: istore_1      
           2: iload_1       
           3: iinc          1, 1
           6: istore_2      
           7: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
          10: iload_2       
          11: bipush        10
          13: isub          
          14: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
          17: goto          2
    
      public void b();
        Code:
           0: iconst_0      
           1: istore_1      
           2: iload_1       
           3: iinc          1, 1
           6: istore_2      
           7: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
          10: iload_2       
          11: bipush        10
          13: isub          
          14: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
          17: goto          2
    }
    ~%
    .
    Reply With Quote  
     

  9. Thankful user:


  10. #8  
    Registered Member

    Join Date
    Jan 2013
    Posts
    485
    Thanks given
    58
    Thanks received
    132
    Rep Power
    248
    Quote Originally Posted by Graham View Post
    Ah, I can see where you or your teacher might have got this misconception - but it isn't the case. The declaration itself is done statically at compile time - it isn't done at runtime (at least in the majority of languages, perhaps there are some oddball languages out there where this isn't the case.) Putting the declaration inside a for loop which iterates 10 times doesn't mean the declaration happens 10 times - it still happens once.

    Well, I say "happens" - what's really going on is that space is being reserved in the stack frame for the variable. The stack frame itself is allocated upon entering the method, and freed upon leaving it. This actually means it doesn't matter where you actually declare the variable - ultimately the stack frame is the same size (although maybe some optimising compilers use the scope to determine if a variable can use the same 'slot' as another, rather than running LVA, so perhaps this isn't quite true but even so it still means it's best to use tighter scopes. Also to complicate matters even further, a good compiler will put variables in registers where possible, where it doesn't really make sense to talk about RAM being allocated at all - cos the registers are just fixed bits of memory within the CPU itself.).

    So in the majority of cases you should give your variables as narrow a scope as possible - because it makes absolutely no difference to memory usage and/or speed.

    However, there are a few cases where you might want looser scopes - e.g. you probably want to do:

    Code:
    int x;
    x = someLongRunningCalculation();
    for (...) {
      // use x in each iteration
    }
    rather than:

    Code:
    for (...) {
      int x;
      x = someLongRunningCalculation();
      // use x in each iteration
    }
    (Although even here it might even be possible that a smart compiler could turn the latter into the former. Also here I split the declaration & assignment just to emphasise they are two different things - even though you can do the shorthand of int x = blah, it's really doing int x; x = blah.)

    Here's a simple example showing the bytecode generated is identical regardless of the scope of "b":

    Code:
    ~% cat A.java 
    public class A {
    	public void a() {
    		int a = 0;
    		for (;;) {
    			int b = a++;
    			System.out.println(b-10);
    		}
    	}
    
    	public void b() {
    		int a = 0, b;
    		for (;;) {
    			b = a++;
    			System.out.println(b-10);
    		}
    	}
    }
    ~% javac A.java
    ~% javap -c A
    Compiled from "A.java"
    public class A {
      public A();
        Code:
           0: aload_0       
           1: invokespecial #1                  // Method java/lang/Object."<init>":()V
           4: return        
    
      public void a();
        Code:
           0: iconst_0      
           1: istore_1      
           2: iload_1       
           3: iinc          1, 1
           6: istore_2      
           7: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
          10: iload_2       
          11: bipush        10
          13: isub          
          14: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
          17: goto          2
    
      public void b();
        Code:
           0: iconst_0      
           1: istore_1      
           2: iload_1       
           3: iinc          1, 1
           6: istore_2      
           7: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
          10: iload_2       
          11: bipush        10
          13: isub          
          14: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
          17: goto          2
    }
    ~%
    Good example, thank you explains everything.
    Reply With Quote  
     

  11. #9  
    Renown Programmer

    Join Date
    Dec 2010
    Posts
    2,876
    Thanks given
    508
    Thanks received
    1,898
    Rep Power
    5000
    Quote Originally Posted by JonyFX View Post
    lol you dont need to return how many numbers have 3 minor pairs, u need to return how many minor pairs a number will have, so it must work with any number u give the program.
    ye i just started on it
    never talk to me or my wife's son ever again
    Reply With Quote  
     

  12. #10  
    Registered Member

    Join Date
    Jan 2013
    Posts
    485
    Thanks given
    58
    Thanks received
    132
    Rep Power
    248
    Quote Originally Posted by Graham View Post
    Ah, I can see where you or your teacher might have got this misconception - but it isn't the case. The declaration itself is done statically at compile time - it isn't done at runtime (at least in the majority of languages, perhaps there are some oddball languages out there where this isn't the case.) Putting the declaration inside a for loop which iterates 10 times doesn't mean the declaration happens 10 times - it still happens once.

    Well, I say "happens" - what's really going on is that space is being reserved in the stack frame for the variable. The stack frame itself is allocated upon entering the method, and freed upon leaving it. This actually means it doesn't matter where you actually declare the variable - ultimately the stack frame is the same size (although maybe some optimising compilers use the scope to determine if a variable can use the same 'slot' as another, rather than running LVA, so perhaps this isn't quite true but even so it still means it's best to use tighter scopes. Also to complicate matters even further, a good compiler will put variables in registers where possible, where it doesn't really make sense to talk about RAM being allocated at all - cos the registers are just fixed bits of memory within the CPU itself.).

    So in the majority of cases you should give your variables as narrow a scope as possible - because it makes absolutely no difference to memory usage and/or speed.

    However, there are a few cases where you might want looser scopes - e.g. you probably want to do:

    Code:
    int x;
    x = someLongRunningCalculation();
    for (...) {
      // use x in each iteration
    }
    rather than:

    Code:
    for (...) {
      int x;
      x = someLongRunningCalculation();
      // use x in each iteration
    }
    (Although even here it might even be possible that a smart compiler could turn the latter into the former. Also here I split the declaration & assignment just to emphasise they are two different things - even though you can do the shorthand of int x = blah, it's really doing int x; x = blah.)

    Here's a simple example showing the bytecode generated is identical regardless of the scope of "b":

    Code:
    ~% cat A.java 
    public class A {
    	public void a() {
    		int a = 0;
    		for (;;) {
    			int b = a++;
    			System.out.println(b-10);
    		}
    	}
    
    	public void b() {
    		int a = 0, b;
    		for (;;) {
    			b = a++;
    			System.out.println(b-10);
    		}
    	}
    }
    ~% javac A.java
    ~% javap -c A
    Compiled from "A.java"
    public class A {
      public A();
        Code:
           0: aload_0       
           1: invokespecial #1                  // Method java/lang/Object."<init>":()V
           4: return        
    
      public void a();
        Code:
           0: iconst_0      
           1: istore_1      
           2: iload_1       
           3: iinc          1, 1
           6: istore_2      
           7: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
          10: iload_2       
          11: bipush        10
          13: isub          
          14: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
          17: goto          2
    
      public void b();
        Code:
           0: iconst_0      
           1: istore_1      
           2: iload_1       
           3: iinc          1, 1
           6: istore_2      
           7: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
          10: iload_2       
          11: bipush        10
          13: isub          
          14: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
          17: goto          2
    }
    ~%
    So in the C# Course, I got curious and ran the following code, and checked it's ram Usage:
    Code:
    	while (true) {
    		String hey = "hello!";
    	}
    Ram usage: 1820kb
    Code:
            String hey;
    	while (true) {
    		hey = "hello!";
    	}
    Ram usage: 1720kb

    Why?

    Nevermind, that's in c#:

    "When running code under release mode in .NET, the two pieces of code are identical due to a compiler optimization technique called loop invariant code motion. There are a huge number of smart optimization techniques in the JIT optimizer that will 'fix' your code. Therefore you should in principle favor readability/simplicity in code over anything else."

    Another quoted answer:

    "Who is saying that the first loop is better for performance? It's generally better for readability to declare variables in as small a scope as possible, but that's not about performance"
    Reply With Quote  
     


Thread Information
Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)


User Tag List

Similar Threads

  1. Replies: 2
    Last Post: 02-21-2011, 05:34 AM
  2. Better way of doing player ranks
    By tj007razor in forum Snippets
    Replies: 10
    Last Post: 06-02-2010, 06:27 AM
  3. A way of doing 'ZonEs'
    By 'Exs Faith in forum Tutorials
    Replies: 19
    Last Post: 05-04-2010, 03:16 PM
  4. Better way of doing this
    By Aeterna in forum Application Development
    Replies: 2
    Last Post: 04-17-2010, 07:17 PM
  5. Is this a good way of doing things?
    By WH:II:DOW in forum Application Development
    Replies: 6
    Last Post: 08-07-2009, 07:22 PM
Posting Permissions
  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •