Java program for On a Cube Problem
On a Cube Problem
On a cube, the problem is one of the questions asked in TCS CodeVita where we need to calculate the total distance traveled by the beetle. A beetle can travel in al the 3 directions as it is on the surface of the cube. Here is the Java program for On a Cube Problem, which can give the total travel distance covered by a beetle.
Problem Statement
A solid cube of 10 cm x 10cm x 10 cm rests on the ground. It has a beetle on it, and some sweet honey spots at various locations on the surface of the cube. The beetle starts at a point on the surface of the cube and goes to the honey spots in order along the surface of the cube.
- If it goes from a point to another point on the same face (say X to Y), it goes in an arc of a circle that subtends an angle of 60 degrees at the center of the circle
- If it goes from one point to another on a different face, it goes by the shortest path on the surface of the cube, except that it never travels along the bottom of the cube
The beetle is a student of cartesian geometry and knows the coordinates (x, y, z) of all the points it needs to go to. The origin of coordinates it uses is one corner of the cube on the ground, and the z-axis points up.Hence, the bottom surface (on which it does not crawl) is z=0, and the top surface is z=10.The beetle keeps track of all the distances traveled, and rounds the distance traveled to two decimal places once it reaches the next spot so that the final distance is a sum of the rounded distances from spot to spot.
Input Format:
The first line gives an integer N, the total number of points (including the starting point) the beetle visits
- The second line is a set of 3N comma separated non-negative numbers, with up to two decimal places each. These are to be interpreted in groups of three as the x, y, z coordinates of the points the beetle needs to visit in the given order.
Output Format:
- One line with a number giving the total distance traveled by the beetle accurate to two decimal places. Even if the distance traveled is an integer, the output should have two decimal places
Constraints:
None of the points the beetle visits is on the bottom face (z=0) or on any of the edges of the cube (the lines where two faces meet)
2<=N<=10
Sample Input 1:
3
1, 1, 10, 2, 1, 10, 0, 5, 9
Sample Output 1:
6.05
Sample Input 2:
3
1, 1, 10, 2, 1, 10, 0, 1, 9
Sample Output 2:
4.05
On a Cube Problem in few other Coding Languages
C
We don’t have the solution for this problem, you can contribute the answer of this code in C programming language, we post that answer on our page
C++
We don’t have the solution for this problem, you can contribute the answer of this code in C++ programming language, we post that answer on our page
Python
We don’t have the solution for this problem, you can contribute the answer of this code in C programming language, we post that answer on our page
#include
#include
#include
#include
using namespace std;
// Function to calculate the distance between two points in 3D space
double calculateDistance(const vector& p1, const vector& p2) {
double dx = p1[0] – p2[0];
double dy = p1[1] – p2[1];
double dz = p1[2] – p2[2];
return sqrt(dx * dx + dy * dy + dz * dz);
}
// Function to calculate the distance traveled along an arc of a circle
double calculateArcDistance(double radius, double angle) {
return (2 * M_PI * radius * angle) / 360;
}
int main() {
int N;
cin >> N;
vector<vector> coordinates(N, vector(3));
for (int i = 0; i < N; ++i) {
for (int j = 0; j > coordinates[i][j];
}
}
double total_distance = 0.0;
vector current_position = coordinates[0];
for (int i = 1; i < N; ++i) {
const vector& next_position = coordinates[i];
if (current_position[2] == next_position[2]) {
// Same face, move along an arc of a circle
double distance = calculateArcDistance(calculateDistance(current_position, next_position), 60);
distance = round(distance * 100.0) / 100.0;
total_distance += distance;
cout<<distance<<endl;
} else {
// Different face, move along the shortest path on the surface
double distance = calculateDistance(current_position, next_position);
// Round the distance to two decimal places
distance = ceil(distance);
cout<<distance<<endl;
total_distance += distance;
}
current_position = next_position;
}
// Print the total distance with two decimal places
cout << fixed << setprecision(2) << total_distance << endl;
return 0;
}
C++ code easy to understand
Kindly connect with our Discord channel for technical queries💕
Kindly join our Discord Channel for technical queries.
Java code :
import java.util.Scanner;
public class BeetleOnACube {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double distance = 0.0;
double[] currentPoint = {sc.nextDouble(), sc.nextDouble(), sc.nextDouble()};
for (int i = 1; i < n; i++) {
double[] nextPoint = {sc.nextDouble(), sc.nextDouble(), sc.nextDouble()};
double legDistance;
if (currentPoint[2] == nextPoint[2]) { // same face
legDistance = arcDistance(currentPoint, nextPoint);
} else { // different face
legDistance = straightDistance(currentPoint, nextPoint);
}
distance += legDistance;
currentPoint = nextPoint;
}
System.out.printf("%.2f", distance);
}
private static double arcDistance(double[] point1, double[] point2) {
double distance = Math.sqrt(Math.pow(point1[0] – point2[0], 2) + Math.pow(point1[1] – point2[1], 2));
return Math.round(distance * Math.PI / 3 * 100) / 100.0;
}
private static double straightDistance(double[] point1, double[] point2) {
double xDistance = Math.abs(point1[0] – point2[0]);
double yDistance = Math.abs(point1[1] – point2[1]);
double zDistance = Math.abs(point1[2] – point2[2]);
double totalDistance = xDistance + yDistance + zDistance;
if (point1[0] == point2[0] || point1[1] == point2[1]) { // same column or row
return Math.round(totalDistance * 100) / 100.0;
} else { // diagonal
return Math.round((totalDistance – 2) * 100) / 100.0;
}
}
}
import math
N = int(input())
points_arr = list(map(int,input().split(“,”)))
points = []
for i in range(N):
points.append(points_arr[i*3:i*3+3:1])
def calc_distance(arr):
dist_sum = 0
for i in range(1,len(arr)):
curr_loc = arr[i-1]
nxt_loc = arr[i]
same_face = False
adj_face = False
opp_face = False
opp_face_idx = 0
curr_dis = 0
for j in range(3):
if nxt_loc[j]==curr_loc[j] and (nxt_loc[j]==10 or nxt_loc[j]==0):
same_face = True
break
elif abs(nxt_loc[j]-curr_loc[j])==10:
opp_face = True
opp_face_idx = j
break
if not same_face and not opp_face:
adj_face = True
if same_face:
x = pow(nxt_loc[0]-curr_loc[0],2)
y = pow(nxt_loc[1]-curr_loc[1],2)
z = pow(nxt_loc[2]-curr_loc[2],2)
rad = math.sqrt(x+y+z)
curr_dis = math.pi*rad/3
elif adj_face:
face = []
for i in range(3):
if nxt_loc[i]==0 or nxt_loc[i]==10 or curr_loc[i]==0 or curr_loc[i]==10:
face.append(i)
diff = [0,0,0]
diff[0] = abs(nxt_loc[0]-curr_loc[0])
diff[1] = abs(nxt_loc[1]-curr_loc[1])
diff[2] = abs(nxt_loc[2]-curr_loc[2])
x = diff[face[0]] + diff[face[1]]
y = diff[0] + diff[1] + diff[2] -x
curr_dis = math.sqrt(x**2 + y**2)
else:
valid_face = list({0,1,2}-{opp_face_idx})
x = []
y = []
x.append(curr_loc[valid_face[0]]+nxt_loc[valid_face[0]]+10)
x.append(10-curr_loc[valid_face[0]]+10-nxt_loc[valid_face[0]]+10)
x.append(curr_loc[valid_face[1]]+nxt_loc[valid_face[1]]+10)
y.append(abs(nxt_loc[valid_face[1]]-curr_loc[valid_face[1]]))
y.append(abs(nxt_loc[valid_face[1]]-curr_loc[valid_face[1]]))
y.append(abs(nxt_loc[valid_face[0]]-curr_loc[valid_face[0]]))
curr_dis = 30
for i in range(3):
if curr_dis>math.sqrt(x[i]**2 + y[i]**2):
curr_dis = math.sqrt(x[i]**2 + y[i]**2)
dist_sum += round(curr_dis,2)
return “{:.2f}”.format(dist_sum)
print(calc_distance(points))
#include
#include
using namespace std;
#define ll long long
int main(){
int n; cin>>n;
ll x[n],y[n],z[n];
for (int i = 0; i >x[i]>>y[i]>>z[i];
}
double d=0;
for(int i=1;i>=0;i–){
if(x[i]==x[i+1] & y[i]==y[i+1] || x[i]==x[i+1] & z[i]==z[i+1] || z[i]==z[i+1] & y[i]==y[i+1] ){
d+=1.05;
}
else{
d=d+ceil(pow((pow((x[i]-x[i+1]),2)+pow((y[i]-y[i+1]),2)+pow((z[i]-z[i+1]),2)),0.5));
}
}
cout<<d<<endl;
}
#include
using namespace std;
#define PI 3.14
int pt_x,pt_y,pt_z;
float short_dist(int x,int y,int z);
int main()
{
int i,N,a[50],x,y,z;
float sum = 0.0;
cin>>N;
N = 3 * N;
for(i = 0;i >a[i];
}
pt_x = a[0];
pt_y = a[1];
pt_z = a[2];
for(i = 3;i<N;i=i+3)
{
sum = sum + short_dist(a[i],a[i+1],a[i+2]);
}
printf("%.2f",sum);
return 0;
}
float short_dist(int x,int y,int z)
{
float dis = 0.0;
if(z == pt_z && (x == pt_x || y == pt_y) && pt_z != 0)
{
if(x != pt_x){
dis = (2 * PI * (abs(x-pt_x)))/6.0;
}
else{
dis = (2 * PI * (abs(y-pt_y)))/6.0;
}
}
else{
dis = (sqrt(pow(x-pt_x,2) + pow(y-pt_y,2)) + abs(z – pt_z));
}
pt_x = x;
pt_y = y;
pt_z = z;
return dis;
}
3
1 1 10 2 1 10 0 1 9
4.05
include statement is
bits/stdc++.h
Kalyan Chowdary
#include
#include
using namespace std;
int main()
{
long long int n;
cin>>n;
long long int a[n],b[n],c[n],i,s=0;
double x=0.05;
for(i=0;i>a[i]>>b[i]>>c[i];
}
for(i=1;i<n;i++)
{
s=s+ceil(pow((pow((a[i]-a[i-1]),2)+pow((b[i]-b[i-1]),2)+pow((c[i]-c[i-1]),2)),0.5));
}
cout<<x+s;
}
#include
#include
#include
#define PI 3.14
int sx,sy,sz;
float short_dist(int x,int y,int z);
int main()
{
int i,N,a[50],x,y,z;
float sum = 0.0;
scanf(“%d”,&N);
N = 3 * N;
for(i = 0;i < N;i++)
{
scanf("%d",&a[i]);
}
sx = a[0];
sy = a[1];
sz = a[2];
for(i = 3;i<N;i=i+3)
{
sum = sum + short_dist(a[i],a[i+1],a[i+2]);
}
printf("%.2f",sum);
return 0;
}
float short_dist(int x,int y,int z)
{
float dis = 0.0;
if(z == sz && (x == sx || y == sy) && sz != 0)
{
if(x != sx){
dis = (2 * PI * (abs(x – sx)))/6.0;
}
else{
dis = (2 * PI * (abs(y – sy)))/6.0;
}
}
else{
dis = (int)(sqrt(pow(x-sx,2) + pow(y-sy,2)) + abs(z – sz));
}
sx = x;sy = y;sz = z;
return dis;
}
Thanks for contributing the code Lokani, we’ll fix that include statement, don’t worry about it
Please check the solution.
from math import pi
def calculate_distance(point_1, point_2):
for i in range(3):
if point_1[i] in [0,10]:
surface_1 = i
if point_2[i] in [0,10]:
surface_2 = i
if surface_1 == surface_2:
radius = 0
for i in range(3):
if i != surface_1:
radius += (point_1[i] – point_2[i])**2
radius = radius**(0.5)
return round(2*pi*radius/6,2)
else:
height = abs(point_1[surface_1] – point_2[surface_1]) + abs(point_1[surface_2] – point_2[surface_2])
index = 3 – surface_1 – surface_2
base = abs(point_1[index] – point_2[index])
return round(((height)**2+(base)**2)**(0.5), 2)
N = int(input())
coordinates = list(map(int, input().split()))
point_1 = coordinates[:3]
total_distance = 0
for i in range(1,N):
point_2 = coordinates[i*3 : (i+1)*3]
total_distance += (calculate_distance(point_1, point_2))
point_1 = point_2.copy()
print(round(total_distance, 2))
This is wrong
i want this program ans
yeah we are working on this