• Márton Balassa (unregistered)

    Delphi solution. The function returns an array of integers. The Nth element of the array is 0 if the Nth locker is closed, and X if it's opened, where X was the number of toggles.

    function Lockers(const Count: Integer): TIntegerDynArray;
    var
      I, K: Integer;
    begin
      SetLength(Result, Count);
      for I := 1 to Count do
      begin
        Result[I - 1] := 0;
        K := Count;
        while K > 0 do
        begin
          if I mod K = 0 then
            Inc(Result[I - 1]);
          Dec(K);
        end;
      end;
      for I := 0 to Count - 1 do
        if Result[I] mod 2 = 0 then
          Result[I] := 0;
    end;
    
  • (cs) in reply to Scot
    Scot:
    The locker toggled the most is the locker whose prime factors can create the greatest number of combinations. (locker ... combinations ... get it?).

    At first, I think 64 might be a good choice, but (2,2,2,2,2,2) creates only 6 combinations. If I replace a 2 with a 3, I describe locker 96, and I can now create 11 combinations. Applying my knowledge of cribbage, I see that I can replace three 2s with two 3s to describe locker 72 (2,2,2,3,3), which also creates 11 combinations.

    12, not 11 - you're probably failing to count 1.

    Also, the smallest number with 12 factors is 60 (and since it's the largest highly composite number smaller than 100, the next being 120, 12 factors is indeed the most possible).

  • Daniel (unregistered)

    Sinclair ZX81 / Timex TS100 (via emulator):

    [image]
  • Rhombicosidodecahedron (unregistered)

    public static IEnumerable<int> GetOpenLockers(int num0) {int num1=0,num2=-1;while((num1+=num2+=2)<=num0)yield return num1;}

    // You can use it like this /* foreach(int i in GetOpenLockers(100)) Console.WriteLine(i);

    // Or with descending and using System.Linq;

    Array.ForEach(GetOpenLockers(100).OrderByDescending(i => i).ToArray(), i => Console.WriteLine(i)); */

  • Mamont (unregistered)

    sub getOpenLockers { my @opened; my $last = 1; my $total = shift; my $skip = 2;

    for (my $i = 0; $i < $total; $i++) {
    	push @opened,$i+1;
    	$i = $i+$skip;
    	$skip = $skip+2;
    }
    return @opened;
    

    }

  • (cs) in reply to reallyAmazed
    reallyAmazed:
    simply - squares of prime numbers (or perfect squares)

    I'm amazed with amount of i^2 solutions. Think a bit longer before posting.

    16 is not the square of a prime number, yet it remains open. The i^2 solution is common because it's correct.

  • micksam7 (unregistered)

    Quicky crappy php using square-checking ~

    function locker($in) {
       $out="";
       for($t=1;$t<=$in;$t++)
        $out .= pow($t,.5) == round(pow($t,.5)) ? "{$t}, " : "";
       return substr($out,0,-2);
    }
    

    locker(1000);

    1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961

  • (cs)

    #include <stdio.h>

    int main(int argc, char **argv) { printf("4 9 16 25 36 49 64 81\n"); return 0; }

    Totally optimized.

  • Tim (unregistered)

    This Befunge program works OK on 2 and 10. Output is reversed though. I'm currently testing it on 100.

    v ;//00 - num lockers;
    v ;//10 - current step;
    v ;//20 - current locker;
    v ;//x1 - locker: 0 if closed, 1 if open;
    
    >25*:*00pv ; #00 = 100 ;
    v        <
    >010pv ; #10 = 0 ;
    v    <
    >v ; do { // set x1 to 0;
     >00g1-00pv ; #00 -= 1 ;
     v        <
     >000g1pv ; #[#00]1 = 0 ;
     v      <
     >00g0`v; } while (#00 > 0) ;
     v     <
    ^_v
    v <
    >25*:*00pv ; #00 = 100 ;
    v        <
    >v ; do { // b = 0 .. #00;
     >10g1+10pv ; #10 += 1 ;
     v        <
     >020pv ; #20 = 0 ;
     v    <
     >v ; do { // c = 0, b, 2b .. #00;
      >20g10g+20pv ; #20 += #10 ;
      v          <
      >20g1g!20g1pv ; #[#20]1 = !#[#20]1 ;
      v           <
      >00g20g`v; } while (#00 > #20) ;
      v       <
     ^_v
     v <
     >00g10g`v; } while (#00 > #10) ;
     v       <
    ^_v
    v <
    >v ; do { // print the results ;
     >00g1-00pv ; #00 -= 1 ;
     v        <
     >00g1g.v ; #[#00]1 = 0 ;
     v      <
     >00g0`v; } while (#00 > 0) ;
     v     <
    ^_v
    v <
    >@ ; exit() ;
    
    

    ; ; denote pseudo-code, sort of

  • noway! (unregistered)

    In BASICish (num being number of lockers):

    For i=1 to sqrt(num) print i*i next

  • (cs)

    If I got this as an interview question, I'd go postal. Promise.

  • Børge N (unregistered)

    Some ancient guy has already figured out the solution to the "number of toggles" question.

  • Nathon (unregistered)

    Sorta brute force-ish...

    def testy (number):
        skip = 3
        sum = 3
        step = 1
        while True:
            if number <= sum:
                return step
            skip += 2
            sum += skip
            step += 1
    
  • Tama (unregistered) in reply to Welbog

    Technically, this is incorrect; more than one factor may be repeated. To prove that a number has an odd number of factors if and only if it is a perfect prime:

    Let x be an integer, x = x1^a1 * x2^a2 * ... * xn^an. For a given factor, there are (a1 + 1) ways to choose at what power x1 will be, (a2 + 1) ways to choose at what power x2 will be, and so on. The number of distinct factors for x is thus p = (a1 + 1) * (a2 + 1) * ... * (an + 1). Now, p is odd if and only if all of (a1 + 1), (a2 + 1), ..., (an + 1) are odd, or equivalently, if and only if a1, a2, ..., an are even. That last condition is equivalent to saying that x is a perfect prime.

  • MichaelM (unregistered)
    #!/usr/bin/env ruby
    
    def getOpenLockers(lockers)
     (1..lockers).map {|locker| locker if(Math.sqrt(locker) % 1 == 0)}.compact
    end
    
    puts getOpenLockers(ARGV[0].to_i).join(', ')
    

    YAY!

  • Shoko (unregistered) in reply to Alex Papadimoulis

    public class LockersApp {

    /**

    • @param args */ public static void main(String[] args) { // TODO Auto-generated method stub
    double sqrts = Math.sqrt(Double.parseDouble(args[0]));
    for (double i = 1; i <= sqrts; i++) {
      System.out.print(new Double(Math.pow(i, 2.0)).intValue() + ",");
    }
    

    } }

  • Tama (unregistered) in reply to Welbog
    Welbog:
    The open lockers are perfect squares.

    The reasoning is simple: non-perfect squares have an even number of factors. The jocks toggle a number for every factor it has. Therefore every door should be toggled an even number of times and should therefore end closed (the starting state).

    However, perfect squares have an odd number of unique factors, because one of the factors is repeated. Because of this, perfect squares are toggled for their square root which has no pair to reverse the toggle, so the door ends up open (the opposite state it started in).

    Make sense?

    Technically, this is incorrect; more than one factor may be repeated. To prove that a number has an odd number of factors if and only if it is a perfect prime:

    Let x be an integer, x = x1^a1 * x2^a2 * ... * xn^an. For a given factor, there are (a1 + 1) ways to choose at what power x1 will be, (a2 + 1) ways to choose at what power x2 will be, and so on. The number of distinct factors for x is thus p = (a1 + 1) * (a2 + 1) * ... * (an + 1). Now, p is odd if and only if all of (a1 + 1), (a2 + 1), ..., (an + 1) are odd, or equivalently, if and only if a1, a2, ..., an are even. That last condition is equivalent to saying that x is a perfect prime.

  • BobbyBob (unregistered) in reply to Alex Papadimoulis

    from math import sqrt

    def IsSquare(n): if sqrt(n) == int(sqrt(n)): return True return False

    def GetOpenLockers(n): open_lockers = [] for v in xrange(n): if IsSquare(v + 1): open_lockers.append(v + 1) return open_lockers

  • reallyAmazed (unregistered) in reply to Welbog

    Ok ,sorry, i will state it a bit more clearly:

    for any natural power of a square of a prime number

    (as an example 36 is 6*6 but it stays closed)

  • Ramūns (unregistered)

    More JS:

    function (n) {
        if (n <= 0) {
            return [];
        }
        var ret = [1];
        for (var i = 4, plus = 5; i <= n; i += plus, plus += 2) {
            ret[ret.length] = i;
        }
        return ret;
    }
  • port (unregistered) in reply to reallyAmazed

    I'm really amazed you can't even use the demonstration at the top of the page before you start spouting off.

  • (cs)

    It's all the square numbers. I've done this before, but with 1000 and only an imaginary hallway filled with lockers.

  • (cs)

    A PHP Solution...

    <?php for($i=1;$i*$i<=100;$i++)echo($i*$i)."\n";?>
    
  • BobbyBob (unregistered) in reply to reallyAmazed

    You're still wrong: 4 is not prime, but 16 remains open. Here's an optimized (O(sqrt(N)) solution:

    def GetOpenLockersOsqrtn(n):
      open_lockers = []
      for v in xrange(int(sqrt(n))):
        open_lockers.append((v+1) * (v+1))
      return open_lockers
    
  • shane blake (unregistered)

    some pretty simple sql... more brute force than nerdy, but it works...

    declare @count int set @count = 100 declare @lockers table( id int identity, state bit ) insert into @lockers ( state ) values ( 0 ) while ( (select max(id) from @lockers) < @count ) insert into @lockers ( state ) values ( 0 ) while ( @count > 0 ) begin update @lockers set state = abs(state - 1) where id % @count = 0 set @count = @count - 1 end

    select * from @lockers where state = 1

  • Rob (unregistered) in reply to Alex Papadimoulis

    Untested and messy php

    <?PHP
    	function lockers( $n )
    	{
    		$ret = "1,";
    		while ( $i = 2; $i^2 < $n; $i++ )
    		{
    			$ret .= "$i,";
    		}
    		return $ret;
    	}
    
    	print_r lockers(100);
    ?>
    
  • (cs)
    reallyAmazed:
    Ok ,sorry, i will state it a bit more clearly:

    for any natural power of a square of a prime number

    (as an example 36 is 6*6 but it stays closed)

    1,2,3,4,6,9,12,18,36 9 factors

    Think about it this way: given integer n (> 0) find every pairwise factorisation (a,b) such that a <= b with a == b iff a^2 = n. Call the set of such factorisations S (so S = {(a,b) | ab = n && a <= b}).

    Then the set of factors of n is F = {a | Exists b : (a,b) in S} U {b | Exists a : (a,b) in S}. That's a union of two sets which are the same size, so if the two sets are disjoint then |F| is even. The intersection of the two sets is the set of integers x such that Exists b : (x,b) in S and Exists a : (a,x) in S. By definition of S, xb = n and ax = n, so x = 0 (impossible since we said n > 0) or a=b. But, again by definition of S, x <= b and a <= x, so since b=a we have x <= a <= x, or x = a. Therefore the intersection of the two sets is the set of integers x such that x^2 = n.

    Therefore if n is not a square number the two sets are disjoint and |F| is even. If n is a square number the two sets have sqrt(n) in common, and |F| is odd.

    Edit: ok, I'm missing a step. I should also have shown that if (a,b) in S and (a,c) in S then b=c, and similarly if (a,b) in S and (c,b) in S then a=c. Trivial, since division by a non-zero real is well-defined.

  • MisterCheese (unregistered)

    I see... the ones that remain open have been hit by 1, themselves, and their square root, plus pairs of factors.

    Eg 36 is hit by 1 and 36, 2 and 18, 3 and 12, 4 and 9, and 6.

    The closed ones don't have a positive integer square root so are hit an even number of times.

    Now I guess I need to work out how to extract my head from the toilet bowl...

  • Zack (unregistered)

    Man, you would think the nerds from one year would notice the answer is all primes and tell the younger generation so they could show up the jocks next year and tell Zargus the answer while the jocks tired themselves out slamming lockers.

  • (cs)

    C++, by Brute force.

    #include <cstdio>
    #define DOORCOUNT 100
    
    template <int Lock, bool LockFrozen = true, int Run = DOORCOUNT>
    struct DoorColor {
    	typedef typename DoorColor<Lock, (Lock<=Run)||(Lock%Run!=0), Run-1>::color color;
    	typedef typename DoorColor<Lock, (Lock<=Run)||(Lock%Run!=0), Run-1>::anticolor anticolor;
    	static void print();
    };
    
    template <int Lock, int Run>
    struct DoorColor<Lock, false, Run> {
    	typedef typename DoorColor<Lock, (Lock<=Run)||(Lock%Run!=0), Run-1>::anticolor color;
    	typedef typename DoorColor<Lock, (Lock<=Run)||(Lock%Run!=0), Run-1>::color anticolor;
    	static void print();
    };
    
    template <int Lock>
    struct DoorColor<Lock, true, 0> {
    	typedef char color;
    	typedef struct { char x[256]; } anticolor;
    	static void print();
    };
    
    template <int Lock>
    struct DoorColor<Lock, false, 0> {
    	typedef char color;
    	typedef struct { char x[256]; } anticolor;
    	static void print();
    };
    
    template <int Lock, bool LockFrozen, int Run>
    void DoorColor<Lock,LockFrozen,Run>::print() {
    	std::printf("Door %d is %s.\n", Lock, sizeof(typename DoorColor<Lock,LockFrozen,Run>::color) == 1 ? "closed" : "open");
    }
    
    int main () {
    	// Excel was used to generate this part.
    	DoorColor<1>::print();
    	DoorColor<2>::print();
    	DoorColor<3>::print();
    	DoorColor<4>::print();
    	DoorColor<5>::print();
    	// ... you get the idea ...
    	DoorColor<96>::print();
    	DoorColor<97>::print();
    	DoorColor<98>::print();
    	DoorColor<99>::print();
    	DoorColor<100>::print();
    	return 0;
    }
    

    Addendum (2009-08-05 10:57): Edit: The 3rd struct should be

    template <int Lock>
    struct DoorColor<Lock, true, 0> {
    	typedef struct { char x[256]; } color;
    	typedef char anticolor;
    	static void print();
    };
    

    To enforce the 1st door to be open initially. Yeah, templates are crazy.

  • David Kowis (unregistered)
    #!/usr/bin/ruby
    #
    
    def getOpenLockers(total)
            open = []
            (1..total).each do |num|
                    sqr = num ** 2
                    if(sqr <= total)
                            open << sqr
                    elsif sqr > total
                            break
                    end
            end
            open
    end
    
    
    puts "100: #{getOpenLockers(100)}"
    
    

    There's a ruby solution. Works to find all the open lockers, will have to figure out which ones are opened most often.

  • Anonymous (unregistered)

    I like the concept of coding challenges but so far they have all been the same - provide an algorithm to solve some well known mathematical problem. How about a challenge that consists of a bit more than just solving known equations?

    What's that? We can suggest our own programming challenges? Well OK then!

    <thinking> <thinking> <thinking> <don't worry, I'm getting there...>
  • John (unregistered) in reply to Alex Papadimoulis

    Might be worth al least putting some form of color behind the title.

    White-on-white doesn't work out too well...

  • egilhh (unregistered)

    Ada (Quick and dirty, no validation of input)

    with Command_Line;
    with Ada.Text_IO;
    with Ada.Numerics.Generic_Elementary_Functions;
    procedure Lockers is
       package Float_Numerics is
          new Ada.Numerics.Generic_Elementary_Functions(Float);
       Input : Integer := Integer'Value(Ada.Command_Line.Argument(1));
    begin
       for i in 1..Integer(Float_Numerics.Sqrt(Float(Input)) loop
          Ada.Text_IO.Put(Integer'Image(i**2));
       end loop;
    end Lockers;
    

    -- egilhh

  • (cs) in reply to Nick

    In the same vein at the .NET IEnumerable, using Javascript 1.7 generators, and without brackets since that works too =)

    You'll need a recent firefox with a special flag to the script tag to use generators.

    function l(i) for(j = 1; j < Math.floor(Math.sqrt(i)); j++) yield i*i;

    and getting it is fun too:

    var opens = [i for each (i in l(100))];

    javascript is fun =)

  • Fernando (unregistered)

    Stupid short solution in PHP:

    <?php
        function getOpenLockers($lockers)
        {
            $openLockers = array();
            for ( $i = 0; $i < (int)sqrt($lockers);; $i++ ) $openLockers[] = pow( ($i + 1), 2 );
            return $openLockers;
        }
    ?>
  • (cs) in reply to reallyAmazed
    reallyAmazed:
    Ok ,sorry, i will state it a bit more clearly:

    for any natural power of a square of a prime number

    (as an example 36 is 6*6 but it stays closed)

    I admire your mathematical skills! Now do it for an irrational number of lockers, so that your reasoning powers can be truly matched...

  • BJ Homer (unregistered)

    In Python:

    [code] count = int(sys.argv[1])

    open_lockers = [] for i in range(1, count+1): factors = [j for j in range(1, i+1) if i%j == 0] if len(factors) % 2 == 1: open_lockers.append(i)

    print open_lockers [code]

    You know, just in case they decide to change the rules on square numbers or anything.

  • indrora (unregistered)

    ok. This one is easy once you get the fact its a square system. the algorithm is simple:

    for(int l=1;l*l<=n;l++) {Console.WriteLine(" locker "+(l*l) + " is open" ); }

    C#: Given that n is an integer representing the number of lockers.

    replace with your language of preferences form. Example, the basic syntax on a TI-89 (the only decent calculator) would be:

    Prgm lsol(n)
    For i,1,sqrt(n)
    if i^2 <= n
    Disp i^2
    endif
    EndFor
    EndPrgm
    

    its not brute force, and they can show it scales for however many lockers. :)

    Simple, elegant, and in its own simple way a brute force. Captca: Esse (Hey, Esse you want some algorithms? )

  • (cs)

    The Java way to find the most toggled

    	private static ArrayList<Integer> toggledTheMost(int n) {
    		int arr[] = new int[n];
    		ArrayList<Integer> list = new ArrayList<Integer>();
    		for(int i = 1; i <= n; i++) {
    			for(int j = i ; j <= n ; j = j + i) {
    				arr[j-1]++;
    			}
    		}
    		
    		int toggled = 0;
    		for(int i = 0; i < arr.length ; ++i) {
    			if(arr[toggled] < arr[i])
    				toggled = i;
    			if(arr[i]%2 != 0)
    				list.add(i+1);
    		}
    		System.out.println("The locker that was toggled the most was locker: " + (toggled+1));
    
    		return list;
    	}
    
  • Miquel Fire (unregistered)

    I noticed an interesting pattern with the brute force method. When you get to the halfway mark, you're basically doing the single locker toggle.

  • azredwing (unregistered)

    sub lockers{ push @, $**2 for 1..shift; return @_; }

    Someone mentioned that doing the logic makes the programming "less fun" - they'd rather brute-force the program by actually flipping all 100 doors so many times - to make pretty code or something. The way I see it is if you can optimize a problem away beforehand, and your code ends up being an efficient one-liner, that's WAY better than trying to "beautifully" make a giant solution that somehow account for "edge cases" when it's clear there will never be any.

    Anyone can program; not everyone can think logically, and that's the difference between mediocre and good programmers, or even good and great.

  • Matt Flowers (unregistered)

    A simple solution is to just sequentially add up all of the odd numbers. Each number in the series is an open locker.

    Start with 1. Add 3 to get 4 Add 5 to get 9 Add 7 to get 16 Add 9 to get 25 etc.

  • (cs)

    C, 66chars:

    void f(int l){for(int i=0,j=0;++i<=l;i+=(j+=2))printf("%d,",i);}

    I'm claiming extra credit for not using multiplication, and it being deeply, deeply ugly code.

  • monkey (unregistered)

    Who is Paula and why is she brill(i)ant?

  • (cs) in reply to Matt Flowers
    Matt Flowers:
    A simple solution is to just sequentially add up all of the odd numbers. Each number in the series is an open locker.

    Start with 1. Add 3 to get 4 Add 5 to get 9 Add 7 to get 16 Add 9 to get 25 etc.

    Yep. What you're seeing is the identity:

    (n+1)^2 = n^2 + 2n + 1

    and you're subtracting off the n^2.

    Hence you get: 1 - 21+1 = 3 2 - 22+1 = 5 3 - 2*3+1 = 7

    as you'd expect.

    That's the trick my horrific C experience uses.

  • (cs)

    I'm amazed at the number of brute force methods.

    I'm surprised at the nerds in the story as well. If you cannot solve a problem mathematically, optimize the numeric method. To wit, they could have used a bike to traverse the lockers. Or 100 boxes on a sheet of paper.

  • Reverend Gonzo (unregistered)

    Groovy

    def getOpenLockers(int n) { return (1..Math.sqrt(n)).collect {it**2} }

    println getOpenLockers(100)

  • (cs)

    That guy in Nethack is totally a jock.

    And may have a lot of identical twins.

    #!/usr/bin/perl
    
    $n = $ARGV[0];
    
    foreach $s (1..$n) {
      for ($i = $s-1; $i<$n; $i += $s) {
        $h[$i] = !$h[$i];
      }
      for ($i = 0; $i<$n; $i++) {
        print ($h[$i] ? "'" : "+");
      }
      print "\n";
      for ($i = 1; $i<=$n; $i++) {
        print (($i % $s || $i+1<$s) ? " " : "@");
      }
      print "\n\n";
    }

    This is what it looks like when run:

    curtmack@cardboardbox:~$ ./hall.pl 10
    ''''''''''
    @@@@@@@@@@
    
    '+'+'+'+'+
     @ @ @ @ @
    
    '+++'''+++
      @  @  @ 
    
    '++'''''++
       @   @  
    
    '++'+'''+'
        @    @
    
    '++'++''+'
         @    
    
    '++'+++'+'
          @   
    
    '++'+++++'
           @  
    
    '++'++++''
            @ 
    
    '++'++++'+
             @
  • (cs) in reply to DaveGamble
    DaveGamble:
    C, 66chars:

    void f(int l){for(int i=0,j=0;++i<=l;i+=(j+=2))printf("%d,",i);}

    I'm claiming extra credit for not using multiplication, and it being deeply, deeply ugly code.

    Why not
    void f(int l){for(int i=1,j=1;i<=l;i+=(j+=2))printf("%d,",i);}

Leave a comment on “Nerds, Jocks, and Lockers”

Log In or post as a guest

Replying to comment #:

« Return to Article