In this, we are given an array of numbers, say 1 2 3 4.
We start from a given position, let's say the 1st position. We cancel that number and move forward that many non-cancelled numbers. The number on which we stop again has the same procedure.This is repeated until only one number is left. That is the lucky number.
1 2 3 4
2 3 4
3 4
3
My code:
import java.util.*;
class ln
{
public static void main(String[] ar)throws Exception
{
Scanner sc = new Scanner(System.in);
System.out.print("How many nos. will you enter: ");
int n = sc.nextInt();
int[] a = new int[n];
System.out.print("Enter the nos.: ");
for(int i = 0; i < a.length; i++)
a[i] = sc.nextInt();
System.out.print("From which position do you want to start: ");
int st = sc.nextInt();
for(int i = 0; i < a.length - 1; i++)
{
int j = a[st - 1];
a[st - 1] = 0;
int s = (int)Math.signum(j);
while(j != 0)
{
if(a[st-1] != 0)
j -= s;
st += s;
if(st > a.length)
st = 1;
else if(st < 1)
st = a.length;
}
}
for(int i = 0; i < a.length; i++)
{
if(a[i] != 0)
{
System.out.println("Final no.: " + a[i]);
break;
}
}
}
}
Please tell if there is a more elegant way of doing this .
1 2 3 4
and the starting number1
returns2
, not3
as you have described. \$\endgroup\$