I am making a program that uses maps to hold and organize a music library from a text file. An artist map holds an album map which holds a song map. The problem I am having is that every album for every artist is inserted under each artist rather than just the albums for that artist. I've narrowed it down to this function that determines if the artist is new and inserts it in the artist map if it is. Same for the Albums and the songs once the albums are straightened out.
Here is my class information
class Song {
public:
string title;
int time;
int track;
};
class Album {
public:
map <int, Song *> songs;
string name;
int time;
};
class Artist {
public:
map <string, Album *> albums;
string name;
int time;
int nsongs;
};
Here is the function where I believe the problem is:
map <string, Artist*> newArtist(Artist* a, Album* al, Song* s, string artist, string album, int track, map <string, Artist*> lib){
if (lib.find(artist) == lib.end()){
cout << "New Artist: " << artist << endl;
a->name = artist;
lib[artist] = a;
} else if (lib.find(artist) != lib.end()){
cout << "Old Artist: " << artist << endl;
}
if (lib.find(artist)->second->albums.find(album) == lib.find(artist)->second->albums.end()){
cout << "New Album: " << album << endl;
al->name = album;
lib.find(artist)->second->albums[album] = al;
} else if (lib.find(artist)->second->albums.find(album) != lib.find(artist)->second->albums.end()){
cout << "Old Album: " << album << endl;
}
return lib;
}
This is what prints out. As you can see every single album is under every artist.
King Crimson
A Russian Piano Recital
Intergalactic Boogie Express
Jazz Piano III (A Smithsonian Collection)
Josef Hofmann & Ignace Jan Paderewski Play Liszt
Larks' Tongues In Aspic
Paderewski Plays Concert No. 1
Three of a Perfect Pair
Larkins, Ellis
A Russian Piano Recital
Intergalactic Boogie Express
Jazz Piano III (A Smithsonian Collection)
Josef Hofmann & Ignace Jan Paderewski Play Liszt
Larks' Tongues In Aspic
Paderewski Plays Concert No. 1
Three of a Perfect Pair
League of Crafty Guitarists
A Russian Piano Recital
Intergalactic Boogie Express
Jazz Piano III (A Smithsonian Collection)
Josef Hofmann & Ignace Jan Paderewski Play Liszt
Larks' Tongues In Aspic
Paderewski Plays Concert No. 1
Three of a Perfect Pair
Lewin, Michael
A Russian Piano Recital
Intergalactic Boogie Express
Jazz Piano III (A Smithsonian Collection)
Josef Hofmann & Ignace Jan Paderewski Play Liszt
Larks' Tongues In Aspic
Paderewski Plays Concert No. 1
Three of a Perfect Pair
Paderewski, Ignace
A Russian Piano Recital
Intergalactic Boogie Express
Jazz Piano III (A Smithsonian Collection)
Josef Hofmann & Ignace Jan Paderewski Play Liszt
Larks' Tongues In Aspic
Paderewski Plays Concert No. 1
Three of a Perfect Pair
Any ideas on what I am doing wrong here.
In order to fix this I needed to create the objects within the main program loop and I had to remove the statements where I deleted them.
Related
This is the JavaScript part(car_race.js) i am able to create a track that is moving but it is not that much realistic as it should be. Write now what's happening is if one boundary bar gets completely disappeared then only it appears at the top of the canvas. what i want to do is when one boundary bar goes through the complete canvas from top to bottom i want it to resume back from top with the amount of body it gets disappeared from bottom part of canvas. Can anyone help me with this part.
To create an interval race game in C++, you will need to implement the following steps:
Set up a loop to run the game. The game should continue until the player has finished all the intervals or has chosen to quit.
Display the current interval and prompt the player to enter their time for that interval.
Read the player's time for the interval and store it in a variable.
Calculate the player's time for the entire race by adding their time for the current interval to their total time.
Check if the player has finished all the intervals. If they have, go to step 7. If not, go to step 6.
Display the player's current total time and go back to step 2 to start the next interval.
Display the player's final time and any other relevant information (e.g. their time for each interval).
Here is some sample code that demonstrates how you might implement these steps in C++:
#include <iostream>
#include <string>
using namespace std;
int main() {
// Set up variables to track the player's time and interval count
int interval_count = 0;
int total_time = 0;
// Run the game loop
while (true) {
// Increment the interval count
interval_count++;
// Display the current interval and prompt the player to enter their time
cout << "Interval " << interval_count << ": ";
cout << "Enter your time (in seconds): ";
// Read the player's time for the interval
int interval_time;
cin >> interval_time;
// Add the interval time to the total time
total_time += interval_time;
// Check if the player has finished all the intervals
if (interval_count == 3) {
// The player has finished all the intervals
break;
} else {
// The player has more intervals to complete
cout << "Total time: " << total_time << endl;
}
}
// Display the player's final time
cout << "Final time: " << total_time << endl;
return 0;
}
Background
I bought an Arduino magnetometer/compass with a QMC5883 chip from Amazon, however the bearing output I'm getting doesn't tally with the calculations I've found online. The serial output seems to be plausible (sinusoids with a phase difference of 90°), but the numbers I'm getting for the calculated bearing don't match what they are supposed to. I stored the serial output as a .csv file to graph the magnetometer response when turned through 360° in Excel:
Response was roughly as expected - Z remaining roughly steady (apart from a few wobbles caused by the cable!), X and Y varying sinusoidaly through 360°. (Bear in mind I couldn't turn the magnetometer at a constant speed with my hand which is why the curves are so unsteady).
However below is the graph of what heading was calculated; results were supposed to be between -180° and +180°:
As you can see it only varies around -60° to -160°, and each bearing reading is not unique as it is given by two different rotations of the magnetometer. The specific calculation in the code used (in full at the bottom) is:
bearing =180*atan2(y,x)/3.141592654; //values will range from +180 to -180°
bearing +=0-(19/60); //Adjust for local magnetic declination
Question
I can't figure out what's wrong with the calculation as it is used in a few different sources, and I would like to know how to convert the readings I'm getting to a usable range which is one to one instead of many to one, such as -180° to +180° or 0° to 360°.
Here is the code:
//There are several differences between the QMC5883L and the HMC5883L chips
//Differences in address: 0x0D for QMC5883L; 0x1E for HMC5883L
//Differences in register map (compare datasheets)
//Output data register differences include location of x,y,z and MSB and LSB for these parameters
//Control registers are also different (so location and values for settings change)
#include <Wire.h> //I2C Arduino Library
#define addr 0x0D //I2C Address for The QMC5883L (0x1E for HMC5883)
double scale=1.0;
void setup() {
// double scaleValues[9]={0.00,0.73,0.92,1.22,1.52,2.27,2.56,3.03,4.35};
// scale=scaleValues[2];
//initialize serial and I2C communications
Serial.begin(9600);
Wire.begin();
Wire.beginTransmission(addr); //start talking to slave
Wire.write(0x0B);
Wire.write(0x01);
Wire.endTransmission();
Wire.beginTransmission(addr); //start talking to slave
Wire.write(0x09);
Wire.write(0x1D);
Wire.endTransmission();
}
void loop() {
int x, y, z; //triple axis data
//Tell the QMC what regist to begin writing data into
Wire.beginTransmission(addr);
Wire.write(0x00); //start with register 00H for QMC5883L
Wire.endTransmission();
double bearing=0.00;
//Read the data.. 2, 8 bit bytes for each axis.. 6 total bytes
Wire.requestFrom(addr, 6);
//read 6 registers in order; register location (i.e.00H)indexes by one once read
if (6 <= Wire.available()) {
//note the order of following statements matters
//as each register will be read in sequence starting from data register 00H to 05H
//where order is xLSB,xMSB,yLSB,yMSB,zLSB,zMSB
//this is different from HMC5883L!
//data registers are 03 to 08
//where order is xMSB,xLSB,zMSB,zLSB,yMSB,yLSB
x = Wire.read(); //LSB x;
x |= Wire.read()<<8; //MSB x; bitshift left 8, then bitwise OR to make "x"
// x*=scale;
y = Wire.read(); //LSB y
y |= Wire.read()<<8; //MSB y;
// y*=scale;
z = Wire.read(); //LSB z; irrelevant for compass
z |= Wire.read()<<8; //MSB z;
// z*=scale;
bearing =180*atan2(y,x)/3.141592654;//values will range from +180 to -180 degrees
bearing +=0-(19/60);//Adjust for local magnetic declination
}
// Show Values
//Serial.print("X:");
Serial.print(x);
//Serial.print(" Y: ");
Serial.print(",");
Serial.print(y);
//Serial.print(" Z: ");
Serial.print(",");
Serial.print(z);
//Serial.print(" B: ");
Serial.print(",");
Serial.println(bearing);
delay(500);
}
For others reading this question:
The OP forgot to implement a x,y,z smoothing and an out of scope value removal. How this can be achieved and how its done look into the source code of this QMC5883 compass library:
QMC5883L Compass is an Arduino library for using QMC5583L series chip boards as a compass.
It supports:
Getting values of XYZ axis.
Calculating Azimuth.
Getting 16 point Azimuth bearing direction (0 - 15).
Getting 16 point Azimuth bearing Names (N, NNE, NE, ENE, E, ESE, SE, SSE, S, SSW, SW, WSW, W, WNW, NW, NNW)
Smoothing of XYZ readings via rolling averaging and min / max removal.
I am preparing for an exam that I have on monday and the professor said that this would be on the exam for sure. I know the basic theorems of boolean algebra but I cannot quite simplify these 3. If someone could please explain how this would be done without using a truth table or k-map.
refer your notes. check out the identities you can apply to simplify these expressions.
eg
Y=C(A+A'B')=>C(A+B') using(A+A'B)=A+B
Use De Morgan's law
if you solve first 2 you can do this one.
Here you can refer the basic rules.
Well using c++ and letting the computer do the hard work you could do it like this
# include <iostream>
using namespace std;
int main ()
{
bool Y1,Y2,A,B,C;
Y1 = true;
Y2 = true;
B = false;
A = false;
C = false;
Y1 = A*C+(!A)*(!B)*(C);
Y2 = (!A)*(!B) + (!A)*(B)*(!C) + !(A+(!C));
if (Y1)
cout << "First" << "True"<<endl;
if (Y2)
cout << "Second" << "True"<<endl;
system("Pause");
return 0;
}
As part of a recent job application I was asked to code a solution to this problem.
Given,
n = number of people standing in a circle.
k = number of people to count over each time
Each person is given a unique (incrementing) id. Starting with the first person (the lowest id), they begin counting from 1 to k.
The person at k is then removed and the circle closes up. The next remaining person (following the eliminated person) resumes counting at 1. This process repeats until only one person is left, the winner.
The solution must provide:
the id of each person in the order they are removed from the circle
the id of the winner.
Performance constraints:
Use as little memory as possible.
Make the solution run as fast as possible.
I remembered doing something similar in my CS course from years ago but could not recall the details at the time of this test. I now realize it is a well known, classic problem with multiple solutions. (I will not mention it by name yet as some may just 'wikipedia' an answer).
I've already submitted my solution so I'm absolutely not looking for people to answer it for me. I will provide it a bit later once/if others have provided some answers.
My main goal for asking this question is to see how my solution compares to others given the requirements and constraints.
(Note the requirements carefully as I think they may invalidate some of the 'classic' solutions.)
Manuel Gonzalez noticed correctly that this is the general form of the famous Josephus problem.
If we are only interested in the survivor f(N,K) of a circle of size N and jumps of size K, then we can solve this with a very simple dynamic programming loop (In linear time and constant memory). Note that the ids start from 0:
int remaining(int n, int k) {
int r = 0;
for (int i = 2; i <= n; i++)
r = (r + k) % i;
return r;
}
It is based on the following recurrence relation:
f(N,K) = (f(N-1,K) + K) mod N
This relation can be explained by simulating the process of elimination, and after each elimination re-assigning new ids starting from 0. The old indices are the new ones with a circular shift of k positions. For a more detailed explanation of this formula, see http://blue.butler.edu/~phenders/InRoads/MathCounts8.pdf.
I know that the OP asks for all the indices of the eliminated items in their correct order. However, I believe that the above insight can be used for solving this as well.
You can do it using a boolean array.
Here is a pseudo code:
Let alive be a boolean array of size N. If alive[i] is true then ith person is alive else dead. Initially it is true for every 1>=i<=N
Let numAlive be the number of persons alive. So numAlive = N at start.
i = 1 # Counting starts from 1st person.
count = 0;
# keep looping till we've more than 1 persons.
while numAlive > 1 do
if alive[i]
count++
end-if
# time to kill ?
if count == K
print Person i killed
numAlive --
alive[i] = false
count = 0
end-if
i = (i%N)+1 # Counting starts from next person.
end-while
# Find the only alive person who is the winner.
while alive[i] != true do
i = (i%N)+1
end-while
print Person i is the winner
The above solution is space efficient but not time efficient as the dead persons are being checked.
To make it more efficient time wise you can make use of a circular linked list. Every time you kill a person you delete a node from the list. You continue till a single node is left in the list.
The problem of determining the 'kth' person is called the Josephus Problem.
Armin Shams-Baragh from Ferdowsi University of Mashhad published some formulas for the Josephus Problem and the extended version of it.
The paper is available at: http://www.cs.man.ac.uk/~shamsbaa/Josephus.pdf
This is my solution, coded in C#. What could be improved?
public class Person
{
public Person(int n)
{
Number = n;
}
public int Number { get; private set; }
}
static void Main(string[] args)
{
int n = 10; int k = 4;
var circle = new List<Person>();
for (int i = 1; i <= n; i++)
{
circle.Add(new Person(i));
}
var index = 0;
while (circle.Count > 1)
{
index = (index + k - 1) % circle.Count;
var person = circle[index];
circle.RemoveAt(index);
Console.WriteLine("Removed {0}", person.Number);
}
Console.ReadLine();
}
Console.WriteLine("Winner is {0}", circle[0].Number);
Essentially the same as Ash's answer, but with a custom linked list:
using System;
using System.Linq;
namespace Circle
{
class Program
{
static void Main(string[] args)
{
Circle(20, 3);
}
static void Circle(int k, int n)
{
// circle is a linked list representing the circle.
// Each element contains the index of the next member
// of the circle.
int[] circle = Enumerable.Range(1, k).ToArray();
circle[k - 1] = 0; // Member 0 follows member k-1
int prev = -1; // Used for tracking the previous member so we can delete a member from the list
int curr = 0; // The member we're currently inspecting
for (int i = 0; i < k; i++) // There are k members to remove from the circle
{
// Skip over n members
for (int j = 0; j < n; j++)
{
prev = curr;
curr = circle[curr];
}
Console.WriteLine(curr);
circle[prev] = circle[curr]; // Delete the nth member
curr = prev; // Start counting again from the previous member
}
}
}
}
Here is a solution in Clojure:
(ns kthperson.core
(:use clojure.set))
(defn get-winner-and-losers [number-of-people hops]
(loop [people (range 1 (inc number-of-people))
losers []
last-scan-start-index (dec hops)]
(if (= 1 (count people))
{:winner (first people) :losers losers}
(let [people-to-filter (subvec (vec people) last-scan-start-index)
additional-losers (take-nth hops people-to-filter)
remaining-people (difference (set people)
(set additional-losers))
new-losers (concat losers additional-losers)
index-of-last-removed-person (* hops (count additional-losers))]
(recur remaining-people
new-losers
(mod last-scan-start-index (count people-to-filter)))))))
Explanation:
start a loop, with a collection of people 1..n
if there is only one person left, they are the winner and we return their ID, as well as the IDs of the losers (in order of them losing)
we calculate additional losers in each loop/recur by grabbing every N people in the remaining list of potential winners
a new, shorter list of potential winners is determined by removing the additional losers from the previously-calculated potential winners.
rinse & repeat (using modulus to determine where in the list of remaining people to start counting the next time round)
This is a variant of the Josephus problem.
General solutions are described here.
Solutions in Perl, Ruby, and Python are provided here. A simple solution in C using a circular doubly-linked list to represent the ring of people is provided below. None of these solutions identify each person's position as they are removed, however.
#include <stdio.h>
#include <stdlib.h>
/* remove every k-th soldier from a circle of n */
#define n 40
#define k 3
struct man {
int pos;
struct man *next;
struct man *prev;
};
int main(int argc, char *argv[])
{
/* initialize the circle of n soldiers */
struct man *head = (struct man *) malloc(sizeof(struct man));
struct man *curr;
int i;
curr = head;
for (i = 1; i < n; ++i) {
curr->pos = i;
curr->next = (struct man *) malloc(sizeof(struct man));
curr->next->prev = curr;
curr = curr->next;
}
curr->pos = n;
curr->next = head;
curr->next->prev = curr;
/* remove every k-th */
while (curr->next != curr) {
for (i = 0; i < k; ++i) {
curr = curr->next;
}
curr->prev->next = curr->next;
curr->next->prev = curr->prev;
}
/* announce last person standing */
printf("Last person standing: #%d.\n", curr->pos);
return 0;
}
Here's my answer in C#, as submitted. Feel free to criticize, laugh at, ridicule etc ;)
public static IEnumerable<int> Move(int n, int k)
{
// Use an Iterator block to 'yield return' one item at a time.
int children = n;
int childrenToSkip = k - 1;
LinkedList<int> linkedList = new LinkedList<int>();
// Set up the linked list with children IDs
for (int i = 0; i < children; i++)
{
linkedList.AddLast(i);
}
LinkedListNode<int> currentNode = linkedList.First;
while (true)
{
// Skip over children by traversing forward
for (int skipped = 0; skipped < childrenToSkip; skipped++)
{
currentNode = currentNode.Next;
if (currentNode == null) currentNode = linkedList.First;
}
// Store the next node of the node to be removed.
LinkedListNode<int> nextNode = currentNode.Next;
// Return ID of the removed child to caller
yield return currentNode.Value;
linkedList.Remove(currentNode);
// Start again from the next node
currentNode = nextNode;
if (currentNode== null) currentNode = linkedList.First;
// Only one node left, the winner
if (linkedList.Count == 1) break;
}
// Finally return the ID of the winner
yield return currentNode.Value;
}
I'm wondering what language would be most suitable to simulate the game Chutes and Ladders (Snakes and Ladders in some countries). I'm looking to collect basic stats, like average and standard deviation of game length (in turns), probability of winning based on turn order (who plays first, second, etc.), and anything else of interest you can think of. Specifically, I'm looking for the implementation that is most readable, maintainable, and modifiable. It also needs to be very brief.
If you're a grown-up and don't spend much time around young kids then you probably don't remember the game that well. I'll remind you:
There are 100 squares on the board.
Each player takes turn spinning a random number from 1-6 (or throwing a dice).
The player then advances that many squares.
Some squares are at the base of a ladder; landing on one of these squares means the player gets to climb the ladder, advancing the player's position to a predetermined square.
Some squares are at the top of a slide (chute or snake); landing on one of these squares means the player must slide down, moving the player's position back to a predetermined square.
Whichever player gets to position 100 first is the winner.
This is a bit rough, but it should work:
class Board
attr_accessor :winner
def initialize(players, &blk)
#chutes, #ladders = {}, {}
#players = players
#move = 0
#player_locations = Hash.new(0)
self.instance_eval(&blk)
end
def chute(location)
#chutes[location[:from]] = location[:to]
end
def ladder(location)
#ladders[location[:from]] = location[:to]
end
def spin
player = #move % #players
die = rand(6) + 1
location = (#player_locations[player] += die)
if endpoint = #chutes[location] || endpoint = #ladders[location]
#player_locations[player] = endpoint
end
if #player_locations[player] >= 100
#winner = player
end
#move += 1
end
end
num_players = 4
board = Board.new num_players, do
ladder :from => 4, :to => 14
ladder :from => 9, :to => 31
# etc.
chute :from => 16, :to => 6
# etc.
end
until board.winner
board.spin
end
puts "Player #{board.winner} is the winner!"
You should check out something along the lines of Ruby or Python. Both are basically executable psuedocode.
You might be able to get a shorter, more brilliant program with Haskell, but I would imagine Ruby or Python would probably be actually understandable.
For many statistics, you don't need to simulate. Using Markov Chains, you can reduce many problems to matrix operations on a 100x100-matrix, which only take about 1 millisecond to compute.
I'm going to disagree with some of the earlier posters, and say that an object oriented approach is the wrong thing to do here, as it makes things more complicated.
All you need is to track the position of each player, and a vector to represent the board. If the board position is empty of a chute or ladder, it is 0. If it contains a ladder, the board contains a positive number that indicates how many positions to move forward. If it contains a chute, it contains a negative number to move you back. Just track the number of turns and positions of each player.
The actual simulation with this method is quite simple, and you could do it in nearly any programming language. I would suggest R or python, but only because those are the ones I use most these days.
I don't have a copy of chutes and ladders, so I made up a small board. You'll have to put in the right board:
#!/usr/bin/python
import random, numpy
board = [0, 0, 0, 3, 0, -3, 0, 1, 0, 0]
numplayers = 2
numruns = 100
def simgame(numplayers, board):
winner = -1
winpos = len(board)
pos = [0] * numplayers
turns = 0
while max(pos) < winpos:
turns += 1
for i in range(0, numplayers):
pos[i] += random.randint(1,6)
if pos[i] < winpos:
pos[i] += board[pos[i]]
if pos[i] >= winpos and winner == -1:
winner = i
return (turns, winner)
# simulate games, then extract turns and winners
games = [simgame(numplayers, board) for x in range(numruns)]
turns = [n for (n, w) in games]
winner = [w for (t, w) in games]
pwins = [len([p for p in winner if p == i]) for i in range(numplayers)]
print "runs:", numruns
print "mean(turns):", numpy.mean(turns)
print "sd(turns):", numpy.std(turns)
for i in range(numplayers):
print "Player", (i+1), "won with proportion:", (float(pwins[i])/numruns)
F# isn't too ugly as well, its hard to beat a functional language for conciseness:
#light
open System
let snakes_and_ladders = dict [(1,30);(2,5);(20,10);(50,11)]
let roll_dice(sides) =
Random().Next(sides) + 1
let turn(starting_position) =
let new_pos = starting_position + roll_dice(6)
let found, after_snake_or_ladder = snakes_and_ladders.TryGetValue(new_pos)
if found then after_snake_or_ladder else new_pos
let mutable player_positions = [0;0]
while List.max player_positions < 100 do
player_positions <- List.map turn player_positions
if player_positions.Head > 100 then printfn "Player 1 wins" else printf "Player 2 wins"
I remember about 4 years ago being it a Top Coders competition where the question was what is the probability that player 1 win at snakes and ladders.
There was a really good write-up how to do the puzzle posted after the match. Can't find it now but this write-up is quite good
C/C++ seemed enough to solve the problem well.
Pick any object oriented language, they were invented for simulation.
Since you want it to be brief (why?), pick a dynamically typed language such as Smalltalk, Ruby or Python.