Open In App

Josephus Circle implementation using STL list

Last Updated : 23 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

There are n people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom. Given the total number of person n and a number k which indicates that k-1 persons are skipped and the kth person is killed in the circle. The task is to choose the place in the initial circle so that you are the last one remaining and so survive. (0-based indexing) .

Examples : 

Input : Length of circle : n = 4
        Count to choose next : k = 2
Output : 0

Input : n = 5
        k = 3
Output : 3

We have already discussed different solutions to this problem (here, here, and here). In this post, a  C++ STL-based solution using a list container is discussed which uses the idea of a circular list.

Implementation:

C++




// CPP program to find last man standing
#include <bits/stdc++.h>
using namespace std;
 
int josephusCircle(int n, int k){
    list<int>l; //creates a doubly linked list using stl container//
    for(int i=0;i<n;i++)
        l.push_back(i); //pushes i to the end of the doubly linked list//
      
     auto it = l.begin(); 
    while(l.size()>1){
         
        for(int i=1;i<k;i++){
            it++;
             
            if(it==l.end()){
              //if iterator reaches the end,then we change it to begin of the list//
                it = l.begin();
            }
        }
         
         it = l.erase(it);
          
         if(it==l.end()){
           //if iterator reaches the end,then we change it to begin of the list//
                it = l.begin();
            }
    }
     
    return l.front(); //returns front element of the list//
     
}
/* Driver program to test above functions */
int main()
{
   int n=14,k=2;
       
      cout<<josephusCircle(n,k)<<"\n";
   
    return 0;
}


Java




// Java Code to find the last man Standing
public class GFG {
     
    // Node class to store data
    static class Node
    {
        public int data ;
        public Node next;
        public Node( int data )
        {
            this.data = data;
        }
    }
     
    /* Function to find the only person left
    after one in every m-th node is killed
    in a circle of n nodes */
    static void getJosephusPosition(int m, int n)
    {
        // Create a circular linked list of
        // size N.
        Node head = new Node(0);
        Node prev = head;
        for(int i = 1; i < n; i++)
        {
            prev.next = new Node(i);
            prev = prev.next;
        }
         
        // Connect last node to first
        prev.next = head;
         
        /* while only one node is left in the
        linked list*/
        Node ptr1 = head, ptr2 = head;
         
        while(ptr1.next != ptr1)
        {
             
            // Find m-th node
            int count = 1;
            while(count != m)
            {
                ptr2 = ptr1;
                ptr1 = ptr1.next;
                count++;
            }
             
            /* Remove the m-th node */
            ptr2.next = ptr1.next;
            ptr1 = ptr2.next;
        }
        System.out.println ("Last person left standing " +
                 "(Josephus Position) is " + ptr1.data);
    }
     
    /* Driver program to test above functions */
    public static void main(String args[])
    {
        int n = 14, m = 2;
        getJosephusPosition(m, n);
    }
}


Python3




# Python3 program to find last man standing
 
# /* structure for a node in circular
#    linked list */
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None
 
# /* Function to find the only person left
#    after one in every m-th node is killed
#    in a circle of n nodes */
def getJosephusPosition(m, n):
   
    # Create a circular linked list of
    # size N.
    head = Node(0)
    prev = head
    for i in range(1, n):
        prev.next = Node(i)
        prev = prev.next
    prev.next = head # Connect last
                       #node to first
 
    #/* while only one node is left in the
    #linked list*/
    ptr1 = head
    ptr2 = head
    while (ptr1.next != ptr1):
        # Find m-th node
        count = 1
        while (count != m):
            ptr2 = ptr1
            ptr1 = ptr1.next
            count += 1
 
        # /* Remove the m-th node */
        ptr2.next = ptr1.next
        # free(ptr1)
        ptr1 = ptr2.next
 
    print("Last person left standing (Josephus Position) is ", ptr1.data)
 
# /* Driver program to test above functions */
if __name__ == '__main__':
    n = 14
    m = 2
    getJosephusPosition(m, n)
 
# This code is contributed by mohit kumar 29


C#




// C# Code to find the last man Standing
using System;
public class GFG {
     
    // Node class to store data
    class Node
    {
        public int data ;
        public Node next;
        public Node( int data )
        {
            this.data = data;
        }
    }
     
    /* Function to find the only person left
    after one in every m-th node is killed
    in a circle of n nodes */
    static void getJosephusPosition(int m, int n)
    {
        // Create a circular linked list of
        // size N.
        Node head = new Node(0);
        Node prev = head;
        for(int i = 1; i < n; i++)
        {
            prev.next = new Node(i);
            prev = prev.next;
        }
         
        // Connect last node to first
        prev.next = head;
         
        /* while only one node is left in the
        linked list*/
        Node ptr1 = head, ptr2 = head;
         
        while(ptr1.next != ptr1)
        {
             
            // Find m-th node
            int count = 1;
            while(count != m)
            {
                ptr2 = ptr1;
                ptr1 = ptr1.next;
                count++;
            }
             
            /* Remove the m-th node */
            ptr2.next = ptr1.next;
            ptr1 = ptr2.next;
        }
        Console.WriteLine ("Last person left standing " +
                "(Josephus Position) is " + ptr1.data);
    }
     
    /* Driver program to test above functions */
     static public void Main(String []args)
    {
        int n = 14, m = 2;
        getJosephusPosition(m, n);
    }
}
//contributed by Arnab Kundu


Javascript




<script>
// javascript Code to find the last man Standing
  
 
    // Node class to store data
class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
    }
}
 
    /*
     * Function to find the only person left after one in every m-th node is killed
     * in a circle of n nodes
     */
    function getJosephusPosition(m , n) {
        // Create a circular linked list of
        // size N.
var head = new Node(0);
var prev = head;
        for (i = 1; i < n; i++) {
            prev.next = new Node(i);
            prev = prev.next;
        }
 
        // Connect last node to first
        prev.next = head;
 
        /*
         * while only one node is left in the linked list
         */
var ptr1 = head, ptr2 = head;
 
        while (ptr1.next != ptr1) {
 
            // Find m-th node
            var count = 1;
            while (count != m) {
                ptr2 = ptr1;
                ptr1 = ptr1.next;
                count++;
            }
 
            /* Remove the m-th node */
            ptr2.next = ptr1.next;
            ptr1 = ptr2.next;
        }
        document.write("Last person left standing " + "(Josephus Position) is " + ptr1.data);
    }
 
    /* Driver program to test above functions */
     
        var n = 14, m = 2;
        getJosephusPosition(m, n);
 
// This code is contributed by umadevi9616
</script>


Output

12

Time complexity: O(k * n), as we are using nested loops to traverse k*n time. 
Auxiliary Space: O(n), as we are using extra space for the linked list.

This article is Improved by Mechanizer.  



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads