Best Rod code snippet using rod.id
moves.go
Source:moves.go
2import (3 "math"4 "math/rand"5)6func Swap(rod *Rod, grid []*GridSpace, config *Config, rods []*Rod) {7 // copy rod structs to use for rosenbluth trials8 og_rod := RodDeepCopy(rod)9 og_grid_id := og_rod.grid_id10 new_rod := RodDeepCopy(rod)11 // calculate initial surface energy12 og_surface_energy := CalcSurfaceEnergy(og_rod, config)13 // move rod to new location14 GetRandLoc(config, new_rod)15 GetGridID(config.box_dims, config.n_bins, config.grid_bins, new_rod)16 new_grid_id := new_rod.grid_id17 // run k rosenbluth trials to generate swap weights (new location - new orientations)18 GetRandOrientation(config, new_rod)19 GetAxes(new_rod)20 GetVertices(config.n_dim, config.n_vertices, new_rod)21 new_weights := make([]float64, config.k)22 var new_weight_sum float64 = 023 new_orientations := make([]float64, config.k)24 new_surface_energies := make([]float64, config.k)25 for i := 0; i < config.k; i++ {26 new_orientations[i] = new_rod.orientation27 surface_energy := CalcSurfaceEnergy(new_rod, config)28 no_overlaps := CheckNeighborOverlaps(new_rod, grid, rods, config)29 if no_overlaps {30 p := math.Exp(-config.beta * surface_energy)31 new_weights[i] = p32 new_weight_sum += p33 new_surface_energies[i] = surface_energy34 } else {35 new_weights[i] = 036 new_surface_energies[i] = surface_energy + 10e837 }38 if i != (config.k - 1) {39 GetRandOrientation(config, new_rod)40 GetAxes(new_rod)41 GetVertices(config.n_dim, config.n_vertices, new_rod)42 }43 }44 // select new configuration45 var new_surface_energy float6446 new_rod.orientation, new_surface_energy = SelectWeightedConfig(new_orientations, new_surface_energies, new_weights, new_weight_sum, config.k)47 // run k-1 rosenbluth trials to generate weights for original configuration48 var og_weight_sum float64 = math.Exp(-config.beta * og_surface_energy)49 for i := 0; i < (config.k - 1); i++ {50 GetRandOrientation(config, og_rod)51 GetAxes(og_rod)52 GetVertices(config.n_dim, config.n_vertices, og_rod)53 no_overlaps := CheckNeighborOverlaps(og_rod, grid, rods, config)54 if no_overlaps {55 surface_energy := CalcSurfaceEnergy(og_rod, config)56 og_weight_sum += math.Exp(-config.beta * surface_energy)57 }58 }59 // calculate acceptance probability for swap60 var acc float6461 if config.k == 1 {62 acc = math.Exp(-config.beta * (new_surface_energy - og_surface_energy))63 } else {64 acc = (og_weight_sum / new_weight_sum) * math.Exp(-config.beta*(new_surface_energy-og_surface_energy))65 }66 if rand.Float64() < acc {67 // move accepted68 GetAxes(new_rod)69 GetVertices(config.n_dim, config.n_vertices, new_rod)70 if og_grid_id == new_rod.grid_id {71 rods[rod.id] = new_rod72 } else {73 new_rod.grid_id = og_grid_id // temporarily store old grid_id in rod to update old neighbor lists74 RemFromNeighborLists(new_rod, grid)75 new_rod.grid_id = new_grid_id // restore new grid_id to add to new neighbor lists76 AddToNeighborLists(new_rod, grid)77 rods[rod.id] = new_rod78 }79 config.potential_energy += (new_surface_energy - og_surface_energy)80 config.swap_successes++81 }82 config.swap_attempts++83}84func Translate(rod *Rod, grid []*GridSpace, config *Config, rods []*Rod) {85 // store original rod location and grid id86 og_loc := rod.loc87 og_grid_id := rod.grid_id88 // get new location within 1 distance away from current rod COM89 new_loc := make([]float64, config.n_dim)90 if !config.restrict_translations {91 var max_r float64 = 192 max_theta := 2 * math.Pi93 r := rand.Float64() * max_r94 theta := rand.Float64() * max_theta95 v := [2]float64{r * math.Sin(theta), r * math.Cos(theta)}96 new_loc[0] = og_loc[0] + v[0]97 new_loc[1] = og_loc[1] + v[1]98 if new_loc[0] >= config.box_dims[0] {99 new_loc[0] -= config.box_dims[0]100 }101 if new_loc[1] >= config.box_dims[1] {102 new_loc[1] -= config.box_dims[1]103 }104 if new_loc[0] < 0 {105 new_loc[0] += config.box_dims[0]106 }107 if new_loc[1] < 0 {108 new_loc[1] += config.box_dims[0]109 }110 } else {111 rand_move_idx := rand.Intn(len(config.lattice_moves))112 rand_move := config.lattice_moves[rand_move_idx]113 new_lattice_x := rod.lattice_x + rand_move[0]114 new_lattice_y := rod.lattice_y + rand_move[1]115 if new_lattice_x >= config.lattice_x {116 new_lattice_x -= config.lattice_x117 }118 if new_lattice_y >= config.lattice_y {119 new_lattice_y -= config.lattice_y120 }121 if new_lattice_x < 0 {122 new_lattice_x += config.lattice_x123 }124 if new_lattice_y < 0 {125 new_lattice_y += config.lattice_y126 }127 rod.lattice_x = new_lattice_x128 rod.lattice_y = new_lattice_y129 new_loc[0] = config.lattice_grid[rod.lattice_x][rod.lattice_y][0]130 new_loc[1] = config.lattice_grid[rod.lattice_x][rod.lattice_y][1]131 if new_loc[0] > config.box_dims[0] {132 new_loc[0] -= config.box_dims[0]133 }134 if new_loc[1] > config.box_dims[1] {135 new_loc[1] -= config.box_dims[1]136 }137 if new_loc[0] < 0 {138 new_loc[0] += config.box_dims[0]139 }140 if new_loc[1] < 0 {141 new_loc[1] += config.box_dims[0]142 }143 }144 rod.loc = new_loc145 GetGridID(config.box_dims, config.n_bins, config.grid_bins, rod)146 GetAxes(rod)147 GetVertices(config.n_dim, config.n_vertices, rod)148 new_grid_id := rod.grid_id149 // check new rod location for overlaps150 no_overlaps := CheckNeighborOverlaps(rod, grid, rods, config)151 // automatically accept move if there are no overlaps152 if no_overlaps {153 // move accepted154 if og_grid_id == rod.grid_id {155 rods[rod.id] = rod156 } else {157 rod.grid_id = og_grid_id // temporarily store old grid_id in rod to update old neighbor lists158 RemFromNeighborLists(rod, grid)159 rod.grid_id = new_grid_id // restore new grid_id to add to new neighbor lists160 AddToNeighborLists(rod, grid)161 }162 config.translation_successes++163 } else {164 // move rejected165 rod.loc = og_loc166 rod.grid_id = og_grid_id167 GetAxes(rod)168 GetVertices(config.n_dim, config.n_vertices, rod)169 }170 config.translation_attempts++171}172func Rotate(rod *Rod, grid []*GridSpace, config *Config, rods []*Rod) {173 // copy rod structs to use for rosenbluth trials174 og_rod := RodDeepCopy(rod)175 new_rod := RodDeepCopy(rod)176 // calculate initial surface energy177 og_surface_energy := CalcSurfaceEnergy(og_rod, config)178 // fmt.Printf("Original Surface Energy: %f\n", og_surface_energy)179 // run k rosenbluth trials to generate rotation weights (same location - new orientations)180 GetRandOrientation(config, new_rod)181 GetAxes(new_rod)182 GetVertices(config.n_dim, config.n_vertices, new_rod)183 new_weights := make([]float64, config.k)184 var new_weight_sum float64 = 0185 new_orientations := make([]float64, config.k)186 new_surface_energies := make([]float64, config.k)187 for i := 0; i < config.k; i++ {188 new_orientations[i] = new_rod.orientation189 surface_energy := CalcSurfaceEnergy(new_rod, config)190 no_overlaps := CheckNeighborOverlaps(new_rod, grid, rods, config)191 if no_overlaps {192 p := math.Exp(-config.beta * surface_energy)193 // fmt.Printf("New Surface Energy: %f\n", surface_energy)194 new_weights[i] = p195 new_weight_sum += p196 new_surface_energies[i] = surface_energy197 } else {198 // fmt.Printf("New Surface Energy: %f\n", surface_energy+10e8)199 new_weights[i] = 0200 new_surface_energies[i] = surface_energy + 10e8201 }202 if i != (config.k - 1) {203 GetRandOrientation(config, new_rod)204 GetAxes(new_rod)205 GetVertices(config.n_dim, config.n_vertices, new_rod)206 }207 }208 // select new configuration209 var new_surface_energy float64210 new_rod.orientation, new_surface_energy = SelectWeightedConfig(new_orientations, new_surface_energies, new_weights, new_weight_sum, config.k)211 // run k-1 rosenbluth trials to generate weights for original configuration212 var og_weight_sum float64 = math.Exp(-config.beta * og_surface_energy)213 for i := 0; i < (config.k - 1); i++ {214 GetRandOrientation(config, og_rod)215 GetAxes(og_rod)216 GetVertices(config.n_dim, config.n_vertices, og_rod)217 no_overlaps := CheckNeighborOverlaps(og_rod, grid, rods, config)218 if no_overlaps {219 surface_energy := CalcSurfaceEnergy(og_rod, config)220 og_weight_sum += math.Exp(-config.beta * surface_energy)221 }222 }223 // calculate acceptance probability for rotation224 var acc float64225 if config.k == 1 {226 acc = math.Exp(-config.beta * (new_surface_energy - og_surface_energy))227 } else {228 acc = (og_weight_sum / new_weight_sum) * math.Exp(-config.beta*(new_surface_energy-og_surface_energy))229 }230 // fmt.Printf("acceptance probability: %f\n", acc)231 if rand.Float64() < acc {232 // move accepted233 GetAxes(new_rod)234 GetVertices(config.n_dim, config.n_vertices, new_rod)235 rods[rod.id] = new_rod236 config.potential_energy += (new_surface_energy - og_surface_energy)237 if og_rod.orientation != new_rod.orientation {238 config.rotation_successes++239 }240 }241 config.rotation_attempts++242}243func Insert(grid []*GridSpace, config *Config, rods *[]*Rod) {244 // find rod id to insert and either create new rod or refresh rod state245 fromScratch := false246 var rod *Rod247 if len(config.avail_rod_ids) > 0 {248 rand_id := rand.Intn(len(config.avail_rod_ids))249 rod_id := config.avail_rod_ids[rand_id]250 rod = (*rods)[rod_id]251 RodRefresh(config, rod)252 } else {253 fromScratch = true254 rod_id := config.next_unused_rod_id255 rod = &Rod{}256 rod.id = rod_id257 RodInit(config, rod)258 }259 // set rosenbluth k to 1 for insertion260 k := 1261 // run k rosenbluth trials to generate insertion weights (same location - new orientation)262 new_weights := make([]float64, k)263 var new_weight_sum float64 = 0264 new_orientations := make([]float64, k)265 new_surface_energies := make([]float64, k)266 for i := 0; i < k; i++ {267 new_orientations[i] = rod.orientation268 surface_energy := CalcSurfaceEnergy(rod, config)269 no_overlaps := CheckNeighborOverlaps(rod, grid, *rods, config)270 if no_overlaps {271 p := math.Exp(-config.beta * surface_energy)272 new_weights[i] = p273 new_weight_sum += p274 new_surface_energies[i] = surface_energy275 } else {276 new_weights[i] = 0277 new_surface_energies[i] = surface_energy + 10e8278 }279 if i != (k - 1) {280 GetRandOrientation(config, rod)281 GetAxes(rod)282 GetVertices(config.n_dim, config.n_vertices, rod)283 }284 }285 // select new configuration286 var new_surface_energy float64287 rod.orientation, new_surface_energy = SelectWeightedConfig(new_orientations, new_surface_energies, new_weights, new_weight_sum, k)288 // calculate acceptance probability for insertion289 N := float64(config.n_rods)290 acc := (config.V * math.Exp(config.beta*(config.mu-new_surface_energy)) / (N + 1))291 if rand.Float64() < acc {292 // move accepted293 rod.exists = true294 GetAxes(rod)295 GetVertices(config.n_dim, config.n_vertices, rod)296 // add rod to neighbor lists297 AddToNeighborLists(rod, grid)298 // update avail ids299 if !fromScratch {300 cur_rod_idx := 0301 for i := 0; i < len(config.avail_rod_ids); i++ {302 if config.avail_rod_ids[i] == rod.id {303 cur_rod_idx = i304 break305 }306 }307 config.avail_rod_ids = append(config.avail_rod_ids[:cur_rod_idx], config.avail_rod_ids[cur_rod_idx+1:]...)308 } else if fromScratch {309 config.next_unused_rod_id++310 (*rods) = append((*rods), rod)311 }312 config.potential_energy += new_surface_energy313 config.n_rods++314 config.insertion_successes++315 } else {316 // move rejected317 rod.exists = false318 }319 config.insertion_attempts++320}321func Delete(rod *Rod, grid []*GridSpace, config *Config, rods []*Rod) {322 // calculate acceptance probability for deletion323 N := float64(config.n_rods)324 surface_energy := CalcSurfaceEnergy(rod, config)325 acc := (N / (config.V * math.Exp(config.beta*(config.mu-surface_energy))))326 if rand.Float64() < acc {327 // if delete then remove rod from nearest neighbors lists328 RemFromNeighborLists(rod, grid)329 // and remove from rod list330 rod.exists = false331 config.avail_rod_ids = append(config.avail_rod_ids, rod.id)332 config.potential_energy -= surface_energy333 config.n_rods--334 config.deletion_successes++335 }336 config.deletion_attempts++337}...
rods.go
Source:rods.go
...5 "math/rand"6 "gonum.org/v1/gonum/mat"7)8type Rod struct {9 id int10 loc []float6411 lattice_x int12 lattice_y int13 orientation float6414 length float6415 width float6416 length_by_2 float6417 width_by_2 float6418 long_axis []float6419 short_axis []float6420 rot_mat []float6421 vertical_vertices []float6422 rotated_vertices []float6423 grid_id int24 exists bool25 static bool26}27func GetRandRod(rods []*Rod) (rod *Rod) {28 exists := false29 for !exists {30 rod_id := rand.Intn(len(rods))31 rod = rods[rod_id]32 exists = rod.exists33 }34 return rod35}36func GetRandLoc(config *Config, rod *Rod) {37 if !config.restrict_translations {38 x := rand.Float64() * config.box_dims[0]39 y := rand.Float64() * config.box_dims[1]40 if config.n_dim == 2 {41 rod.loc = []float64{x, y}42 } else if config.n_dim == 3 {43 z := rand.Float64() * config.box_dims[2]44 rod.loc = []float64{x, y, z}45 }46 } else {47 rand_lattice_x := rand.Intn(config.lattice_x)48 rand_lattice_y := rand.Intn(config.lattice_y)49 x := config.lattice_grid[rand_lattice_x][rand_lattice_y][0]50 y := config.lattice_grid[rand_lattice_x][rand_lattice_y][1]51 rod.loc = []float64{x, y}52 rod.lattice_x = rand_lattice_x53 rod.lattice_y = rand_lattice_y54 }55}56func GetRandOrientation(config *Config, rod *Rod) {57 if config.restrict_orientations {58 rand_w := rand.Float64()59 if config.lattice_pattern == "triangular" {60 if rand_w < (1. / 3.) {61 rod.orientation = 30.62 } else if rand_w < (2. / 3.) {63 rod.orientation = 90.64 } else {65 rod.orientation = 150.66 }67 } else if config.lattice_pattern == "square" {68 if rand_w < (1. / 2.) {69 rod.orientation = 0.70 } else {71 rod.orientation = 90.72 }73 }74 } else {75 rod.orientation = rand.Float64() * 18076 }77}78func GetGridID(box_dims []float64, n_bins []int, grid_bins [][]float64, rod *Rod) {79 x := rod.loc[0]80 y := rod.loc[1]81 if x > box_dims[0] {82 x -= box_dims[0]83 } else if x < 0 {84 x += box_dims[0]85 }86 if y > box_dims[1] {87 y -= box_dims[1]88 } else if y < 0 {89 y += box_dims[1]90 }91 found_x := false92 found_y := false93 x_bin := n_bins[0] - 194 y_bin := n_bins[1] - 195 var bins_iter int96 if x_bin < y_bin {97 bins_iter = y_bin98 } else {99 bins_iter = x_bin100 }101 for i := 0; i < (bins_iter); i++ {102 var binx float64103 var biny float64104 if !found_x {105 binx = grid_bins[0][i]106 } else {107 binx = 0.108 }109 if !found_y {110 biny = grid_bins[1][i]111 } else {112 biny = 0.113 }114 if (x < binx) && (!found_x) {115 x_bin = i116 found_x = true117 }118 if (y < biny) && (!found_y) {119 y_bin = i120 found_y = true121 }122 if found_x && found_y {123 break124 }125 }126 rod.grid_id = x_bin + y_bin*n_bins[0]127}128func GetAxes(rod *Rod) {129 v := [2]float64{1, 0}130 rod.long_axis = RotateVector(v, rod.orientation)131 rod.short_axis = []float64{-rod.long_axis[1], rod.long_axis[0]}132 rod.rot_mat = rod.long_axis133 rod.rot_mat = append(rod.rot_mat, rod.short_axis...)134}135func GetVertices(n_dim int, n_vertices int, rod *Rod) {136 rot_mat := mat.NewDense(n_dim, n_dim, rod.rot_mat)137 vert_vx_mat := mat.NewDense(n_vertices, n_dim, rod.vertical_vertices)138 rot_vx_mat := mat.NewDense(n_vertices, n_dim, rod.rotated_vertices)139 rot_vx_mat.Mul(vert_vx_mat, rot_mat)140 for i := 0; i < len(rod.rotated_vertices); i++ {141 rod.rotated_vertices[i] += rod.loc[i%2]142 }143}144func RodRefresh(config *Config, rod *Rod) {145 GetRandLoc(config, rod)146 GetRandOrientation(config, rod)147 GetGridID(config.box_dims, config.n_bins, config.grid_bins, rod)148 GetAxes(rod)149 GetVertices(config.n_dim, config.n_vertices, rod)150}151func RodInit(config *Config, rod *Rod) {152 // set rod struct variables153 rod.length = config.rod_length154 rod.width = config.rod_width155 rod.length_by_2 = rod.length / 2156 rod.width_by_2 = rod.width / 2157 rod.long_axis = make([]float64, config.n_dim)158 rod.short_axis = make([]float64, config.n_dim)159 rod.rot_mat = make([]float64, config.n_dim*config.n_dim)160 rod.vertical_vertices = make([]float64, config.n_vertices*config.n_dim)161 all_vertices := []float64{-rod.length_by_2, rod.width_by_2, rod.length_by_2, rod.width_by_2, rod.length_by_2, -rod.width_by_2, -rod.length_by_2, -rod.width_by_2}162 rod.vertical_vertices = all_vertices163 rod.rotated_vertices = make([]float64, config.n_vertices*config.n_dim)164 RodRefresh(config, rod)165}166func CheckOverlap(rod1 *Rod, rod2 *Rod, config *Config) bool {167 if rod1.id == rod2.id {168 return false169 }170 if (rod1.loc[0] == rod2.loc[0]) && (rod1.loc[1] == rod2.loc[1]) {171 return true172 }173 move_rod := false174 var r [2]float64175 r[0] = rod1.loc[0] - rod2.loc[0]176 r[1] = rod1.loc[1] - rod2.loc[1]177 for d := 0; d < len(rod1.loc); d++ {178 f := math.Round(r[d] / config.box_dims[d])179 if math.Round(f) != 0 {180 r[d] = r[d] - config.box_dims[d]*f181 move_rod = true182 }183 }184 if move_rod {185 rod2 = RodDeepCopy(rod2)186 rod2.loc[0] = rod1.loc[0] - r[0]187 rod2.loc[1] = rod1.loc[1] - r[1]188 GetAxes(rod2)189 GetVertices(config.n_dim, config.n_vertices, rod2)190 }191 projections := make([][]float64, config.n_dim)192 for i := 0; i < config.n_dim; i++ {193 projections[i] = make([]float64, config.n_dim*2)194 }195 axes := make([][]float64, config.n_dim*2)196 for i := 0; i < config.n_dim*2; i++ {197 axes[i] = make([]float64, config.n_dim)198 }199 axes[:][0] = rod1.long_axis200 axes[:][1] = rod1.short_axis201 axes[:][2] = rod2.long_axis202 axes[:][3] = rod2.short_axis203 overlap := true204 for i := 0; i < config.n_dim*2; i++ {205 for j := 0; j < config.n_vertices; j++ {206 projections[0][j] = axes[i][0]*rod1.rotated_vertices[j*2] + axes[i][1]*rod1.rotated_vertices[(j*2)+1]207 projections[1][j] = axes[i][0]*rod2.rotated_vertices[j*2] + axes[i][1]*rod2.rotated_vertices[(j*2)+1]208 }209 if config.print_proj {210 fmt.Println(projections)211 }212 min_proj_1, max_proj_1 := MinMax(projections[0][:])213 min_proj_2, max_proj_2 := MinMax(projections[1][:])214 if (min_proj_1 > max_proj_2) || (max_proj_1 < min_proj_2) {215 overlap = false216 return overlap217 }218 }219 return overlap220}221// func CheckOverlapFrenkel(rod1 *Rod, rod2 *Rod, config *Config) bool {222// if rod1.id == rod2.id {223// return false224// }225// move_rod := false226// var r [2]float64227// r[0] = rod1.loc[0] - rod2.loc[0]228// r[1] = rod1.loc[1] - rod2.loc[1]229// for d := 0; d < len(rod1.loc); d++ {230// f := math.Round(r[d] / config.box_size)231// if math.Round(f) != 0 {232// r[d] = r[d] - config.box_size*f233// move_rod = true234// }235// }236// if move_rod {237// rod2 = RodDeepCopy(rod2)238// rod2.loc[0] = rod1.loc[0] - r[0]239// rod2.loc[1] = rod1.loc[1] - r[1]240// GetAxes(rod2)241// GetVertices(config.n_dim, config.n_vertices, rod2)242// }243// v_i := rod1.short_axis244// v_j := rod2.short_axis245// rhs := (math.Pow(config.rod_length, 2) / 4) * (1 - math.Pow(v_i[0]*v_j[0]+v_i[1]*v_j[1], 2))246// g_i := math.Pow(r[0]*v_i[0]+r[1]*v_i[1], 2) - rhs247// g_j := math.Pow(r[0]*v_j[0]+r[1]*v_j[1], 2) - rhs248// if (g_i < 0) && (g_j < 0) {249// return true250// } else {251// return false252// }253// }254func CheckNeighborOverlaps(rod *Rod, grid []*GridSpace, rods []*Rod, config *Config) bool {255 rod_neighbors := grid[rod.grid_id].rod_neighbors256 // rod_neighbor_count := len(rod_neighbors)257 // result := make(chan bool)258 // for i := 0; i < rod_neighbor_count; i++ {259 // go func(rod1 *Rod, rod2 *Rod, config *Config) {260 // overlap := CheckOverlap(rod1, rod2, config)261 // result <- overlap262 // }(rod, rods[grid[rod.grid_id].rod_neighbors[i]], config)263 // }264 // overlaps := false265 // for i := 0; i < rod_neighbor_count; i++ {266 // is_overlap := <-result267 // if is_overlap {268 // overlaps = true269 // }270 // }271 // return !overlaps272 no_overlaps := true273 for i := 0; i < len(rod_neighbors); i++ {274 overlap := CheckOverlap(rod, rods[grid[rod.grid_id].rod_neighbors[i]], config)275 if overlap {276 no_overlaps = false277 return no_overlaps278 }279 }280 return no_overlaps281}282func RemFromNeighborLists(rod *Rod, grid []*GridSpace) {283 for i := 0; i < len(grid[rod.grid_id].grid_neighbors); i++ {284 grid_id := grid[rod.grid_id].grid_neighbors[i]285 rod_neighbors := grid[grid_id].rod_neighbors286 cur_rod_idx := 0287 for j := 0; j < len(rod_neighbors); j++ {288 if rod_neighbors[j] == rod.id {289 cur_rod_idx = j290 break291 }292 }293 new_rod_neighbors := make([]int, 0)294 new_rod_neighbors = append(new_rod_neighbors, grid[grid_id].rod_neighbors[:cur_rod_idx]...)295 new_rod_neighbors = append(new_rod_neighbors, grid[grid_id].rod_neighbors[cur_rod_idx+1:]...)296 grid[grid_id].rod_neighbors = new_rod_neighbors297 }298}299func AddToNeighborLists(rod *Rod, grid []*GridSpace) {300 for i := 0; i < len(grid[rod.grid_id].grid_neighbors); i++ {301 grid_id := grid[rod.grid_id].grid_neighbors[i]302 grid[grid_id].rod_neighbors = append(grid[grid_id].rod_neighbors, rod.id)303 }304}...
clockProblemAnswer.go
Source:clockProblemAnswer.go
1package main2import (3 "fmt"4 "strconv"5)6type BallStatus struct {7 Id int8 BallName string9 CurrentPosition string10 OriginalPosition string11}12type BallList struct {13 Id int14 Name string15 BallStatuses []BallStatus16}17type Results struct {18 Id int19 Days int20 Main []BallStatus21 Min []BallStatus22 FiveMin []BallStatus23 Hour []BallStatus24}25func ballCycleIsRestored(generatedBalls BallList, numBalls int) bool {26 if len(generatedBalls.BallStatuses) == numBalls {27 for i := 0; i < len(generatedBalls.BallStatuses); i++ {28 if generatedBalls.BallStatuses[i].CurrentPosition != generatedBalls.BallStatuses[i].OriginalPosition {29 return false30 }31 }32 } else {33 return false34 }35 return true36}37func findLeastUsedBall(generatedBalls BallList) BallStatus {38 return generatedBalls.BallStatuses[0]39}40func UpdateCurrentPositionBallList(generatedBalls BallList) BallList {41 for i := 0; i < len(generatedBalls.BallStatuses); i++{42 generatedBalls.BallStatuses[i].CurrentPosition = "mainRod" + strconv.Itoa(i)43 }44 return generatedBalls45}46func processUntilBallCycleIsRestored(numBalls int, listToProcess BallList, mode int, minuteAmount int) Results {47 var minuteRod BallList48 minuteRod.Id = 249 minuteRod.Name = "minuteRodCurrentList"50 var fiveMinuteIncrementRod BallList51 fiveMinuteIncrementRod.Id = 352 fiveMinuteIncrementRod.Name = "fiveMinuteIncrementRodCurrentList"53 var twelveHourRod BallList54 twelveHourRod.Id = 555 twelveHourRod.Name = "twelveHourRodCurrentList"56 var mainRod BallList = listToProcess57 mainRod.Id = 658 mainRod.Name = "mainRodCurrentList"59 var minute_tracker int = 060 var five_minute_tracker int = 061 var hour_tracker int = 062 var half_days_passed int = 063 var transfer_minute_rod BallStatus64 var iteratorMax int = 0;65 if mode == 1 {66 iteratorMax = 999999967 } else if mode == 2 {68 iteratorMax = minuteAmount69 }70 71 for z := 0; z < iteratorMax; z++ {72 mainRod = UpdateCurrentPositionBallList(mainRod)73 if z > 10 {74 if ballCycleIsRestored(mainRod, numBalls) == true {75 break76 }77 }78 //Begin Clock Operation -- least used ball or least used ball that is in queue first79 // For now will run as if every iterator is a minute80 // while if iterator is not 0 and current position equals originalPosition then return ball cycles after # of days81 transfer_minute_rod = findLeastUsedBall(mainRod)82 minute_tracker += 183 // minuteRod counter needed84 // , if minuteRod length contains 4 (5 in this case)85 // , then move last ball over to 5 minute increment while other balls go to mainRod (reverse order)86 if len(minuteRod.BallStatuses) < 4 {87 minuteRod.BallStatuses = append(minuteRod.BallStatuses, BallStatus{88 Id: transfer_minute_rod.Id,89 BallName: transfer_minute_rod.BallName,90 CurrentPosition: transfer_minute_rod.CurrentPosition,91 OriginalPosition: transfer_minute_rod.OriginalPosition,92 })93 mainRod.BallStatuses = append(mainRod.BallStatuses[:0], mainRod.BallStatuses[1:]...)94 mainRod = UpdateCurrentPositionBallList(mainRod)95 } else {96 // 5 minute increment counter needed97 // , if fiveMinuteIncrementRod length contains 11 (12)98 // , then move last ball over to hour rod, while others go to mainRod (reverse order)99 mainRod.BallStatuses = append(mainRod.BallStatuses[:0], mainRod.BallStatuses[1:]...)100 mainRod = UpdateCurrentPositionBallList(mainRod)101 for i := len(minuteRod.BallStatuses) - 1; i > -1; i-- {102 mainRod.BallStatuses = append(mainRod.BallStatuses, BallStatus{103 Id: minuteRod.BallStatuses[i].Id,104 BallName: minuteRod.BallStatuses[i].BallName,105 CurrentPosition: minuteRod.BallStatuses[i].CurrentPosition,106 OriginalPosition: minuteRod.BallStatuses[i].OriginalPosition,107 })108 minuteRod.BallStatuses = append(minuteRod.BallStatuses[:i], minuteRod.BallStatuses[i+1:]...)109 }110 mainRod = UpdateCurrentPositionBallList(mainRod)111 112 // hour counter needed and half day counter needed113 // , if mainRod length contains 10 (11)114 // , then move all balls over to MainRod since there is always a ball (reverse order)115 if len(fiveMinuteIncrementRod.BallStatuses) < 11 {116 fiveMinuteIncrementRod.BallStatuses = append(fiveMinuteIncrementRod.BallStatuses, BallStatus{117 Id: transfer_minute_rod.Id,118 BallName: transfer_minute_rod.BallName,119 CurrentPosition: transfer_minute_rod.CurrentPosition,120 OriginalPosition: transfer_minute_rod.OriginalPosition,121 })122 five_minute_tracker += 1123 } else {124 hour_tracker += 1125 for i := len(fiveMinuteIncrementRod.BallStatuses) - 1; i > -1; i-- {126 mainRod.BallStatuses = append(mainRod.BallStatuses, BallStatus{127 Id: fiveMinuteIncrementRod.BallStatuses[i].Id,128 BallName: fiveMinuteIncrementRod.BallStatuses[i].BallName,129 CurrentPosition: fiveMinuteIncrementRod.BallStatuses[i].CurrentPosition,130 OriginalPosition: fiveMinuteIncrementRod.BallStatuses[i].OriginalPosition,131 })132 fiveMinuteIncrementRod.BallStatuses = append(fiveMinuteIncrementRod.BallStatuses[:i], fiveMinuteIncrementRod.BallStatuses[i+1:]...)133 }134 mainRod = UpdateCurrentPositionBallList(mainRod)135 136 // 12 hour section137 if len(twelveHourRod.BallStatuses) < 11 {138 twelveHourRod.BallStatuses = append(twelveHourRod.BallStatuses, BallStatus{139 Id: transfer_minute_rod.Id,140 BallName: transfer_minute_rod.BallName,141 CurrentPosition: transfer_minute_rod.CurrentPosition,142 OriginalPosition: transfer_minute_rod.OriginalPosition,143 })144 } else {145 half_days_passed += 1146 for i := len(twelveHourRod.BallStatuses) - 1; i > -1; i-- {147 mainRod.BallStatuses = append(mainRod.BallStatuses, BallStatus{148 Id: twelveHourRod.BallStatuses[i].Id,149 BallName: twelveHourRod.BallStatuses[i].BallName,150 CurrentPosition: twelveHourRod.BallStatuses[i].CurrentPosition,151 OriginalPosition: twelveHourRod.BallStatuses[i].OriginalPosition,152 })153 twelveHourRod.BallStatuses = append(twelveHourRod.BallStatuses[:i], twelveHourRod.BallStatuses[i+1:]...) 154 }155 mainRod.BallStatuses = append(mainRod.BallStatuses, BallStatus{156 Id: transfer_minute_rod.Id,157 BallName: transfer_minute_rod.BallName,158 CurrentPosition: transfer_minute_rod.CurrentPosition,159 OriginalPosition: transfer_minute_rod.OriginalPosition,160 })161 mainRod = UpdateCurrentPositionBallList(mainRod)162 }163 }164 }165 }166 fmt.Println("minutes passed: ", minute_tracker)167 fmt.Println("hours passed: ", hour_tracker)168 var finalReturn Results169 finalReturn.Days = (half_days_passed / 2)170 return finalReturn171}172func mode01(numBalls int, mode int, minuteAmount int) string {173 if numBalls > 26 && numBalls < 128 {174 // Need dictionary to show ballName, currentPosition, originalPosition175 var myBallList BallList176 myBallList.Id = 1177 myBallList.Name = "BallListMode01"178 for i := 0; i < (numBalls); i++ {179 myBallList.BallStatuses = append(myBallList.BallStatuses, BallStatus{180 Id: i,181 BallName: "ballName" + strconv.Itoa(i),182 CurrentPosition: "mainRod" + strconv.Itoa(i),183 OriginalPosition: "mainRod" + strconv.Itoa(i),184 })185 }186 daysPassed := processUntilBallCycleIsRestored(numBalls, myBallList, mode, minuteAmount)187 return strconv.Itoa(numBalls) + " balls cycle after " + strconv.Itoa(daysPassed.Days) + " days. "188 } else {189 return "Please pass in numbers from 27 to 127."190 }191}192func main() {193 fmt.Println(mode01(45, 1, 0))194}195// Planning to output to JSON196//fmt.Println(myBallList.BallStatuses[0].Id)197/*198json1, err := json.Marshal(myBallList)199if err != nil {200log.Fatal("Cannot encode to JSON ", err)201}202//fmt.Fprintf(os.Stdout, "%s", json1)203var myBallList1 BallList 204bytes := []byte(json1)205json.Unmarshal(bytes, &myBallList1)206fmt.Println(myBallList1)207*/...
id
Using AI Code Generation
1import (2func main() {3 browser := rod.New().Connect()4 page.Element("#hplogo").ID()5 fmt.Println("ID of hplogo is", page.Element("#hplogo").ID())6}7import (8func main() {9 browser := rod.New().Connect()10 element := page.Element("#hplogo")11 fmt.Println("The element ID is", element.ID())12}13import (14func main() {15 browser := rod.New().Connect()16 element := page.Element("#hplogo")17 fmt.Println("The element ID is", element.ID())18}
id
Using AI Code Generation
1import "fmt"2type rod struct {3}4func (r rod) id() {5fmt.Println("rod id is ", r.length)6}7func main() {8r1 := rod{10}9r1.id()10}11import "fmt"12type rod struct {13}14func (r *rod) changeLength(newLength int) {15}16func main() {17r1 := rod{10}18fmt.Println("rod length before change", r1.length)19r1.changeLength(20)20fmt.Println("rod length after change", r1.length)21}
id
Using AI Code Generation
1import (2func main() {3 browser := rod.New().Connect()4 id := page.ID()5 fmt.Println(id)6}7func (p *Page) Screenshot() (string, error)8import (9func main() {10 browser := rod.New().Connect()11 screenshot, err := page.Screenshot()12 fmt.Println(screenshot, err)13}14func (p *Page) Title() (string, error)15import (16func main() {17 browser := rod.New().Connect()18 title, err := page.Title()19 fmt.Println(title, err)20}21func (p *Page) Viewport() (int, int, error)22import (
id
Using AI Code Generation
1import (2type rod struct {3}4func (r *rod) id() {5 fmt.Println("Rod is ", r.length)6}7func main() {8 r := rod{length: 10}9 r.id()10}11import (12type rod struct {13}14func (r *rod) id() {15 fmt.Println("Rod is ", r.length)16}17func main() {18 r := rod{length: 10}19 r.id()20}21import (22type person struct {23}24func main() {25 fmt.Println(person{"Bob", 20})26 fmt.Println(person{name: "Alice", age: 30})27 fmt.Println(person{name: "Fred"})28 fmt.Println(&person{name: "Ann", age: 40})29 s := person{name: "Sean", age: 50}30 fmt.Println(s.name)31 fmt.Println(sp.age)32}33{Bob 20}34{Alice 30}35{Fred 0}36&{Ann 40}37import (38func main() {39 fmt.Println("emp:", a)40 fmt.Println("set:", a)41 fmt.Println("get:", a[4])42 fmt.Println("len:", len(a))43 b := [5]int{1, 2, 3, 4, 5}44 fmt.Println("dcl:", b)45 for i := 0; i < 2; i
id
Using AI Code Generation
1import "fmt"2import "github.com/go-rod/rod"3func main(){4 browser := rod.New().MustConnect()5 defer browser.MustClose()6 id := page.MustElement("input").MustID()7 fmt.Println(id)8}
id
Using AI Code Generation
1import "fmt"2type Rod struct{3}4func (r Rod) id() int{5}6func main(){7r := Rod{length: 10}8fmt.Println(r.id())9}10func (r *Rod) id() int{11}12import "fmt"13type Rod struct{14}15func (r *Rod) id() int{16}17func main(){18r := Rod{length: 10}19fmt.Println(r.id())20}21In the above program, we have created a function id()
id
Using AI Code Generation
1import (2func main() {3 app := widgets.NewQApplication(len(os.Args), os.Args)4 window := widgets.NewQMainWindow(nil, 0)5 window.SetMinimumSize2(600, 400)6 label := widgets.NewQLabel2("Hello World", nil, 0)7 label.SetAlignment(core.Qt__AlignCenter)8 layout := widgets.NewQVBoxLayout()9 layout.AddWidget(label, 0, 0)10 widget := widgets.NewQWidget(nil, 0)11 widget.SetLayout(layout)12 window.SetCentralWidget(widget)13 window.Show()14 app.Exec()15}16import (17func main() {18 app := widgets.NewQApplication(len(os.Args), os.Args)19 window := widgets.NewQMainWindow(nil, 0)20 window.SetMinimumSize2(600, 400)21 label := widgets.NewQLabel2("Hello World", nil, 0)22 label.SetAlignment(core.Qt__AlignCenter)23 layout := widgets.NewQVBoxLayout()24 layout.AddWidget(label, 0, 0)25 widget := widgets.NewQWidget(nil, 0)26 widget.SetLayout(layout)27 window.SetCentralWidget(widget)28 window.Show()29 app.Exec()30}31import (32func main() {33 app := widgets.NewQApplication(len(os.Args
id
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println("Rod id is:", r1.id)4}5import "fmt"6func main() {7 fmt.Println("Rod id is:", r1.id)8}9import "fmt"10func main() {11 fmt.Println("Rod id is:", r1.id)12}13import "fmt"14func main() {15 fmt.Println("Rod id is:", r1.id)16}17import "fmt"18func main() {19 fmt.Println("Rod id is:", r1.id)20}21import "fmt"22func main() {23 fmt.Println("Rod id is:", r1.id)24}25import "fmt"26func main() {27 fmt.Println("Rod id is:", r1.id)28}29import "fmt"30func main() {31 fmt.Println("Rod id is:", r1.id)32}33import "fmt"34func main() {35 fmt.Println("Rod id is:", r1.id)36}
id
Using AI Code Generation
1import (2func main() {3 fmt.Println(rod.Id())4}5import (6func main() {7 fmt.Println(rod.Id())8}9import (10func main() {11 fmt.Println(rod.Id())12}13import (14func main() {15 fmt.Println(rod.Id())16}17import (18func main() {19 fmt.Println(rod.Id())20}21import (22func main() {23 fmt.Println(rod.Id())24}25import (26func main() {27 fmt.Println(rod.Id())28}29import (30func main() {31 fmt.Println(rod.Id())32}33import (34func main() {35 fmt.Println(rod.Id())36}37import (38func main() {39 fmt.Println(rod.Id())40}41import (42func main() {
id
Using AI Code Generation
1import (2func main() {3 browser := rod.New().Connect()4 page.WaitLoad()5 page.Element("input[name=q]").Input("rod").Press(rod.Enter)6 page.WaitLoad()7 page.Element("h3").Click()8 page.WaitLoad()9 fmt.Println(page.URL())10}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!