samchen2009
BAN USERThe oldest friend will be the 1st friend added unless it gets removed. So I think an "ID" and "Valid" column in relationship database will be able to get the answer, right? In Rails, it could look like this:
user.friends.find_by_valid(true) #it will return the 1st valid friends ordered by ID.
The luck string is ordered like this:
str length number examples
1 2^1 4, 5
2 2^2 44,45,54,55
3 2^3 444,445,454,455,544,545,554,555
...
So this question can be tranlated to find the size of luck_string and its offset to the array of string with the same size.
A verified solution in ruby as below:
# get the width and offset of the nth luck string
# e.g, n = 3 ('44'), width = 2, offset = 0 [44, 45, 54, 55]
def str_width_and_offset(n)
sum = 0
(1..n).each do |i|
tmp = sum
sum = sum + 2**i
return i, n - tmp - 1 if sum -n >= 0
end
end
# print m luck string
m = ARGV[0].to_i
luck_str = ""
(1..m).each do |n|
width,offset = str_width_and_offset(n)
# return offset's bit mask, e.g, 3 => "11"
bit_mask_str = offset.to_i.to_s(2)
# padding '0' to width length
bit_mask_str = ('0'*(width - bit_mask_str.size)) << bit_mask_str
# replace '0' with '4' and '1' with '5'
luck_str << bit_mask_str.gsub(/0/,'4').gsub(/1/,'5') + " "
end
puts luck_str
isn't it a database issue?
consider 3 database tables: "users", "items", "categories" and 1 association table, "deals", which contains 2 columns: user_id and item_id.
Through these 4 tables, we can have the followings associations:
* an user has bought many items.
* an item belongs to one category.
so 'Users who bought item X also bought items' can be accomplished by the following steps:
1. get users from deals table where 'item_id' = 'X'
2. for each user, find all the items he bought that belongs to the same category as 'X'.
3. merge all user's item arrays.
int isNonPowerOf2(num)
Power=0;
if (num=0) reutrn 0;
while(num>0)
{
power+=(num&0x1);
num = num>>1;
}
return power-1;
int isNonPowerOf2(num)
{
Power=0;
if (num=0) reutrn 0;
while(num>0)
{
power+=(num&0x1);
num = num>>1;
}
return power-1;
}
solution in Ruby.
To avoid array search, use 2 hashes to
1. detect duplicate set, determined by the a[i]
2. detect duplicate number in a set.
The computation complexity is O(n)
ruby largest_set.rb 5,4,0,3,1,6,2
- samchen2009 February 02, 2014input:[5, 4, 0, 3, 1, 6, 2]
output:
0 loop:4 [5, 6, 2, 0]
1 loop:2 [4, 1]
2 loop:4 [0, 5, 6, 2]
3 loop:1 [3]
4 loop:2 [1, 4]
5 loop:4 [6, 2, 0, 5]
6 loop:4 [2, 0, 5, 6]
n = 7, total loop= 28