def manaddnode(G, n, singles): counter = 0 results = open( os.getcwd() + "/results/testResults" + str(counter) + ".txt", 'w') nodecount = number_of_nodes(G) + 1 #print(str(nodecount)) while (n > 0): G.add_node(str(nodecount)) incNodes = rd(0, nodecount - 1) outNodes = rd(0, nodecount - 1) for i in range(1, incNodes): rand = rd(1, nodecount - 1) G.add_edge(str(rand), str(nodecount)) for j in range(1, outNodes): rand2 = rd(1, nodecount - 1) G.add_edge(str(nodecount), str(rand2)) if (singles): info = doCalc(G, counter, results) counter = info[0] results = info[1] G = Ginit nodecount = nodecount + 1 # print(n) n = n - 1 info = doCalc(G, counter, results) counter = info[0] results = info[1] results.close()
def bot_response(usr_team, bot_team): while True: x,y = rd(0,2), rd(0,2) if BOARD[x][y] != usr_team: if BOARD[x][y] != bot_team: BOARD[x][y] = bot_team break
def manaddedge(G, n, singles): counter = 0 results = open( os.getcwd() + "/results/testResults" + str(counter) + ".txt", 'w') nodecount = number_of_nodes(G) #print(str(nodecount)) while (n > 0): rand = rd(1, nodecount) rand2 = rd(1, nodecount - 1) found = False while not found: found = True for x in G.edges(str(rand)): if (x == "(" + str(rand) + ", " + str(rand2) + ")"): rand2 = rd(1, nodecount - 1) found = False break #print (x) #print (str(rand)+str(rand2)) G.add_edge(str(rand), str(rand2)) if (singles): info = doCalc(G, counter, results) counter = info[0] results = info[1] G = Ginit # print(n) n = n - 1 info = doCalc(G, counter, results) counter = info[0] results = info[1] results.close()
def choose_attacks(self): atk1 = rd() self.atk1 = self.hexxa1.attacks[where( self.hexxa1.attacks["probabilities"] > atk1)[0][0] + 1] atk2 = rd() self.atk2 = self.hexxa2.attacks[where( self.hexxa2.attacks["probabilities"] > atk2)[0][0] + 1]
def click(x, y): global field_b, f, disabled if f: field_b, f = b, 0 while field_b: x1, y1 = rd(0, w - 1), rd(0, h - 1) if (x1, y1) != (x - 1, y - 1) and (x1, y1) != (x - 1, y) and (x1, y1) != (x - 1, y + 1) and \ (x1, y1) != (x, y - 1) and (x1, y1) != (x, y) and (x1, y1) != (x, y + 1) and \ (x1, y1) != (x + 1, y - 1) and (x1, y1) != (x + 1, y) and (x1, y1) != (x + 1, y + 1): set_bomb(x1, y1) if field[x][y] != 'b': disabled += 1 Label(window, text=field[x][y] if field[x][y] else '').place(x=x * 20, y=y * 20, width=20, height=20) if not field[x][y]: zero_click_check(x, y) else: Label(window, text='GAME OVER').place(x=0, y=-10, width=w * 20, height=h * 20 + 10) Button(text='Restart', bg='light gray', command=lambda: setting()).place(x=w * 10 - 40, y=h * 10, width=80, height=20) win_check()
def move(): iteration = 0 while True: randNum = rd(0, 140) if randNum <= 20: randKey = 'w' elif randNum <= 40: randKey = 's' elif randNum <= 60: randKey = 'd' else: randKey = 'a' pyautogui.keyDown(randKey) time.sleep(rd(0, 20) / 10) pyautogui.keyUp(randKey) iteration += 1 if iteration % 30 == 0: pyautogui.keyDown('a') time.sleep(10) pyautogui.keyUp('a')
def profaseI(cario): print(green + '[!] INCÍO DA PRÓFASE I') for duplosBivalentes, nC in zip(cario, ncromo): while True: if rd(0, 100) <= 35: quiasma = True print( yellow + '[*] HOUVE TROCA DE SEGMENTOS ENTRE CROMATÍDEOS HOMÓLOGOS NÚMERO {0}' .format(nC)) else: quiasma = False break while quiasma: pontoDeTroca = rd(0, 1) #ponto 0 ou ponto 1 indexGene0 = rd(0, len(duplosBivalentes[pontoDeTroca][0]) - 1) indexGene1 = rd(0, len(duplosBivalentes[pontoDeTroca][1]) - 1) print( yellow + '[*] GENE DA POSIÇÃO {0} NO CROMOSSOMA 1 VAI PARA A POSIÇÃO {1} NO CROMOSSOMA 2 (NO PONTO DE QUIASMA {2})' .format(indexGene0, indexGene1, pontoDeTroca)) duplosBivalentes[pontoDeTroca][0][ indexGene0], duplosBivalentes[pontoDeTroca][1][ indexGene1] = duplosBivalentes[pontoDeTroca][1][ indexGene1], duplosBivalentes[pontoDeTroca][0][ indexGene0] break return cario
def DataMake(c): MAXL = 100000 f = open('data' + str(c) + '.in', 'w') n = 5 #1000 node = range(1, n + 1) sl(node) sl(node) m = rd(1, min(n * n, 5000)) w2f(f, n, 0) w2f(f, m, 1) for i in range(0, m): p1 = rd(1, n - 1) p2 = rd(p1 + 1, n) x = node[p1 - 1] y = node[p2 - 1] l = rd(1, MAXL) w = gn() w2f(f, x, 0) w2f(f, y, 0) w2f(f, l, 0) w2f(f, w, 1) k = gn() w2f(f, k, 1) for i in range(0, k): w2f(f, gn(), 1) print(n, ' node', m, ' edges', k, 'Queries') f.close()
def initializeGuesses(self): ''' Instantiate initial x0 values for scipy.minimize and scipy.basinhopping to iterate ''' x = [] for i in range(self.num_zones): wells_in_zone = self.well_counts[i] initial_spacing = self.right_bound / wells_in_zone well_iter = 0 if i % 2 == 0: while self.lease_offset + well_iter * initial_spacing <= self.right_bound: x.append(self.lease_offset + well_iter * initial_spacing + 2 * (rd() - 0.5)) well_iter += 1 else: while (self.right_bound - self.lease_offset - (wells_in_zone - 1) * initial_spacing) + well_iter * initial_spacing + 2 * ( rd() - 0.5) <= self.right_bound: x.append((self.right_bound - self.lease_offset - (wells_in_zone - 1) * initial_spacing) + well_iter * initial_spacing + 2 * (rd() - 0.5)) well_iter += 1 if len(x) != sum(self.well_counts): return -1 else: return x
def GenerateKeyPair(self): self.e = rd(2, self.__fi - 1) while ExEuclid(self.e, self.__fi)[0] != 1: self.e = rd(2, self.__fi - 1) self.__d = ExEuclid(self.e, self.__fi)[1] % self.__fi print(str(hex(self.e)[2:]), " ASDASDA ", str(hex(self.n)[2:]))
def player_func_random1(map_info: GameMap, player_id: int): ACTIONS = [] tmp_left = [i.power[player_id] for i in map_info.nodes] # print("I am TESTING!!!",map_info)#测试 def isValid(action): a, b, c = action if map_info.nodes[a].belong != player_id: return False if b not in map_info.nodes[a].get_next(): return False if tmp_left[a] <= c + 0.01: return False tmp_left[a] -= c return True for i in range(1000): tmp_action = (rd(1, len(map_info.nodes) - 1), rd(1, len(map_info.nodes) - 1), rd(1, 1000) / 10) if isValid(tmp_action): ACTIONS.append(tmp_action) # 随机出兵 # print(ACTIONS) return ACTIONS
def randomZScore(): while True: randX = rd(-30000, 30000) / 10000 randY = rd(0, 50000) / 100000 if randY <= normalDistribution(randX): return randX
def gen_word(): size = rd(4, 8) word = "" for i in range(0, size): l = chr(rd(ord('a'), ord('z'))) word = word + l return word
def get_data(self) -> None: from random import randint as rd for _ in range(self.number_of_examples): closer_x = closer_y = 0 coor = [1, 1] while closer_x + closer_y < ( self.graph_size[0] / self.middle_distance + self.graph_size[1] / self.middle_distance) and ( closer_x + closer_y > -(self.graph_size[0] / self.middle_distance + self.graph_size[1] / self.middle_distance)): coor = [rd(1, self.graph_size[0]), rd(1, self.graph_size[1])] closer_x = int(coor[0] - self.coor_base_one[0]) - (int( (1 - (coor[0] / self.coor_base_two[0])) * self.graph_size[0])) closer_y = int(coor[1] - self.coor_base_one[1]) - (int( (1 - (coor[1] / self.coor_base_two[1])) * self.graph_size[1])) belong = 1 if closer_x + closer_y > 0 else 0 if rd(1, 100) <= self.percentage_of_random: belong = rd(0, 1) self.all_data = self.all_data.append( { self.columns[0]: coor[0], self.columns[1]: coor[1], self.columns[2]: belong }, ignore_index=True)
def place(self): coins = [] cnt = 0 a = 0 while a < 1490: b = rd(3, 41) a = a + rd(7, 30) if a >= 1290 and a not in range(346, 354) and a not in range( 645, 654) and a not in range(698, 705) and a not in range( 440, 450): break if rd(1, 2) == 1: obj = coin1() coins.append(obj) cnt = cnt + 1 for i in range(4): self.__board.ret_grid()[b + i][a] = coins[cnt - 1].retcoin()[i][0] else: obj = coin2() coins.append(obj) cnt = cnt + 1 for i in range(2): for j in range(6): self.__board.ret_grid()[b + i][a + j] = coins[ cnt - 1].retcoin()[i][j]
def __init__(self, *args, color_range=(256, 256, 256)): if args: self.r, self.g, self.b = args else: if isinstance(color_range, Color): color_range = color_range.tuple() self.r, self.g, self.b = rd(0, color_range[0]), rd( 0, color_range[1]), rd(0, color_range[2])
def stataddedge(G, stat, singles, n): counter = 0 results = open( os.getcwd() + "/results/testResults" + str(counter) + ".txt", 'w') minv = min(stat) maxv = max(stat) minlist = [] maxlist = [] min1list = [] min2list = [] min3list = [] betweenlist = [] for num in range(0, len(stat)): if (stat[num] == minv): minlist.append(num) elif stat[num] == maxv: maxlist.append(num) elif stat[num] == minv + 1: min1list.append(num) elif stat[num] == minv + 2: min2list.append(num) elif stat[num] == minv + 3: min3list.append(num) elif stat[num] > minv + 2 & stat[num] < maxv: betweenlist.append(num) while (n >= 0): if len(minlist) - 1 == 1: minlist = min1list min1list = min2list min2list = min3list min3list = betweenlist if len(minlist) - 1 > 1: rand = rd(1, len(minlist) - 1) else: rand = 1 dele = minlist[rand] minlist.pop(rand) min1list.append(rand) rand2 = rd(1, number_of_nodes(G)) found = False while not found: found = True for i in G.edges(str(dele)): if (i == "(" + str(dele) + ", " + str(rand2) + ")"): rand2 = rd(1, number_of_nodes(G)) found = False G.add_edge(str(dele), str(rand2)) if (singles): info = doCalc(G, counter, results) counter = info[0] results = info[1] G = Ginit n = n - 1 info = doCalc(G, counter, results) counter = info[0] results = info[1] results.close()
def list_of_rgb_colors(nums): ans = [] for i in range(0, nums): v1 = rd(0, 255) v2 = rd(0, 255) v3 = rd(0, 255) tmp = 'rgb(' + str(v1) + ', ' + str(v2) + ', ' + str(v3) + ')' ans.append(tmp) return ans
def mutate(population): for i in range(b2m): p1 = round(rd() * L) - 1 p2 = round(rd() * N) - 1 if population[p2, p1] == 0: population[p2, p1] = 1 else: population[p2, p1] = 0 return population
def run_1(): while True: tu.forward(rd(40, 100)) turn = rd(0, 1) if turn: tu.left(rd(0, 360)) else: tu.right(rd(0, 360)) tu.dot()
def statdeledge(G, stat, singles, n): counter = 0 results = open( os.getcwd() + "/results/testResults" + str(counter) + ".txt", 'w') minv = min(stat) maxv = max(stat) minlist = [] maxlist = [] min1list = [] min2list = [] min3list = [] betweenlist = [] for num in range(0, len(stat)): if (stat[num] == minv): minlist.append(num) elif stat[num] == maxv: maxlist.append(num) elif stat[num] == minv + 1: min1list.append(num) elif stat[num] == minv + 2: min2list.append(num) elif stat[num] == minv + 3: min3list.append(num) elif stat[num] > minv + 2 & stat[num] < maxv: betweenlist.append(num) while (n >= 0): if len(minlist) - 1 == 1: minlist = min1list min1list = min2list min2list = min3list min3list = betweenlist if len(minlist) - 1 > 1: rand = rd(1, len(minlist) - 1) else: rand = 1 dele = minlist[rand] minlist.pop(rand) min1list.append(rand) rand2 = rd(0, len(G.edges(str(dele)))) inc = 0 for i in G.edges(str(dele)): if inc == rand2: G.remove_edge(i) inc = inc + 1 if (singles): info = doCalc(G, counter, results) counter = info[0] results = info[1] G = Ginit n = n - 1 info = doCalc(G, counter, results) counter = info[0] results = info[1] results.close()
def captcha_generator(): global captcha_text captcha_text = '' for each_letter in range(6): if rd(0, 1) == 0: captcha_text += alphabet[rd(0, len(alphabet) - 1)] else: captcha_text += alphabet[rd(0, len(alphabet) - 1)].upper() # print(captcha_text) image.write(captcha_text, 'captcha.png')
def make_enemy(): enemy_image = pygame.image.load('images/enemy.png') enemy = { 'image': enemy_image, 'x': rd(0, 730), 'y': rd(5, 100), 'dx': random.random() + 3, 'dy': 30 } return enemy
def maneuver_event(msg, robot): trials = 0 if msg.event == "start_teleoperation": robot_state = models_service(robot, '') while trials < 4: # Try to move if 'UAV' in robot: dest = ExecuteDroneApproachGoal() dest.goal.position.x = robot_state.pose.position.x + 2 * DIST * rd( ) - DIST # Desired x position dest.goal.position.y = robot_state.pose.position.y + 2 * DIST * rd( ) - DIST # Desired y position dest.goal.position.z = robot_state.pose.position.z + DIST * rd( ) # Desired z position dest.goal.orientation.w = 1.0 trajectory_clients[robot].send_goal(dest) trajectory_clients[robot].wait_for_result( ) # Wait for the result state = trajectory_clients[robot].get_state( ) # Get the state of the action if state == GoalStatus.SUCCEEDED: trials = 10 msg2pub.event = "end_teleoperation" else: trials += 1 if trials >= 4: msg2pub.event = "teleoperation_error" elif 'pioneer3at' in robot: pub_msg = Twist() pub_msg.linear.x = 0.3 * rd() - 0.2 pub_msg.angular.z = 1 * rd() - 0.5 trajectory_clients[robot].publish(pub_msg) sleep(10) pub_msg.linear.x = 0.0 pub_msg.angular.z = 0.0 trajectory_clients[robot].publish(pub_msg) robot_pose = models_service(robot, '') if ((robot_pose.pose.position.x - robot_state.pose.position.x) **2 + (robot_pose.pose.position.y - robot_state.pose.position.y)**2)**(1 / 2) > 0.5: trials = 10 msg2pub.event = "end_teleoperation" else: trials += 1 if trials >= 4: msg2pub.event = "teleoperation_error" end_publishers[robot].publish(msg2pub)
def game_restart(player, enemies): global go_flag go_flag = False player['x'] = 370 player['y'] = 480 for enemy in enemies: enemy['y'] = rd(5, 150) enemy['dx'] = random.random() + 3 enemy['x'] = rd(0, 730)
def getNearestNodeS(x: float, y: float) -> List[Node]: min: Node = Graph.nodeS[rd(0, len(Graph.nodeS) - 1)] #by default min2: Node = Graph.nodeS[rd(0, len(Graph.nodeS) - 1)] #by default for node in Graph.nodeS: if distance(node.x, node.y, x, y) < distance(min.x, min.y, x, y): min = node for node in Graph.nodeS: if distance(node.x, node.y, x, y) < distance(min2.x, min2.y, x, y) and node is not min: min2 = node return [min, min2]
def generation(thing, w1, w2, b): learning_rate = 1000 #bigger number = slower learning rate result = [] for i in range(1000): new_w1 = w1 + rd(-10, 10) / learning_rate new_w2 = w2 + rd(-10, 10) / learning_rate new_b = b + rd(-10, 10) / learning_rate individual = Individual(new_w1, new_w2, new_b) individual.evaluate(thing) result.append(individual) return findFittest(thing, result), result
def get_init_state(self): # x, y rand_values_x = [0.0] * 2 rand_values_y = [0.0] * 2 rand_values_x[0] = -(rd() * (0.45 - 0.21) + 0.21) rand_values_x[1] = -(rd() * (0.49 - abs(rand_values_x[0])) + abs(rand_values_x[0])) rand_values_y[0] = (rd() * (0.25 - 0.0) + 0.0) rand_values_y[1] = (rd() * (0.3 - rand_values_y[0]) + rand_values_y[0]) ret = np.array([ 0.0, -0.175, rand_values_x[0], rand_values_x[1], -0.5, 0.0, 0.0, rand_values_y[0], rand_values_y[1], 0.12, ]) """ ret = np.array([ 0.0, -0.175, -0.3, -0.35, -0.5, 0.0, 0.0, 0.12, 0.12, 0.12 ]) """ # a, h, b, c section = np.array([0.0] * self.N * 4) ret = np.concatenate((ret, section)) for i in range(self.N): ret[self.section_a_start + i] = self.lowerLimitSection / 1000. ret[self.section_h_start + i] = ((self.upperLimitSection - self.lowerLimitSection * 2) * rd() + self.lowerLimitSection) * 2 / 1000. ret[self.section_b_start + i] = ((self.upperLimitSection - self.lowerLimitSection * 2) * rd() + self.lowerLimitSection) * 2 / 1000. ret[self.section_c_start + i] = self.lowerLimitSection / 1000. return ret
def generate(): from random import random as rd k = int(rd() * pow(10, 5)) + 1 m = int(rd() * pow(10, 7)) + 1 n = int(rd() * pow(10, 5)) + 1 pows = [rd() * pow(10, 6) for _ in xrange(n)] print k, m, n try: assert solve(n, k, m, pows) == hack00(n, k, m, pows) except: print solve(n, k, m, pows) print hack00(n, k, m, pows) print k, m, n, pows exit("bug")
def generatePos(self, lvl): while (True): randX = rd(0, len(lvl[0])); randY = rd(0, len(lvl)); if (inBound(lvl, randY, randX) and lvl[randY][randX] == '0'): self.x = randX; self.y = randY; break; #Opfermann #nononononononoononononnonon, are you making it so its a random location? # cant you just make a list of all the cordinates, and then tell it to put it at a ranom location? ah ok # but we might be making more levels
def create_vc(vc): '''vc id a dict refered to huawei_driver.py {'document':{'cmd':1,'site_1_id':xx, 'site_2_id':xxx,'bandwidth_f':xxx, 'bandwidth_b':xxx}} ''' #site must in table siteinfo site_1_id = vc['document']['site_1_id'] site_2_id = vc['document']['site_2_id'] pwid_r = rd(50,100) #for test #first deal with create vlink vlinkid_f = create_vlink(a2b(site_1_id),a2b(site_2_id),vc['document']['bandwidth_f']) vlinkid_b = create_vlink(a2b(site_2_id),a2b(site_1_id),vc['document']['bandwidth_b']) #then deal with vcinfo vcid = uuid4().get_hex() #this is ascii try: vc = hw.VcInformation(vcid = a2b(vcid),site1id=a2b(site_1_id),site2id=a2b(site_2_id),vlinkid=vlinkid_f,\ back_vlinkid=vlinkid_b,pwid=pwid_r) session = Session() session.add(vc) #session.flush() session.commit() except: pass return {"document":{"result":0,"vcid":vcid}}
def __init__(self): self.pairs = ['spade', 'clubs', 'diamonds', 'hearts'] self.cardnums = ['two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'jack', 'queen', 'king', 'ace'] self.deck = [(pair, card) for pair in self.pairs for card in self.cardnums] self.rdcard = self.deck[rd(0,len(self.deck)-1)]
def create_vlink(s1id,s2id,band): current_max_vlink_id = get_max_id('vlink') tunnelid_r = rd(10,20) vlink = hw.VlinkInformation(vlinkid = current_max_vlink_id+1,site1id=s1id,site2id=s2id,\ tunnelid = tunnelid_r,bandwidth=band) session = Session() session.add(vlink) session.commit() return current_max_vlink_id+1
def setupgamelist(): """Creates a list containing 14 lists, each containing 60 characters that are randomly either a ` or ~ character. Returns list to use for game """ waves = [] totalwavelist = [] wavelist = ['`','~'] count = 0 while count <15: waves = [] for i in range(0,60): wavenum = rd(0,1) waves.append(wavelist[wavenum]) if count<10: waves.insert(0, ' '+str(count)+' ') else: waves.insert(0, str(count)+' ') waves.insert(len(waves)+1, ' '+str(count)) totalwavelist.insert(count, waves) count+=1 return totalwavelist
def generateSequence(self, length, iniState): data = "" s = iniState visitedStates = [s.name] for i in range(0,length): dist = [0] d = [float(x[2]) for x in s.outedges] dist.extend(d) r = rd() c = 0 for j in range(0,len(dist)-1): c += dist[j] if (c < r <= c + dist[j+1]): a = s.outedges[j] data += a[0] w = s.nextStateFromEdge(a[0]) s = self.stateNamed(w) if s.name not in visitedStates: visitedStates.append(s.name) break print len(visitedStates) return data
def randomFil(n, LList): for i in xrange(n): #generate random numbers [1-50] num = rd(1, 50) LList.insertFirst(num)
def rnd_color2(): return (rd(32, 127), rd(32, 127), rd(32, 127))
from random import randint as rd n=10 for i in range(1, n + 1): f = open(str(i) + '.in', 'w'); a = rd(1, 100) b = rd(1, 100) f.write(str(a) + ' ' + str(b) + '\n') f.close() f2 = open(str(i) + '.out', 'w'); f2.write(str(a + b) + '\n') f2.close()
from random import randint as rd N = 10 print(N) for i in range(N): print(rd(1, 100000), end=' ') print('')
def rnd_color(): return (rd(64, 255), rd(64, 255), rd(64, 255))
# -*- coding: utf-8 -*- ''' 生成字母验证码图片 ''' from PIL import Image, ImageFont, ImageFilter, ImageDraw from random import randint as rd w, h = 240, 60 def rnd_color(): return (rd(64, 255), rd(64, 255), rd(64, 255)) def rnd_color2(): return (rd(32, 127), rd(32, 127), rd(32, 127)) image = Image.new('RGB', (w, h), (255, 255, 255)) font = ImageFont.truetype('msyh.ttc', 35) draw = ImageDraw.Draw(image) for x in range(w): for y in range(h): draw.point((x, y), fill=rnd_color()) for i in range(4): draw.text((i*60 + 15, 10), chr(rd(65, 90)), font=font, fill=rnd_color2()) image = image.filter(ImageFilter.BLUR) image.save('code.jpg', 'jpeg')
# print '\t', fa s += b fa -= fb while puede(fc): s += c fa -= fc elif tc <= tb: while puede(fc): s += c fa -= fc while puede(fb): s += b fa -= fb while total(fa) > 0: r = rd(0, 10) for k in fa.keys(): if fa[k] > 0: if r >= 5: if s + k * fa[k] != a: s += k * fa[k] else: s = k * fa[k] + s else: if k * fa[k] + s != a: s = k * fa[k] + s else: s += k * fa[k] fa[k] = 0 if Counter(s) == Counter(a):
def rectangle(point_num, recwidth, recheight, list_points = None): from random import randrange as rd import matplotlib.pyplot as plt import numpy as np x=[] y=[] for i in xrange(point_num): x.append(rd(0, 100, 0.01)) y.append(rd(0, 100, 0.01)) if list_points != None: x=[] y=[] for point in list_points: x.append(point[0]) y.append(point[1]) minx = min(x) # Get the minimum x value in the entire dataset maxx = max(x) # Get the maximum x value in the entire dataset miny = min(y) # Get the minimum y value in the entire dataset maxy = max(y) # Get the maximum y value in the entire dataset fig = plt.figure() plt.plot(x,y,'+') plt.plot(min(x), min(y), 'o', color='black') # Plot the SW cornor of the smallest rectangle plt.plot(max(x), min(y), 'o', color='black') # SE cornor plt.plot(max(x), max(y), 'o', color='black') # NE cornor plt.plot(min(x), max(y), 'o', color='black') # NW cornor # Draw the smallest rectangle for the entire dataset plt.plot([minx, maxx], [miny, miny], '--', lw=.5, color='black') # Draw a line between the SW and SE cornors plt.plot([maxx, maxx], [miny, maxy], '--', lw=.5, color='black') # Draw a line between the SE and NE cornors plt.plot([maxx, minx], [maxy, maxy], '--', lw=.5, color='black') # Draw a line between the NE and NW cornors plt.plot([minx, minx], [maxy, miny], '--', lw=.5, color='black') # Draw a line between the NW and SW cornors # Create a list of x-nods on the x-axis and a list of y-nods on the y-axis based on the width and height of the defined rectangle xnods = np.arange(minx, maxx+recwidth, recwidth) ynods = np.arange(miny, maxy+recheight, recheight) # Calculate the x- and y-coordinates of the middle point in each rectangle xmidpoints = [] ymidpoints = [] for i in xrange(len(xnods)-1): xmidpoints.append((xnods[i]+xnods[i+1])/2.) for i in xrange(len(ynods)-1): ymidpoints.append((ynods[i]+ynods[i+1])/2.) # Use a list "rectangles" to store the number of points in each rectangle rectangles = [] # Calculate the x- and y-coordinates of four cornors for each rectangle and then draw the grid for i in xrange(len(xmidpoints)): for j in xrange(len(ymidpoints)): # SW cornor SW_x = xmidpoints[i] - recwidth/2. SW_y = ymidpoints[j] - recheight/2. # SE cornor SE_x = xmidpoints[i] + recwidth/2. SE_y = ymidpoints[j] - recheight/2. # NE cornor NE_x = xmidpoints[i] + recwidth/2. NE_y = ymidpoints[j] + recheight/2. # NW cornor NW_x = xmidpoints[i] - recwidth/2. NW_y = ymidpoints[j] + recheight/2. # Draw the rectangle plt.plot([SW_x, SE_x], [SW_y, SE_y], lw=2, color='black') plt.plot([SE_x, NE_x], [SE_y, NE_y], lw=2, color='black') plt.plot([NE_x, NW_x], [NE_y, NW_y], lw=2, color='black') plt.plot([NW_x, SW_x], [NW_y, SW_y], lw=2, color='black') # Update the "rectangles" list # Use "q" to store the number of points q = 0 for p in xrange(len(x)): if x[p]>= SW_x and x[p]<=SE_x and y[p]>= SW_y and y[p]<=NE_y: q+=1 x[p] = [] y[p] = [] rectangles.append(q) # Print out the "rectangles" list print 'There are', len(rectangles) ,'quadrats in total.' for i in xrange(len(rectangles)): print 'Quadrat', i+1, 'has', rectangles[i], 'points.' ax = fig.gca() ax.set_xticks(np.arange(minx-recwidth, maxx+recwidth*2, recwidth)) ax.set_yticks(np.arange(miny-recheight, maxy+recheight*2, recheight)) plt.show() # This function has two returns. "rec_num" is the total number of rectangles. # "rectangles" is the list that stores the number of points in each rectangle. return len(rectangles), rectangles
def hexagon(point_num, side): from random import randrange as rd import matplotlib.pyplot as plt import numpy as np from math import sqrt x=[] y=[] for i in xrange(point_num): x.append(rd(0,101,1)) y.append(rd(0,101,1)) minx = min(x) # Get the minimum x value in the entire dataset maxx = max(x) # Get the maximum x value in the entire dataset miny = min(y) # Get the minimum y value in the entire dataset maxy = max(y) # Get the maximum y value in the entire dataset fig = plt.figure() plt.plot(x, y, '+') plt.plot(minx, miny, 'o', color='black') # Plot the SW cornor of the smallest rectangle plt.plot(maxx, miny, 'o', color='black') # SE cornor plt.plot(maxx, maxy, 'o', color='black') # NE cornor plt.plot(minx, maxy, 'o', color='black') # NW cornor # Draw the smallest rectangle for all the points plt.plot([minx, maxx], [miny, miny], '--', lw=.5, color='black') # Draw a line between the SW and SE cornors plt.plot([maxx, maxx], [miny, maxy], '--', lw=.5, color='black') # Draw a line between the SE and NE cornors plt.plot([maxx, minx], [maxy, maxy], '--', lw=.5, color='black') # Draw a line between the NE and NW cornors plt.plot([minx, minx], [maxy, miny], '--', lw=.5, color='black') # Draw a line between the NW and SW cornors # This below determines the number of hexagon columns, or the easternmost point where the hexagons can reach column_num = 1 # Starting from the first column and count to the right side x_tip = minx + 0.5*side # x_tip variable controls the farthest point that the current column can reach while x_tip < maxx: # x_tip is compared with the maxmium x value to see if it needs to continue x_tip += 1.5*side column_num += 1 length_x = column_num # Use length_x to represent the number of columns # This below determines the number of hexagon rows for odd columns, or the northernmost point where the odd column hexagons can reach row_num = 1 up_lmt = miny + side/2.*sqrt(3) while up_lmt < maxy: up_lmt += side*1.*sqrt(3) row_num += 1 length_y_odd = row_num # This below determines the number of hexagon rows for even columns, or the northernmost point where the even column hexagons can reach row_num = 1 up_lmt = miny + side*1.*sqrt(3) while up_lmt < maxy: up_lmt += side*1.*sqrt(3) row_num += 1 length_y_even = row_num # Define the starting point (minx, miny) where to build the first hexagon start_x = minx*1. start_y = miny*1. mid_x = start_x mid_y = start_y midpoints = [] # Used to store all the coordinates of center points for all the hexagons # i controls columns(x's); j controls rows (y's) # Starting from the SW cornor and then build up to the north for i in xrange(length_x): if i%2 == 0: for j in xrange(length_y_odd): midpoints.append([mid_x, mid_y]) mid_y += side*1.*sqrt(3) mid_y = start_y + side/2.*sqrt(3) if i%2 == 1: for j in xrange(length_y_even): midpoints.append([mid_x, mid_y]) mid_y += side*1.*sqrt(3) mid_y = start_y mid_x += 1.5*side # Use "hexagons" list to store the number of points in each hexagon hexagons = [] for midpoint in midpoints: # Calculate the coordinates of six hexagon vertex NE_x = midpoint[0]*1. + side/2. NE_y = midpoint[1]*1. + side/2.*sqrt(3) E_x = midpoint[0]*1. + side*1. E_y = midpoint[1]*1. SE_x = midpoint[0]*1. + side/2. SE_y = midpoint[1]*1. - side/2.*sqrt(3) SW_x = midpoint[0]*1. - side/2. SW_y = midpoint[1]*1. - side/2.*sqrt(3) W_x = midpoint[0]*1. - side*1. W_y = midpoint[1]*1. NW_x = midpoint[0]*1. - side/2. NW_y = midpoint[1]*1. + side/2.*sqrt(3) # Draw the hexagon plt.plot([NE_x, E_x], [NE_y, E_y], lw=2, color='black') plt.plot([E_x, SE_x], [E_y, SE_y], lw=2, color='black') plt.plot([SE_x, SW_x], [SE_y, SW_y], lw=2, color='black') plt.plot([SW_x, W_x], [SW_y, W_y], lw=2, color='black') plt.plot([W_x, NW_x], [W_y, NW_y], lw=2, color='black') plt.plot([NW_x, NE_x], [NW_y, NE_y], lw=2, color='black') # Calculate the slope (a's) and intercept (b's) between each two hexagon vertex a1 = (NE_y - E_y)/(NE_x - E_x)*1. # The slope of line NE-E b1 = NE_y - a1 * NE_x # The intercept of line NE-E a2 = (E_y - SE_y)/(E_x - SE_x)*1. # The slope of line E-SE b2 = E_y - a2 * E_x # The intercept of line E-SE a3 = 0 # The slope of line SE-SW is 0 b3 = SE_y # The intercept of line SE-SW is the y-coordinate of either one a4 = (SW_y - W_y)/(SW_x - W_x)*1. # The slope of line SW-W b4 = SW_y - a4 * SW_x # The intercept of line SW-W a5 = (W_y - NW_y)/(W_x - NW_x)*1. # The slope of line W-NW b5 = W_y - a5 * W_x # The intercept of line W-NW a6 = 0 # The slope of line NW-NE is 0 b6 = NW_y # The intercept of line NW-NE is the y-coordinate of either one # The code below is to decide if a point is in the hexagon just built # Use "q" to store the number of points q = 0 for p in xrange(len(x)): if x[p] == [] and y[p] == []: continue else: x_test_NE_E = (y[p]*1. - b1)/a1 x_test_E_SE = (y[p]*1. - b2)/a2 y_test_SE_SW = a3 * x[p] + b3 x_test_SW_W = (y[p]*1. - b4)/a4 x_test_W_NW = (y[p]*1. - b5)/a5 y_test_NW_NE = a6 * x[p] + b6 if x_test_NE_E >= x[p] and x_test_E_SE >= x[p] and y_test_SE_SW <= y[p] and x_test_SW_W <= x[p] and x_test_W_NW <= x[p] and y_test_NW_NE >= y[p]: q += 1 x[p] = [] y[p] = [] hexagons.append(q) # Print out the "hexagons" list print 'There are', len(hexagons) ,'quadrats in total.' for i in xrange(len(hexagons)): print 'Quadrat', i+1, 'has', hexagons[i], 'points.' ax = fig.gca() ax.set_xticks(np.arange(minx-side, maxx+side+1, side)) ax.set_yticks(np.arange(miny-side, maxy+side+1, side)) plt.show() return len(hexagons), hexagons
def gentreas(): """get random x/y coordinates as string for treasures""" treas = [str(rd(0,59)), str(rd(0,14))] return treas