|
| 1 | +# Copyright (c) Dec 22, 2014 CareerMonk Publications and others. |
| 2 | +# E-Mail : info@careermonk.com |
| 3 | +# Creation Date : 2014-01-10 06:15:46 |
| 4 | +# Last modification : 2008-10-31 |
| 5 | +# by : Narasimha Karumanchi |
| 6 | +# Book Title : Data Structures And Algorithms Made In Java |
| 7 | +# Warranty : This software is provided "as is" without any |
| 8 | +# warranty; without even the implied warranty of |
| 9 | +# merchantability or fitness for a particular purpose. |
| 10 | + |
| 11 | +package main |
| 12 | + |
| 13 | +import ( |
| 14 | + "fmt" |
| 15 | +) |
| 16 | + |
| 17 | +type ListNode struct { // defines a ListNode in a singly linked list |
| 18 | + data interface{} // the datum |
| 19 | + next *ListNode // pointer to the next ListNode |
| 20 | +} |
| 21 | + |
| 22 | +// Create a new node of circular linked list |
| 23 | +func newListNode(data int) *ListNode { |
| 24 | + temp := &ListNode{} |
| 25 | + temp.next = temp |
| 26 | + temp.data = data |
| 27 | + return temp |
| 28 | +} |
| 29 | + |
| 30 | +// Function to find the only person left after one in every m-th node is killed in a circle of n nodes |
| 31 | +func getJosephusPosition(m, n int) { |
| 32 | + // Create a circular linked list of size N. |
| 33 | + head := newNode(1) |
| 34 | + prev := head |
| 35 | + for i := 2; i <= n; i++ { |
| 36 | + prev.next = newListNode(i) |
| 37 | + prev = prev.next |
| 38 | + } |
| 39 | + prev.next = head // Connect last node to first |
| 40 | + |
| 41 | + // while only one node is left in the linked list |
| 42 | + ptr1, ptr2 := head, head |
| 43 | + for ptr1.next != ptr1 { |
| 44 | + // Find m-th node |
| 45 | + count := 1 |
| 46 | + for count != m { |
| 47 | + ptr2 = ptr1 |
| 48 | + ptr1 = ptr1.next |
| 49 | + count++ |
| 50 | + } |
| 51 | + |
| 52 | + // Remove the m-th node |
| 53 | + ptr2.next = ptr1.next |
| 54 | + ptr1 = ptr2.next |
| 55 | + } |
| 56 | + |
| 57 | + fmt.Println("Last person left standing ", "(Josephus Position) is ", ptr1.data) |
| 58 | +} |
| 59 | + |
| 60 | +// Driver program to test above functions |
| 61 | +func main() { |
| 62 | + n, m := 14, 2 |
| 63 | + getJosephusPosition(m, n) |
| 64 | +} |
0 commit comments