When I define *x = 7* and use the statement *if (typeof x === "number")*, why does it log *true* on console, but *typeof "number"* logs a "string"? - typeof

I have a simple question but it's bugging me a lot.
When I write this code:
let x = 7;
if (typeof x === "number") {
console.log(true);
} else {
console.log(false);
}
It logs true on console, which as I understand means that here "number" equals a number but when I use
console.log(typeof "number")
it logs string on console.
So in one case "number" acts as a number and in second case a string. Why does it work that way?
I have an array: [3, -2, -6, -1, "error", 9, 13, 17, 15, 14, 9, 5]
and a piece of code in a for loop:
if (typeof curTemp !== "number") continue;
so if the loop sees that "error" is not a number, it continues on, but why

Related

Unable to understand lists in dart consider the example provided

I am developing an app in flutter. For which I am using lists of map but there something that I am unable to undertand. Consider the following cases:
SCENARIO 1
void main() {
List<Map<String,String>> _reminders = [];
Map<String , String> _tempMap = {};
for (int i = 0; i < 5; i++) {
_tempMap.clear();
_tempMap.putIfAbsent('M' , () => 'm ' + i.toString());
_tempMap.putIfAbsent('D' , () => 'd : ' + i.toString());
_reminders.add(_tempMap);
// or _reminders.insert(i, _tempMap);
}
print(_reminders.toString());
return;
}
to which the result is as follows
[{M: m 4, D: d : 4}, {M: m 4, D: d : 4}, {M: m 4, D: d : 4}, {M: m 4, D: d : 4}, {M: m 4, D: d : 4}]
SCENARIO 2
void main() {
List<Map<String,String>> _reminders = [];
for (int i = 0; i < 5; i++) {
Map<String , String> _tempMap = {};
_tempMap.putIfAbsent('M' , () => 'm ' + i.toString());
_tempMap.putIfAbsent('D' , () => 'd : ' + i.toString());
_reminders.add(_tempMap);;
}
print(_reminders.toString());
return;
}
to which the result is as follows
[{M: m 0, D: d : 0}, {M: m 1, D: d : 1}, {M: m 2, D: d : 2}, {M: m 3, D: d : 3}, {M: m 4, D: d : 4}]
As far as I understand, these scenarios should give similar results. Also in my use case scenario 2 is the correct way as it gives me the result that I want. Please note the above examples have been changed to similify the question. The usage in my original code is much more complex.
Dart, like many other programming languages including java, stores objects as reference, and not contiguous memory blocks. In the first case, in all the iterations of the loop, you have added the same Map using the _reminders.add(_tempMap). Your intuition that "Everytime I add the Map, a copy is created of the current state of Map and that copy is appended to the list" is incorrect.
From my understanding, both are different
The problem is with _tempMap.clear(); in the SCENARIO 1. You have used the global variable for map object and when you apply clear inside the for loop all the previously added entries will be cleared and map becomes empty.
when i = 0 => {} => clear() => all entries will be cleared => New item inserted.
when i = 1 => {"Item inserted in 0th iteration"} => clear() => all entries will be cleared => New item inserted.
So for every iteration map is cleared and holds only last iterated value. After for loop is completed it contains only the last iterated value(i=4) since we are clearing the global map variable every time when a new iteration starts.
EDIT :
You can print the map values inside the for loop and can check yourself.
for (int i = 0; i < 5; i++) {
print('\n $i => ${_tempMap} \n');

Making groups (combinations) of objects using their min/max values

First of all, this is my first question, you can tell me how to improve it and what tags to use.
What I am trying to do is I have a bunch of objects that have minimal and maximal values by those values you can deduce if two objects have some sort of overlapping value and thus they can be put together in a group
This question might need dynamic programming to solve.
example objects:
1 ( min: 0, max: 2 )
2 ( min: 1, max: 3 )
3 ( min: 2, max: 4 )
4 ( min: 3, max: 5 )
object 1 can be grouped with objects 2, 3
object 2 can be grouped with objects 1, 3, 4
object 3 can be grouped with objects 1, 2, 4
object 4 can be grouped with objects 2, 3
as you can see there are multiple ways to group those elements
[1, 2]
[3, 4]
[1]
[2, 3]
[4]
[1]
[2, 3, 4]
[1, 2, 3]
[4]
now there should be some sort of rule to deduce which of the solutions is the best solution
for example least amount of groups
[1, 2]
[3, 4]
or
[1]
[2, 3, 4]
or
[1, 2, 3]
[4]
or most objects in one group
[1]
[2, 3, 4]
or
[1, 2, 3]
[4]
or any other rule that uses another attribute of said objects to compare the solutions
what I have now:
$objects = [...objects...];
$numberOfObjects = count($objects);
$groups = [];
for ($i = 0; $i < $numberOfObjects; $i++) {
$MinA = $objects[$i]['min'];
$MaxA = $objects[$i]['max'];
$groups[$i] = [$i];
for ($j = $i + 1; $j < $numberOfObjects; $j++) {
$MinB = $objects[$j]['min'];
$MaxB = $objects[$j]['max'];
if (($MinA >= $MinB && $MinA <= $MaxB) || ($MaxA >= $MinB && $MaxA <= $MaxB) || ($MinB >= $MinA && $MinB <= $MaxA)) {
array_push($groups[$i], $j);
}
}
}
this basically creates an array with indexes of objects that can be grouped together
from this point, I don't know how to proceed, how to generate all the solution and then check each of them how good it is, and the pick the best one
or maybe there is even better solution that doesn't use any of this?
PHP solutions are preferred, although this problem is not PHP-specific
When I was first looking at your algorithm, I was impressed by how efficient it is :)
Here it is rewritten in javascript, because I moved away from perl a good while ago:
function setsOf(objects){
numberOfObjects = objects.length
groups = []
let i
for (i = 0; i < numberOfObjects; i++) {
MinA = objects[i]['min']
MaxA = objects[i]['max']
groups[i] = [i]
for (j = i + 1; j < numberOfObjects; j++) {
MinB = objects[j]['min']
MaxB = objects[j]['max']
if ((MinA >= MinB && MinA <= MaxB) || (MaxA >= MinB && MaxA <= MaxB) ||
(MinB >= MinA && MinB <= MaxA)) {
groups[i].push(j)
}
}
}
return groups
}
if you happen to also think well in javascript, you might find this form more direct (it is identical, however):
function setsOf(objects){
let groups = []
objects.forEach((left,i) => {
groups[i]=[i]
Array.from(objects).splice(i+1).forEach((right, j) => {
if ((left.min >= right.min && left.min <= right.max) ||
(left.max >=right.max && left.max <= right.max) ||
(right.min >= left.min && right.min <= left.max))
groups[i].push(j+i+1)
})
})
return groups
}
so if we run it, we get:
a = setsOf([{min:0, max:2}, {min:1, max:3}, {min:2, max:4}, {min:3, max: 5}])
[Array(3), Array(3), Array(2), Array(1)]0: Array(3)1: Array(3)2: Array(2)3: Array(1)length: 4__proto__: Array(0)
JSON.stringify(a)
"[[0,1,2],[1,2,3],[2,3],[3]]"
and it does impressively catch the compound groups :) a weakness is that it is capturing groups containing more objects than necessary, without capturing all available objects. You seem to have a very custom selection criteria. To me, it seems like the groups should either be every last intersecting subset, or only subsets where each element in the group provides unique coverage: [0,1], [0,2], [1,2], [1,3], [2,3], [0,1,3]
the algorithm for that is perhaps more involved. this was my approach, and it is nowhere near as terse and elegant as yours, but it works:
function intersectingGroups (mmvs) {
const min = []
const max = []
const muxo = [...mmvs]
mmvs.forEach(byMin => {
mmvs.forEach(byMax => {
if (byMin.min === byMax.min && byMin.max === byMax.max) {
console.log('rejecting identity', byMin, byMax)
return // identity
}
if (byMax.min > byMin.max) {
console.log('rejecting non-overlapping objects', byMin, byMax)
return // non-overlapping objects
}
if ((byMax.max <= byMin.max) || (byMin.min >= byMax.min)) {
console.log('rejecting non-expansive coverage or inversed order',
byMin, byMax)
return // non-expansive coverage or inversed order
}
const entity = {min: byMin.min, max: byMax.max,
compositeOf: [byMin, byMax]}
if(muxo.some(mv => mv.min === entity.min && mv.max === entity.max))
return // enforcing Set
muxo.push(entity)
console.log('adding', byMin, byMax, muxo)
})
})
if(muxo.length === mmvs.length) {
return muxo.filter(m => 'compositeOf' in m)
// solution
} else {
return intersectingGroups(muxo)
}
}
now there should be some sort of rule to deduce which of the solutions is the best solution
Yeah, so, usually for puzzles or for a specification you are fulfilling, that would be given as part of the problem. As it is, you want a general method that is adaptable. It's probably best to make an object that can be configured with the results and accepts rules, then load the rules you are interested in, and the results from the search, and see what rules match where. For example, using your algorithm and sample criteria:
least amount of groups
start with code like:
let reviewerFactory = {
getReviewer (specification) { // generate a reviewer
return {
matches: [], // place to load sets to
criteria: specification,
review (objects) { // review the sets already loaded
let group
let results = {}
this.matches.forEach(mset => {
group = [] // gather each object from the initial set for each match in the result set
mset.forEach(m => {
group.push(objects[m])
})
results[mset] = this.criteria.scoring(group) // score the match relative to the specification
})
return this.criteria.evaluation(results) // pick the best score
}
}
},
specifications: {}
}
now you can add specifications like this one for least amount of groups:
reviewerFactory.specifications['LEAST GROUPS'] = {
scoring: function (set) { return set.length },
evaluation: function (res) { return Object.keys(res).sort((a,b) => res[a] - res[b])[0] }
}
then you can use that in the evaluation of a set:
mySet = [{min:0, max:2}, {min:1, max:3}, {min:2, max:4}, {min:3, max: 5}]
rf = reviewerFactory.getReviewer(reviewerFactory.specifications['LEAST GROUPS'])
Object {matches: Array(0), criteria: Object, review: function}
rf.matches = setsOf(mySet)
[Array(3), Array(3), Array(2), Array(1)]
rf.review(mySet)
"3"
or, most objects:
reviewerFactory.specifications['MOST GROUPS'] = {
scoring: function (set) { return set.length },
evaluation: function (res) { return Object.keys(res).sort((a,b) => res[a] - res[b]).reverse()[0] }
}
mySet = [{min:0, max:2}, {min:1, max:3}, {min:2, max:4}, {min:3, max: 5}]
reviewer = reviewerFactory.getReviewer(reviewerFactory.specifications['MOST GROUPS'])
reviewer.matches = setsOf(mySet)
reviewer.review(mySet)
"1,2,3"
Of course this is arbitrary, but so are the criteria, by definition in the OP. Likewise, you would have to change the algorithms here to work with my intersectingGroups function because it doesn't return indices. But this is what you are looking for I believe.

