C++ if statement seems to ignore the argument - function

Here's the code.
bool b_div(int n_dividend)
{
for (int iii = 10 ; iii>0 ; iii--)
{
int n_remainder = n_dividend%iii;
if (n_remainder != 0)
return false;
if (iii = 1)
return true;
}
}
After testing this function I made for a program, the function seems to stop at the if (n_remainder != 0) part. Now then the function SHOULD test if the number that the function takes in can be divided by all numbers from 10 to 1.(it takes in numbers until it returns true) I know the first number that this works with it is 2520 but even on this number it stops at if(n_remainder != 0). So I was hoping for some advice! Im having trouble troubleshooting it! Any links or words I should look for would be awesome! Im still pretty new to programming so any help you can give for learning would rock! Thanks!

Change your last if statement to:
if (iii == 1)
return true;
Currently you have only a single equals sign, which sets the variable iii to 1, and is always true. By using a double equals it will compare iii and 1.

In addition to SC Ghost's answer, you can actually also clean up your function a bit more :)
bool b_div(int n_dividend) {
for (int i = 10 ; i > 1 ; i--) {
int n_remainder = n_dividend % i;
if (n_remainder != 0) {
return false;
}
}
return true;
}
A few notes,
modulus of 1 will always be zero, so you only need to iterate while i > 1
you can completely remove the if(i == 1) check and just always return true after the for loop if the for loop doesn't return false. It basically removes an unnecessary check.
I think it's more standard to name your iterator iii as i, And I prefer brackets the way I wrote them above (this is of course completely personal preference, do as you please)

Related

Is there a race condition in the code of this Parallel Forall blogopost?

I've recently stumbled upon this blogpost in the NVIDIA devblogs:
https://devblogs.nvidia.com/parallelforall/accelerating-graph-betweenness-centrality-cuda/
I´ve implented the edge parallel code and it seems to work as intended, however it seems to me that the code works with a race condition "controlled" with __syncthreads.
This is the code (as shown in the blog):
__shared__ int current_depth;
__shared__ bool done;
if(idx == 0){
done = false;
current_depth = 0;
}
__syncthreads();
// Calculate the number of shortest paths and the
// distance from s (the root) to each vertex
while(!done){
__syncthreads();
done = true;
__syncthreads();
for(int k=idx; k<m; k+=blockDim.x) //For each edge...
{
int v = F[k];
// If the head is in the vertex frontier, look at the tail
if(d[v] == current_depth)
{
int w = C[k];
if(d[w] == INT_MAX){
d[w] = d[v] + 1;
done = false;
}
if(d[w] == (d[v] + 1)){
atomicAdd(&sigma[w],sigma[v]);
}
}
__syncthreads();
current_depth++;
}
}
I think there is a race condition just at the end:
__syncthreads();
current_depth++;
I think the program is relying on the race condition so the variable gets increased only by one, instead of by the number of threads. I don't feel like this is a good idea, but in my tests it seems to be reliable.
Is this really safe? Is there a better way to do it?
Thanks.
As the author of this blog post, I'd like to thank you for pointing out this error!
When I wrote this snippet I didn't use my verbatim edge-traversal code as that used explicit queuing to traverse the graph which makes the example more complicated without adding any pedagogical value. Instead I must have cargo-culted some old code and posted it incorrectly. It's been quite a while since I've touched this code or algorithm, but I believe the following snippet should work:
__shared__ int current_depth;
__shared__ bool done;
if(idx == 0){
done = false;
current_depth = 0;
}
__syncthreads();
// Calculate the number of shortest paths and the
// distance from s (the root) to each vertex
while(!done)
{
__syncthreads();
done = true;
__syncthreads();
for(int k=idx; k<m; k+=blockDim.x) //For each edge...
{
int v = F[k];
// If the head is in the vertex frontier, look at the tail
if(d[v] == current_depth)
{
int w = C[k];
if(d[w] == INT_MAX){
d[w] = d[v] + 1;
done = false;
}
if(d[w] == (d[v] + 1)){
atomicAdd(&sigma[w],sigma[v]);
}
}
}
__syncthreads(); //All threads reach here, no longer UB
if(idx == 0){ //Only one thread should increment this shared variable
current_depth++;
}
}
Notes:
Looks like a similar issue exists in the node parallel algorithm on the blog post
You could also use a register instead of a shared variable for current_depth, in which case every thread would have to increment it
So to answer your question, no, that method is not safe. If I'm not mistaken the blog snippet has the additional issue that current_depth should only be incremented once all vertices at the previous depth were handled, which is at the conclusion of the for loop.
Finally, if you'd like the final version of my code that has been tested and used by people in the community, you can access it here: https://github.com/Adam27X/hybrid_BC

AS3: Minimum value from that is not 0?

I have a problem:
Is there any way I can find the minimum value of an Array that is not 0? Let's say I have this Array:
{0,2,0,0,1} and I want it to find 1.
It should just be a slight variation on finding the minimum including zero. This would be achieved by setting the minimum to the first value and then going through all the others, replacing the minimum if a value in the array is lower.
The modification needed to that for your scenario is to just ignore those having a value of zero. Something like this should do:
var numbers:Array = [0,2,0,0,1];
var started:Boolean = false;
var minval:Number = 0;
for each (var num:Number in numbers) {
if ((!started) && (num != 0)) {
started = true;
minval = num;
}
if ((started) && (num != 0) && (num < minval)) {
minval = num;
}
}
The first if statement will be the only one executed until you find the first non-zero value, at which point you'll set started and store that number as the minimum.
From then on (including on that iteration), you'll just check the non-zero numbers to see if they're less and store them if so.
At the end, either started will be false in which case there were no non-zero numbers, or started will be true and minval will hold the smallest number found.

