From: Chris Shea Date: 2007-12-18T04:25:02+09:00 Subject: Re: dividing by two and rounding up On Dec 17, 11:42 am, Tom Norian wrote: > Hey all...I am hoping for a tip > > I have a table I want to lay out dynamcially in rails where if a game > has 6 periods the first 3 periods will be in the first column and the > 4-6 in the second column. If someone picks an odd number of periods , > say 5, I want the 1-3 in the first column and 4 and 5 in the second. > > I have figured out how to iterate through IF I could get 5/2 to yield me > 3. > > How do I divide a number (integer) by 2 and get a result that is like: > > 5/2 I want 3 > 6/2 I want 3 > 7/2 I want 4 > > I'm thinking perhaps I could test for oddness then add one to the result > if odd, but that seems kinda a lot of lines for something so simple. > > half_periods = 0 > if num_periods%2 == 1 > half_periods = num_periods/2 +1 > else > half_periods = num_periods/2 > end > > Is there a better way? > -- > Posted viahttp://www.ruby-forum.com/. Here's a few ways: require "test/unit" PERIODS = [1,2,3,4,5,6,7,8,9,10] PER_HALF = [1,1,2,2,3,3,4,4,5,5] class TestPeriods < Test::Unit::TestCase def test_div_two_plus_mod_two assert_equal(PER_HALF, PERIODS.map {|period| period / 2 + period % 2}) end def test_plus_mod_two_div_two assert_equal(PER_HALF, PERIODS.map {|period| (period + period % 2) / 2}) end def test_plus_one_div_two assert_equal(PER_HALF, PERIODS.map {|period| (period + 1) / 2}) end def test_div_2_ceil assert_equal(PER_HALF, PERIODS.map {|period| (period / 2.0).ceil}) end def test_plus_1_div_two_floor assert_equal(PER_HALF, PERIODS.map {|period| ((period + 1.0) / 2).floor}) end def test_div_2_round assert_equal(PER_HALF, PERIODS.map {|period| (period / 2.0).round}) end end