Scala accessing list objects and evaluating number of cycles

Scala accessing list objects and evaluating number of cycles
I have list of objects
case class ItemDesc(a: Int, b: Int, c: Int, d: Int,e: Int, f: Int, g: Int desc: String)
val example = List(ItemDesc(6164,6165,6166,-6195,-6175,-6186,-6195, The values are correct), ItemDesc(14879,-14879,14879,-14894, 14879,14879,14894, The values are ok), ItemDesc(19682,-19690,-19682,19694,19690,19682,19694,The values are good),ItemDesc(5164,-5165,-5166,-6195,5165,5166,6195,The values are correct),ItemDesc(5879,5879,5879,5894,5879,5879,5879,The values are ok))
From the 'example' List, I want to access object 'ItemDesc'. And get the count of cycles. how many times it turns from negative to positive and stays positive for >= 2 seconds.
If >= 2 seconds it is a cycle.
Example 1: (6164,6165,6166,-6195,-6175,-6186,-6195, good)
No. of cycles is 2.
Reason: As we move from 1st element of list to 3rd element, we had 2 intervals which means 2 seconds. Interval is >= 2. So it is one cycle. As we move to 3rd element of list to 4th element, it is a negative value. So we start counting from 4th element and move to 7th element and all elements have same negative sign. we had 3 intervals which means 3 seconds. Interval is >= 2. So it is one cycle. We start counting intervals fresh from zero as one number changes from positive to negative and vice-versa.
Example 2: (14879,-14879,14879,-14894, 14879,14879,14894,better)
No. of cycles is 1.
Reason: As we move from 1st element of list to 2nd element, the sign changes to negative. So we start counting the interval from zero. From element 2 to 3, the sign changes to negative. so interval counter is zero. From element 3 to 4, the sign changes to negative. interval counter is zero. From 5th to 7th all values have same sign, we had 2 intervals which means 2 seconds. Interval is >= 2. So it is one cycle.
Example 3: (5164,-5165,-5166,-6195,5165,5166,6195,good)
No. of cycles is 2
The below code which I wrote is not giving me the no. of cycles which I am looking for. Appreciate help in fixing it.
object findCycles {
def main(args: Array[String]) {
var numberOfPositiveCycles = 0
var numberOfNegativeCycles = 0
var numberOfCycles = 0
case class itemDesc(a: Int, b: Int, c: Int, d: Int, reason: String)
val example = List(ItemDesc(6164,6165,6166,-6195,-6175,-6186,-6195, The values are correct), ItemDesc(14879,-14879,14879,-14894, 14879,14879,14894, The values are ok), ItemDesc(19682,-19690,-19682,19694,19690,19682,19694,The values are good),ItemDesc(5164,-5165,-5166,-6195,5165,5166,6195,The values are correct),ItemDesc(5879,5879,5879,5894,5879,5879,5879,The values are ok))
val data2 = example.map(x => getInteger(x)).filter(_ != "unknown").map(_.toString.toInt)
//println(data2)
var nCycle = findNCycle(data2)
println(nCycle)
}
def getInteger(obj: Any) = obj match {
case n: Int => obj
case _ => "unknown"
}
def findNCycle(obj: List[Int]) : Int = {
def NegativeCycles(fit: itemDesc): Int = {
if (fit.a < 0 && fit.b < 0 && fit.c < 0) || if( fit.b < 0 && fit.c < 0 && fit.d < 0)
{
numberOfNegativeCycles += 1
}
}
//println("negative cycle="+cycles)
def PositiveCycles(fit: itemDesc): Int = {
if (fit.a > 0 && fit.b > 0 && fit.c > 0) || if( fit.b > 0 && fit.c > 0 && fit.d > 0)
{
numberOfPositiveCycles += 1
}
}
//println("positive cycle="+cycles)
numberOfCycles = numberOfPositiveCycles + numberOfNegativeCycles
return numberOfCycles
}
}
For reference on the logic you can refer to- Number of Cycles from list of values, which are mix of positives and negatives in Spark and Scala
Ok this is rough but I think it does what you want. I'm sure there is a more elegant way to do the split method.
I haven't used your ItemDesc as its simpler to demonstrate the problem given the examples you gave.
object CountCycles extends App {
// No. of cycles is 1.
val example1 = List(1, 2, 3, 4, 5, 6, -15, -66)
// No. of cycles is 3.
val example2 = List(11, 22, 33, -25, -36, -43, 20, 25, 28)
// No. of cycles is 8
val example3 = List(1, 4, 82, 5, 6, -2, -12, -22, -32, 100, 102, 100, 102, 0, 0, -2, -12, -22, -32, 4, 82, 5, 6, -6, 8, -6, -6, 8, 8, -5, -6, -7, 9, 8, 6, -5, -6, -7)
def differentSign(x: Int, y: Int): Boolean =
(x < 0) != ( y < 0)
// return a list of sections
def split(l: List[Int]): List[List[Int]] =
l match {
case Nil ⇒ Nil
case h :: _ ⇒
val transition: Int = l.indexWhere(differentSign(h, _))
if (transition < 0) List(l)
else {
val (head, tail) = l.splitAt(transition)
head :: split(tail)
}
}
def count(l: List[Int]): Int = {
val pos: List[List[Int]] = split(l)
// count is the number of sections of length > 2
pos.count(_.length > 2)
}
println(count(example1)) // 1
println(count(example2)) // 3
println(count(example3)) // 8
}
This should be a working solution for the case where you have 7 items in the sample as shown in the description. If your case class changes and instead has a list of values then the implicit helper can be replaced with a simple call to the accessor
import scala.annotation.tailrec
import scala.language.implicitConversions
object CyclesCounter extends App {
val examples = List(
ItemDesc(6164,6165,6166,-6195,-6175,-6186,-6195, "The values are correct"),
ItemDesc(14879,-14879,14879,-14894, 14879,14879,14894, "The values are ok"),
ItemDesc(19682,-19690,-19682,19694,19690,19682,19694,"The values are good"),
ItemDesc(5164,-5165,-5166,-6195,5165,5166,6195,"The values are correct"),
ItemDesc(5879,5879,5879,5894,5879,5879,5879,"The values are ok"))
val counter = new CycleCounter
// Add the index for more readable output
examples.zipWithIndex.foreach{ case (item, index) => println(s"Item at index $index has ${counter.cycleCount(item)} cycles")}
}
class CycleCounter {
def cycleCount(item: ItemDesc): Int = {
#tailrec
def countCycles(remainingValues: List[Int], cycles: Int): Int = {
if (remainingValues.isEmpty) cycles
else {
val headItems = {
if (remainingValues.head < 0) remainingValues.takeWhile(_ < 0)
else remainingValues.takeWhile(_ >= 0)
}
val rest = remainingValues.drop(headItems.length)
if (headItems.length > 2) countCycles(rest, cycles + 1) else countCycles(rest, cycles )
}
}
countCycles(item, 0)
}
// Helper to convert ItemDesc into a List[Int] for easier processing
implicit def itemToValueList(item: ItemDesc): List[Int] = List(item.a, item.b, item.c, item.d, item.e, item.f, item.g)
}
case class ItemDesc(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int, g: Int, reason: String)
Output from running:
Item at index 0 has 2 cycles
Item at index 1 has 1 cycles
Item at index 2 has 1 cycles
Item at index 3 has 2 cycles
Item at index 4 has 1 cycles
Hope that helps
As i read, i see that your problem is to treat the case class as a single entity and no as a list of elements and a reason. I would change the case class to one of these alternatives, first one is if the amount of elements is static (4 in this case):
case class ItemDesc(a: Int, b: Int, c: Int, d: Int, reason: String) {
lazy val getAsList = List(a,b,c,d)
}
ItemDesc(1,2,3,4,"reason").getAsList
In the second case, it can be used if the amount of elements is unbounded:
case class ItemDescAlt(reason:String, elements: Int*)
ItemDescAlt("reason", 5164,-5165,-5166,-6195,5165,5166,6195)
And like the rest i will give my custom version for calculate the number of cycles:
def getCycles(list: Seq[Int]): Int = {
def headPositive(list: Seq[Int]): Boolean = {
list.headOption.forall(_ >= 0)
}
val result = list.foldLeft((0, 0, !headPositive(list))) { //we start with a symbol diferent to the firs one
case ((numberOfCycles, cycleLength, lastWasPositive), number) => { //for each element...
val numberSign = number >= 0
val actualCycleLength = if (numberSign == lastWasPositive) { //see if the actual simbol is equal to the last one
cycleLength + 1 //in that case the length is increased
} else {
0 //in the other reset it
}
val actualNCycles = if (actualCycleLength == 2) { //if the actual length is equal to to
numberOfCycles + 1 //it is a proper new cycle
} else {
numberOfCycles // no new cycles
}
(actualNCycles, actualCycleLength, numberSign) //return the actual state
}
}
result._1 //get the final number of cycles
}
If you already have a solution for List, you can convert any case class into a List using productIterator:
scala> case class X(a:Int, b:Int, c:String)
defined class X
scala> val x = X(1,2,"a")
x: X = X(1,2,a)
scala> x.productIterator.toList
res1: List[Any] = List(1, 2, a)
The main problem is that you get back a List[Any] so you might have to do more work to get a List[Int]