Pointer to a function with Android

I have a problem to solve with Android, but it's really confusing.
Using the function below:
function accumulate(combiner, nullValue, list){
if(list.length == 0){
return nullValue;
}
var first = list.removeFirst();
return combiner(first, accumulate(combiner, nullValue, list));
}
Develop the function sumOfSquares which returns the sum of squares of a list (Example: 1² + 2² + 3²...)
sumOfSquares([1,2,3,4,5])
returns the number 55.
In this case, the function accumulate must be used. The variable "combiner" is a "pointer to a function". The implementation of the function "combiner" is part of the solution.
I have no problem with the basics, doing the sum of squares, etc, but the part "pointer to a function" really confused me.
If anyone can tell me which is the way to get to the answer, I will be thankful :)
I have done until the code below:
public class MainActivity extends Activity{
protected void onCreate(...){
....
List<Integer> list = new ArrayList<Integer>();
//Fill the list with values
long value = accumulate(sumOfSquares(list), 0, list);
//Show the value
}
private int sumOfSquares(List<Integer> list){
int sum = 0;
for(int i = 0; i < list.size(); i++){
sum += Math.pow(list.get(i), 2);
}
return sum;
}
private long accumulate(int combiner, long nullValue, List<Integer> list){
if(list.size() == 0){
return nullValue;
}
int first = list.get(0);
list.remove(0);
return combiner(first, accumulate(combiner, nullValue, list));
}
private long combiner(int first, int rest){
return first + rest;
}
}
In some languages, the notion of a pointer to a function makes sense, and you could write the code pretty much as you've given it in the example. Not in Java, though, which is what underlies Android. (Android is a bit of a weird choice for this, by the way...)
What you want to do in Java (without giving you the whole solution) is to define a
private int combiner(int first, int rest);
method that takes the first element of the list and the solution to the smaller problem defined by the rest of the list, and produces the answer from these two bits. In other words, if first is the first element, and rest is the sum of the squares of everything except the first element, what is the sum of the squares of the whole list (in terms of first and rest)?
Now your accumulate method does almost exactly what you've written out. It just removes the first element, recursively calls itself on the rest of the list, and returns the value of combining the first element with the result of the recursive call.
The nullValue is there to give you the sum of the squares of an empty list.
If you want to look up more of the details of the theory, you're basically doing functional programming but in an imperative language :)

Continue statements

Wondering what a continue statement does in a do...while(false) loop, I mocked up a simple test-case (pseudo-code):
count = 0;
do {
output(count);
count++;
if (count < 10)
continue;
}while (false);
output('out of loop');
The output was, to my surprise:
0
out of loop
A bit confused, I changed the loop from a do...while to a for:
for (count = 0; count == 0; count++) {
output(count);
if (count < 10)
continue;
}
output('out of loop');
While functionally not the same, the purpose is practically the same: Make a condition only satisfied the first iteration, and in next ones continue (until a certain value is reached, purely for stopping possible infinite-loops.) They might not run the same amount of times, but functionality here isn't the important bit.
The output was the same as before:
0
out of loop
Now, put into terms of a simple while loop:
count = 0;
while (count == 0) {
output(count);
count++;
if (count < 10)
continue;
}
output('out of loop');
Once again, same output.
This is a bit confusing, as I've always thought of the continue statement as "jump to the next iteration". So, here I ask: What does a continue statement do in each of these loops? Does it just jump to the condition?
((For what it's worth, I tested the above in JavaScript, but I believe it's language-agnostic...js had to get at least that right))
In a for loop, continue runs the 3rd expression of the for statement (usually used as some kind of iteration), then the condition (2nd expression), and then the loop if the condition is true. It does not run the rest of the current iteration of the loop.
In a while (or do-while) loop, it just runs the condition and then the loop if the condition holds. It also does not run the rest of the current iteration of the loop.
Your definition of continue statement as "jump to the next iteration" is correct. This will force the program to start next iteration by first re-evaluating the conditional expression.
The problem with your snippets is that they all exit after one iteration because your conditional expressions are set to either false or count ==0. This will always return false after one iteration.
Moreover, putting continue statement at the end of the loop is meaningless. It will re-evaluate the conditional expression in either case.
It's best to think of continue as jumping to the end of the enclosing loop. This may haelp:
#include <iostream>
using namespace std;
int main() {
int n = 0;
do {
cout << n << endl;
n += 1;
if ( n == 3 ) {
continue;
}
cout << "n was not 3" << endl;
} while( n != 3 );
}
which prints:
0
n was not 3
1
n was not 3
2
and terminates, because the continue jumps to the while() at the end of the loop. similar stiff happens for for() and while() loops.
continue skips to the next iteration when it is used in a loop. break exits the current block. Typically, break is used to exit a loop but it could be used to exit any block.
for (int i = 0; i < 1000; i++) {
if (some_condition) {
continue; // would skip to the next iteration
}
if (some_other_condition) {
break; // Exits the loop (block)
}
// other work
}

Removal of every 'kth' person from a circle. Find the last remaining person

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;
}