Compact way to write a list of lists

I am writing a program that outputs a list of ordered lists of numbers. Say the output is as follows:
[1,1,1];
[1,1,2]
I would like to look at the output by eye and make some sense of it, but my output is hundreds to thousands of lines long. I would like to write the output in the following more compact format: [1,1,1/2], where the slash indicates that in the third slot I can have a 1 or a 2. So, for a longer example, [1/2, 1/3, 5, 8/9] would be the compact way of writing [1,1,5,8];[1,1,5,9];[1,3,5,8]; etc. Can anyone suggest a pseudocode algorithm for accomplishing this?
Edit: All of the lists are the same length. Also, I expect in general to have multiple lists at the end. For example {[1,1,2], [1,1,3], [1,2,4]} should become {[1,1,2/3], [1,2,4]}.
What'd I do is use a hash at each element in the first list. You'd then iterate through the remaining lists, and for each position in the other lists, you'd check against the hash in the first / original list for that index to see if you'd seen it before. So you'd end up with something like:
[1 : {1}, 1: {1, 3}, 5: {5}, 8: {8, 9}]
And then when printing / formatting the list, you'd just print each key in the hash, except you'd use slashes or whatever.
EDIT: Bad Psuedocode (python)(untested):
def shorten_list(list_of_lists):
primary_list = list_of_lists[0]
hash_values = [{} * len(primary_list)]
for i in range(len(list_of_lists)):
current_list = list_of_lists[i]
for j in range(current_list):
num = current_list[j]
if num not in hash_values[j]:
hash_values[j] = j
for i in range(len(hash_values)):
current_dict = hash_values[i]
print primary_list[i]
for key in current_dict:
if key != primary_list[i]:
print '/', key
Here's actual code to sort the lists the way you wanted. But maybe the most useful visualization would be a scatter plot. Import the data into your favorite spreadsheet, and plot away.
$(document).ready( function(){
var numbers = [
[1, 1, 5, 8],
[1, 1, 5, 9],
[1, 3, 5],
[1, 1, 5, 10, 15]];
$('#output').text(JSON.stringify(compactNumbers(numbers)));
});
function compactNumbers(numberlists){
var output = [];
for(var i = 0; i < numberlists.length; i++){
for(var j = 0; j < numberlists[i].length; j++) {
if(!output[j]) output[j] = [];
if($.inArray(numberlists[i][j], output[j]) == -1){
output[j].push(numberlists[i][j]);
}
}
}
return(output);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>

C++ Program Not Outputting as expected (using .at, if/else, getline)

For some reason my prototype program isn't outputting as expected.
My text file: (separated by tabs)
NameOne NameTwo NameThree 56789
My source code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string name1, name2, name3, name4, name5,fullName;
ifstream inFile;
string attendance;
int index;
inFile.open("test2.dat");
getline(inFile, name1, '\t');
getline(inFile, name2, '\t');
getline(inFile, name3, '\t');
if (name3.at(0) == 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
{
attendance = name3;
fullName = name1 + ' ' + name2;
}
else
{
getline(inFile, name4, '\t');
if (name4.at(0) == 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
{
attendance = name4;
fullName = name1 + ' ' + name2 + ' ' + name3;
}
else
{
getline(inFile, name5, '\t');
if (name5.at(0) == 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
{
attendance = name5;
fullName = name1 + ' ' + name2 + ' ' + name3 + ' ' + name4;
}
else
{
fullName = name1 + ' ' + name2 + ' ' + name3 + ' ' + name4 + ' ' + name5;
inFile >> attendance;
}
}
}
cout << endl << fullName << endl << attendance << endl << endl;
system("pause");
return 0;
}
Expected output :
NameOne NameTwo NameThree
56789
Actual output:
NameOne NameTwo
NameThree
For some reason it's storing the string NameThree into attendance and outputting that.
I was expecting to store NameFour into attendance.
Change this:
if (name.at(0) == 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
To this:
if (isdigit(name.at(0)))
You have two different errors in your code:
The if statement is not properly structured (I'm surprised it even compiles)
In order to check if a character is the 0 digit, for example, you should compare it with '0' (not 0)
You need to fix your if statements:
if (isdigit(name.at(0)))
for the if statement as already stated in another answer.
Now for your stated questiom:
"For some reason it's storing the string NameThree into attendance and outputting that. I was expecting to store NameFour into attendance."
This is because the expression in your first if passes.
name3.at(0) == 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
unfortunately evaluates to true.
The rest of your code (getting name4 etc) is in the else block of that if.
Therefore, everything after the if is executed (and attendance = name3; is executed) and the rest of your code is not run until the end of the else block (and the following cout).
Remember, an if works like this:
if (expr)
{
//run if expr == true
}
else
{
//run if expr == false
}
and don't forget that 0 is false, and everything else is mapped to true when cast to boolean.
In case anyone is wondering how
if (name4.at(0) == 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
even compiles, it's because the C (and by extension C++) language defines , as a binary operator, like / or ->. It has the lowest precedence, left-associativity, and its result is the value on the right-hand side. So the above expression is evaluated as:
(name4.at(0) == 0, 1) => 1
(1, 2) => 2
...
(8, 9) => 9
if(9) => true
(Adding to this, C++ even allows you to override operator,. It's strongly discouraged.)
Before you get too livid at this, bear in mind that this was how inline functions were implemented in the early, early days of C++, before there were native compilers and you used a tool called cfront to convert your C++ to C to then feed a C compiler. For example, if you wrote:
inline int List::read() const
{
int x = *head++;
if(head == end)
head = begin;
return x;
}
Then, when you actually called the function, cfront would insert something like
(__inl_x = *obj->head, ++obj->head, obj->head = (obj->head == obj->end?
obj->begin: obj->head), __inl_x)
into the calling expression. Note that the last thing in the ,-separated list is the return value from the "inline" function. Needless to say, there were a lot of language constructs that weren't allowed in inline functions (much like there are many that aren't allowed in constexpr functions these days.)