Find the Big-O of some functions [closed] - big-o

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Hey I'm having some troubling find the what's Big-O this function have, can anyone help me please?, also can you explain how you solved it?, Thanks to everyone(:
public static Node<Polinom> SumPolinoms(Node<Polinom> polinom1, Node<Polinom> polinom2) // 2.B
{
Node<Polinom> temp1, temp2, result, first;
temp1 = polinom1;
temp2 = polinom2;
first = result = new Node<Polinom>(new Polinom(0, 0));
while (temp1 != null && temp2 != null)
{
if (temp1.GetValue().GetPower() == temp2.GetValue().GetPower())
{
result.SetNext(new Node<Polinom>(new Polinom(temp1.GetValue().GetFactor() + temp2.GetValue().GetFactor(), temp1.GetValue().GetPower())));
temp1 = temp1.GetNext();
temp2 = temp2.GetNext();
}
else if (temp1.GetValue().GetPower() < temp2.GetValue().GetPower())
{
result.SetNext(new Node<Polinom>(temp2.GetValue()));
temp2 = temp2.GetNext();
}
else
{
result.SetNext(new Node<Polinom>(temp1.GetValue()));
temp1 = temp1.GetNext();
}
result = result.GetNext();
}
while (temp1 != null)
{
result.SetNext(new Node<Polinom>(temp1.GetValue()));
temp1 = temp1.GetNext();
result = result.GetNext();
}
while (temp2 != null)
{
result.SetNext(new Node<Polinom>(temp2.GetValue()));
temp2 = temp2.GetNext();
result = result.GetNext();
}
return first.GetNext();
}

I may have misunderstood the code, but wouldn’t this be O(2n), because it just runs through each item of temp1 and temp2. O(2n) simplifies to O(n). The code could also be greatly simplified.

Related

Nested For loop exited after 22 items in 27 items, running on Node server side

[Modified]
A little help here can do.
I ran into a problem with for loop. I got one for loop nested in another. The outer loop has just level of elements, while the nested contains only 27 items.
The problem is that the setup can only run through 22 items of the nested array before exiting.
The setup is running on the server side, done in node.js. The Client is React which communicates with the server through websocket. From the console report, node.js runs the above code 3x; and in all those times, only 22 items are looped out of the expected 27.
Join at Repl for the full Node.js dir:
https://replit.com/join/uabhesdiif-emexrevolarter
The code below. I appreciate any help. Thank you.
VerifyResult.js
let data = {};
let error = [];
let feedback = [];
if(typeof dataJson == 'string') {
data = JSON.parse(dataJson)
} else {
data = dataJson;
}
try {
// get variables
const getAvatarState = data.settings.isAvatar;
const getIdState = data.settings.isAdminId;
const getStudents = data.students[0]['Students Data'];
const getClassInfo = data.students[0]['Class Info'][0];
const getAvatars = data.images;
const getLogo = data.logo;
const getFilenames = data.filenames;
const getFirstTermState = data.settings.isFirstTerm;
const getSecondTermState = data.settings.isSecondTerm;
const getThirdTermState = data.settings.isThirdTerm;
const getSubjectList = data.subjects;
let getFirstTerm = [];
let getSecondTerm =[];
let getThirdTerm = [];
// verify #1: if avatars are permitted & same number of images included
if(getAvatarState == '1') {
if(getStudents.length > getAvatars.length) {
feedback.push(`${getAvatars.length} Images supplied for Avatar is lesser than the number of ${getStudents.length} students`);
feedback.push('Some Results may not include Avatar')
}
if(getStudents.length < getAvatars.length) {
feedback.push(`${getAvatars.length} Images supplied for Avatar is more than the number of ${getStudents.length} students`);
feedback.push('This may not pose any problem except possible mismatch')
}
} else {
feedback.push('Avatar will not be included in any result')
}
// verify #2: if logo is included
if(getLogo == null) {
feedback.push('No image was added as logo, and hence, will not be included')
}
// verify #3: if empty value for Admin Numbers, Names, in Students file
let idList = [];
let countItem = 0;
let innerCount = 0;
for(let k = 0; k < getStudents.length; k++) {
let d = getStudents[k];
countItem = k + 1;
let fName, lName;
if(getIdState == '1') {
if(d.Admin_Number != undefined && d.Admin_Number != '') {
idList.push(d.Admin_Number);
} else {
error.push(`Admin Number for Student at row "${countItem}" is empty, in Students workbook`)
}
}
if(d.Firstname != undefined && d.Firstname != '') {
fName = d.Firstname
} else {
error.push(`Firstname for Student at row "${countItem}" is empty, in Students workbook`)
}
if(d.Surname != undefined && d.Surname != '') {
lName = d.Surname
} else {
error.push(`Surname for Student at row "${countItem}" is empty, in Students workbook`)
}
if(fName != undefined && lName != undefined) {
(getIdState == '0') && idList.push(`${lName}/${fName}`);
}
};
// verify #4: if IDs for Students file is unique
if(!IsArrayUnique(idList)) {
(getIdState == '1') && error.push(`One or Student Admin Numbers are not unique, in Students file`);
(getIdState == '0') && error.push(`One or more Student names are not unique, in Students file`);
}
// verify #5: if empty value for Class Info, in Students file
if(getClassInfo.Class_Name == undefined) {
error.push('Class Name of Class Info worksheet is empty, in Students file')
}
if(getClassInfo.School == undefined) {
error.push('School Name of Class Info worksheet is empty, in Students file')
}
if(getClassInfo.Session == undefined) {
error.push('Session of Class Info worksheet is empty, in Students file')
}
if(getClassInfo.Times_School_Opened == undefined) {
error.push('No of Times School Opened of Class Info worksheet is empty, in Students file')
}
countItem = 0;
for(let i = 0; i < getSubjectList.length; i++) {
let sub = getSubjectList[i];
let gFile = getFilenames[i];
countItem = i + 1;
let innError = false;
let list = [];
let subj, fName, lName, sName, termName;
if(getFirstTermState == '1') {
// verify #6: if empty value in Subject files for First Term
innError = false;
termName = 'First Term';
subj = sub['First Term'];
if(sub['Class Info'][0].Class_Name == undefined) {
innError = true;
error.push(`Class Name in ${gFile} is empty`)
}
if(sub['Class Info'][0].Subject == undefined) {
innError = true;
error.push(`Subject Name in ${gFile} is empty`)
}
if(subj < 1) {
innError = true;
error.push(`Subject scores for ${termName} cannot be found in ${gFile}`)
}
if(!innError) {
console.log('==== STUDENTS TOTAL: ', subj.length);
innerCount = 0;
for(let j = 0; j < subj.length; j++) {
let item = subj[j];
innerCount = j + 1;
if(item.Surname == undefined) {
innError = true;
error.push(`Surname for a Student at row ${innerCount} is empty, for ${termName} in ${gFile}`)
}
if(item.Firstname == undefined) {
innError = true;
error.push(`Firstname for a Student at row ${innerCount} is empty, for ${termName} in ${gFile}`)
}
if(item.Admin_Number == undefined && getIdState == '1') {
innError = true;
error.push(`Admin Number for a Student at row ${innerCount} is empty, for ${termName} in ${gFile}`)
}
if(!innError) {
fName = item.Firstname;
lName = item.Surname;
if(item.CA == undefined && !innError) {
innError = true;
error.push(`CA for "${lName} ${fName}" at row ${innerCount} is empty, for ${termName} in ${gFile}`)
}
if(item.Exam == undefined && !innError) {
innError = true;
error.push(`Exam for "${lName} ${fName}" at row ${innerCount} is empty, for ${termName} in ${gFile}`)
}
}
// verify #7: if both CA & Exam are numbers for First Term
if(!innError) {
console.log('====== TOTAL READ: ', innerCount + ' | ' + countItem);
console.log('====== IS CA A NUMBER?: ', item.CA + ' | ' + IsNumber(item.CA));
console.log('====== IS Exam A NUMBER?: ', item.Exam + ' | ' + IsNumber(item.Exam));
if(!IsNumber(item.CA)) {
innError = true;
error.push(`CA for "${lName} ${fName}" at row ${innerCount} is not a number (${item.CA}), for ${termName} in ${gFile}`)
}
if(!IsNumber(item.Exam)) {
innError = true;
error.push(`Exam for "${lName} ${fName}" at row ${innerCount} is not a number (${item.Exam}), for ${termName} in ${gFile}`)
}
}
// verify #8: if Total is > 45 & < 50
if(!innError) {
const itemTotal = Number(item.CA) + Number(item.Exam);
if(itemTotal > 45 && itemTotal < 50) {
innError = true;
error.push(`The CA (CA: ${item.CA}; Exam: ${item.Exam}; Total: ${itemTotal}) for "${lName} ${fName}" at row ${innerCount}, should be upgraded to 50, for ${termName} in ${gFile}`)
}
}
if(!innError) {
if(getIdState == '1'){
sName = item.Admin_Number;
list.push(sName);
} else {
sName = lName + '/' + fName;
list.push(`${sName}`);
}
// verify #9: match IDs as Admin Number or Names for First Term
if(idList.indexOf(sName) === -1) {
innError = true;
(getIdState == '1') && error.push(`Student Admin Number "${sName}" is mismatched, for ${termName} in ${gFile}`);
(getIdState == '0') && error.push(`Student name "${lName} ${fName}" is mismatched, for ${termName} in ${gFile}`);
}
}
}
// verify #10: if unique IDs for First Term
if(!innError) {
if(idList.length == list.length) {
if(!IsArrayUnique(list)){
innError = true;
(getIdState == '1') && error.push(`One or more Student Admin Numbers are not unique, for ${termName} in ${gFile}`)
(getIdState == '0') && error.push(`One or more Student names are not unique, for ${termName} in ${gFile}`);
}
} else {
innError = true;
error.push(`Found ${list.length} Students against expected ${idList.length} number of Students, for ${termName} in ${gFile}`)
}
}
}
}
}
// verify #3: match admin Id is set as active, else match students names
} catch (err) {
error.push(err)
}
const res = {
data: data,
error: error,
feedback: feedback
}
data.json
{"settings":{"isAdminId":"1","isFirstTerm":"1","isSecondTerm":"0","isThirdTerm":"0","isAvatar":"1","isVerify":"1"},"subjects":[{"First Term":[{"Surname":"ADEOLA","Firstname":"TOLUWALASE","CA":38,"Exam":56,"Admin_Number":"AND/J/0271"},{"Surname":"ADEMOLA","Firstname":"SAMUEL","CA":35,"Exam":55,"Admin_Number":"ADM/J/0273"},{"Surname":"AGBONIRO","Firstname":"JESSE","CA":40,"Exam":54,"Admin_Number":"ADM/J/0284"},{"Surname":"AJAYI","Firstname":"ABIGAIL","CA":23,"Exam":33,"Admin_Number":"ADM/J/0269"},{"Surname":"AKANDE","Firstname":"MICHAEL","CA":29,"Exam":41,"Admin_Number":"ADM/J/0267"},{"Surname":"AKINTOKUN","Firstname":"MOFE","CA":27,"Exam":47,"Admin_Number":"ADM/J/0272"},{"Surname":"ARTHUR","Firstname":"DESTINY","CA":33,"Exam":55,"Admin_Number":"ADM/J/0266"},{"Surname":"AYANWENU","Firstname":"AKOREDE","CA":22,"Exam":35,"Admin_Number":"ADM/J/0270"},{"Surname":"BETHEL","Firstname":"MOYINULUWA","CA":40,"Exam":58,"Admin_Number":"ADM/J/0274"},{"Surname":"CHIJIOKE","Firstname":"JOY","CA":26,"Exam":44,"Admin_Number":"ADM/J/0276"},{"Surname":"CHINWUBA","Firstname":"CHARLES","CA":33,"Exam":40,"Admin_Number":"ADM/J/0275"},{"Surname":"DAVID","Firstname":"BEST","CA":40,"Exam":59,"Admin_Number":"ADM/J/0277"},{"Surname":"DUYILE","Firstname":"IFEOLUWA","CA":29,"Exam":41,"Admin_Number":"ADM/J/0256"},{"Surname":"EZEADILI","Firstname":"CHIBUNDU","CA":35,"Exam":49,"Admin_Number":"ADM/J/0278"},{"Surname":"FAGITE","Firstname":"TOBILOBA","CA":40,"Exam":57,"Admin_Number":"ADM/J/0279"},{"Surname":"IDOGEN","Firstname":"EHIZOFUA","CA":31,"Exam":51,"Admin_Number":"ADM/J/0282"},{"Surname":"IFADA","Firstname":"HOSSONA","CA":33,"Exam":50,"Admin_Number":"ADM/J/0255"},{"Surname":"IHEDIOHA","Firstname":"DELIGHT","CA":34,"Exam":53,"Admin_Number":"ADM/J/0280"},{"Surname":"JOSIAH","Firstname":"MATTHEW","CA":29,"Exam":49,"Admin_Number":"ADM/J/0283"},{"Surname":"MBONU","Firstname":"MMESOMA","CA":32,"Exam":45,"Admin_Number":"ADM/J/0285"},{"Surname":"NWONU","Firstname":"DAVID","CA":27,"Exam":41,"Admin_Number":"ADM/J/0260"},{"Surname":"OBI","Firstname":"LUCIA","CA":20,"Exam":26,"Admin_Number":"ADM/J/0289"},{"Surname":"ODOZOR","Firstname":"AUSTIN","CA":19,"Exam":29,"Admin_Number":"ADM/J/0249"},{"Surname":"OLAWALE","Firstname":"MOYINOLUWA","CA":29,"Admin_Number":"ADM/J/0290"},{"Surname":"OKERENITE","Firstname":"SPLENDID","Exam":53,"Admin_Number":"ADM/J/0287"},{"Surname":"OKUSHI","Firstname":"DANIEL","CA":32,"Exam":"x","Admin_Number":"ADM/J/0288"},{"Surname":"DABRINZE","Firstname":"POSSIBLE","CA":"y","Exam":40,"Admin_Number":"ADM/J/0250"}],"Second Term":[],"Third Term":[],"Class Info":[{"Class_Name":"JS2 Goodness","Subject":"BST (Information Tech.)"}],"ID":[{"Id":"Subjects","Start_Row":3}]}],"filenames":["subject_ict.xlsx"],"students":[{"Students Data":[{"Surname":"ADEOLA","Firstname":"TOLUWALASE","House":"Green","Admin_Number":"AND/J/0271","DOB":"26 FEB 2010","Sex":"M","Times_Present":126,"Override_Teacher_Comment":"very naughty","Override_Skills_Musical":3,"Override_Skills_Painting":4,"Override_Skills_Craft":3,"Override_Skills_Tools":3,"Override_Skills_Fluency":4,"Override_Sports_Indoor":4,"Override_Sports_Ball":4,"Override_Sports_Combative":3,"Override_Sports_Track":3,"Override_Sports_Gymnastics":4,"Override_Curricular_Jets":5,"Override_Curricular_Farmers":3,"Override_Curricular_Debating":4,"Override_Curricular_Homemaker":5,"Override_Curricular_Drama":5,"Override_Curricular_Voluntary":4,"Override_Curricular_Others":3,"Override_Behaviour_Reliability":5,"Override_Behaviour_Neatness":5,"Override_Behaviour_Politeness":5,"Override_Behaviour_Honesty":5,"Override_Behaviour_Creativity":4,"Override_Behaviour_Leadership":5,"Override_Behaviour_Spirituality":5,"Override_Behaviour_Cooporation":5},{"Surname":"ADEMOLA","Firstname":"SAMUEL","House":"Green","Admin_Number":"ADM/J/0273","DOB":"27 MAY 2009","Sex":"M","Times_Present":126},{"Surname":"AGBONIRO","Firstname":"JESSE","House":"Red","Admin_Number":"ADM/J/0284","DOB":"9 SEPT 2010","Sex":"M","Times_Present":126},{"Surname":"AJAYI","Firstname":"ABIGAIL","House":"Green","Admin_Number":"ADM/J/0269","DOB":"JUNE 2010","Sex":"F","Times_Present":120},{"Surname":"AKANDE","Firstname":"MICHAEL","House":"Red","Admin_Number":"ADM/J/0267","DOB":"29 DEC 2010","Sex":"M","Times_Present":126},{"Surname":"AKINTOKUN","Firstname":"MOFE","House":"Yellow","Admin_Number":"ADM/J/0272","DOB":"21 JULY 2010","Sex":"M","Times_Present":126},{"Surname":"ARTHUR","Firstname":"DESTINY","House":"Green","Admin_Number":"ADM/J/0266","DOB":"23 AUG 2009","Sex":"M","Times_Present":126},{"Surname":"AYANWENU","Firstname":"AKOREDE","House":"Blue","Admin_Number":"ADM/J/0270","DOB":"17 MAY 2010","Sex":"F","Times_Present":126},{"Surname":"BETHEL","Firstname":"MOYINULUWA","House":"Blue","Admin_Number":"ADM/J/0274","DOB":"13 MAR 2010","Sex":"F","Times_Present":126},{"Surname":"CHIJIOKE","Firstname":"JOY","House":"Yellow","Admin_Number":"ADM/J/0276","DOB":"27 FEB 2010","Sex":"F","Times_Present":126},{"Surname":"CHINWUBA","Firstname":"CHARLES","House":"Yellow","Admin_Number":"ADM/J/0275","DOB":"15 MAY 2010","Sex":"M","Times_Present":122},{"Surname":"DAVID","Firstname":"BEST","House":"Yellow","Admin_Number":"ADM/J/0277","DOB":"3 MAR 2010","Sex":"F","Times_Present":126},{"Surname":"DUYILE","Firstname":"IFEOLUWA","House":"Green","Admin_Number":"ADM/J/0256","DOB":"8 JAN 2010","Sex":"M","Times_Present":126},{"Surname":"EZEADILI","Firstname":"CHIBUNDU","House":"Yellow","Admin_Number":"ADM/J/0278","DOB":"14 FEB 2010","Sex":"M","Times_Present":126},{"Surname":"FAGITE","Firstname":"TOBILOBA","House":"Blue","Admin_Number":"ADM/J/0279","DOB":"26 AUG 2010","Sex":"M","Times_Present":126},{"Surname":"IDOGEN","Firstname":"EHIZOFUA","House":"Blue","Admin_Number":"ADM/J/0282","DOB":"6 JUNE 2010","Sex":"F","Times_Present":126},{"Surname":"IFADA","Firstname":"HOSSONA","House":"Red","Admin_Number":"ADM/J/0255","DOB":"12 OCT 2010","Sex":"M","Times_Present":126},{"Surname":"IHEDIOHA","Firstname":"DELIGHT","House":"Green","Admin_Number":"ADM/J/0280","DOB":"4 NOV 2010","Sex":"M","Times_Present":126},{"Surname":"JOSIAH","Firstname":"MATTHEW","House":"Red","Admin_Number":"ADM/J/0283","DOB":"13 AUG 2010","Sex":"F","Times_Present":126},{"Surname":"MBONU","Firstname":"MMESOMA","House":"Green","Admin_Number":"ADM/J/0285","DOB":"17 MAY 2009","Sex":"F","Times_Present":126},{"Surname":"NWONU","Firstname":"DAVID","House":"Yellow","Admin_Number":"ADM/J/0260","DOB":"29 AUG 2010","Sex":"M","Times_Present":124},{"Surname":"OBI","Firstname":"LUCIA","House":"Red","Admin_Number":"ADM/J/0289","DOB":"29 DEC 2010","Sex":"F","Times_Present":126},{"Surname":"ODOZOR","Firstname":"AUSTIN","House":"Green","Admin_Number":"ADM/J/0249","DOB":"9 AUG 2008","Sex":"M","Times_Present":126},{"Surname":"OLAWALE","Firstname":"MOYINOLUWA","House":"Red","Admin_Number":"ADM/J/0290","DOB":"19 SEP 2010","Sex":"F","Times_Present":108},{"Surname":"OKERENITE","Firstname":"SPLENDID","House":"Green","Admin_Number":"ADM/J/0287","DOB":"14 DEC 2009","Sex":"M","Times_Present":126},{"Surname":"OKUSHI","Firstname":"DANIEL","House":"Blue","Admin_Number":"ADM/J/0288","DOB":"29 SEP 2010","Sex":"M","Times_Present":126},{"Surname":"DABRINZE","Firstname":"POSSIBLE","House":"Yellow","Admin_Number":"ADM/J/0250","DOB":"20 JUN 2010","Sex":"M","Times_Present":126}],"Class Info":[{"Class_Name":"JS2 Goodness","School":"Junior Secondary","Session":"2021/2022","Times_School_Opened":126,"Next_Term_Begins":"4th January, 2022"}],"Settings":[{"Id_By_Admin_No":"Yes","First_Term_Active":"Yes","Second_Term_Active":"No","Third_Term_Active":"No","Students_Photos":"Yes","Verify":"Yes"}],"ID":[{"Id":"Students","Start_Row":3}]}],"keys":[{"Junior Grade Keys":[{"Grade_Name":"A","Min_Value":70,"Max_Value":100},{"Grade_Name":"B","Min_Value":60,"Max_Value":69.9},{"Grade_Name":"C","Min_Value":50,"Max_Value":59.9},{"Grade_Name":"P","Min_Value":40,"Max_Value":49.9},{"Grade_Name":"F","Min_Value":0,"Max_Value":39.9}],"Senior Grade Keys":[{"Grade_Name":"A","Min_Value":75,"Max_Value":100},{"Grade_Name":"B2","Min_Value":70,"Max_Value":74.9},{"Grade_Name":"B3","Min_Value":65,"Max_Value":69.9},{"Grade_Name":"C4","Min_Value":60,"Max_Value":64.9},{"Grade_Name":"C5","Min_Value":55,"Max_Value":59.9},{"Grade_Name":"C6","Min_Value":50,"Max_Value":54.9},{"Grade_Name":"D7","Min_Value":45,"Max_Value":49.9},{"Grade_Name":"E8","Min_Value":40,"Max_Value":44.9},{"Grade_Name":"F9","Min_Value":0,"Max_Value":39.9}],"Rating Keys":[{"Rating_Name":"Skill","Min_Value":2,"Max_Value":5},{"Rating_Name":"Sports","Min_Value":2,"Max_Value":5},{"Rating_Name":"Curricular","Min_Value":2,"Max_Value":5},{"Rating_Name":"Behaviour","Min_Value":2,"Max_Value":5}],"School Info":[{"School_Name":"SAMUEL ADEGBITE ANGLICAN COLLEGE","Extra_Info":"(A Day-Co-educational Institution Of The Anglican Diocese Of Lagos West)","Address":"St. Peters Anglican Church, Ikotun Road, Idumu, Lagos.","Title":"SECONDARY SCHOOL STUDENT'S INTERNAL ACADEMIC REPORT SHEET","Watermark":"SAMUEL ADEGBITE ANGLICAN COLLEGE"},{"Address":null,"Title":null},{"Address":null,"Title":null},{"Address":null,"Title":null}],"ID":[{"Id":"DON'T CHANGE!!!","Start_Row":null},{"Id":"File ID","Start_Row":"Start Row"},{"Id":"Keys","Start_Row":1},{"Id":null}]}],"pool":[{"Principal Comment":[{"Pool":"Good performance, keep it up"},{"Pool":"A wonderful performance, keep it up"},{"Pool":"A highly impressive result, keep it up"},{"Pool":"Good result but you need to improve in your weak area(s)"},{"Pool":"Average result, there is still room for improvement"},{"Pool":"Average result, you can still do better"},{"Pool":"A fair result, you really need to improve in your weak subject(s)"},{"Pool":"Weak performance, you really need to improve in your weak subjects"},{"Pool":"A very good performance, keep it up"},{"Pool":"Beautiful performance, keep the flag flying"},{"Pool":"Weak result, you need to concentrate more on your studies"},{"Pool":"Excellent performance, keep it up"},{"Pool":"A brilliant performance, keep it up"},{"Pool":"Good result, there is room for improvement"},{"Pool":"An average result, you really need to study harder"},{"Pool":"A very good result, weldone."},{"Pool":"A beautiful result, keep it up"},{"Pool":"An impressive result, keep it up"},{"Pool":"A very good performance, keep the flag flying"},{"Pool":"An average result, there is still room for improvement,"},{"Pool":"A fair result, you can still do better."},{"Pool":"A weak result, there is room for you to work harder."},{"Pool":"A very weak performance, you seriously need to work harder."},{"Pool":"Poor performance, your need to work on your weak subjects"},{"Pool":"Excellent performance, keep it up."},{"Pool":null}],"Teacher Comment":[{"Pool":"Always willing to take up responsiblities"},{"Pool":"Very friendly and humorous"},{"Pool":"A highly talented student"},{"Pool":"Very hardworking and conscioustious"},{"Pool":"Friendly but needs to put in more efforts"},{"Pool":"Easy-going and very neat"},{"Pool":"Always punctual to class and all other activities"},{"Pool":"Highly dependable and trustworthy"},{"Pool":"Very reliable and hardworking"},{"Pool":"Active and always willing to take up responsibilities"},{"Pool":"Friendly but needs to pay more attention to his/her studies"},{"Pool":"Friendly but needs to settle down for serious work"},{"Pool":"Easy-going but needs to be more punctual"},{"Pool":"Very studious and always attentive in class"},{"Pool":"Very reliable and willing to assist others"},{"Pool":"Highly cooperative and dependable"},{"Pool":"Friendly but needs to be less playful"},{"Pool":"Friendly but restless, needs to always observe siesta"},{"Pool":"Highly organized and conscientious"},{"Pool":"Friendly and highly willing to learn"},{"Pool":"A consistent and handworking student"},{"Pool":"Very reliable and ready to take to correction"},{"Pool":null},{"Pool":null},{"Pool":null}],"Skills":[{"Pool":"Musical Instrument"},{"Pool":"Drawing and Painting"},{"Pool":"Craft"},{"Pool":"Handling of Workshop Tools"},{"Pool":"Handwriting/Fluency"}],"Sports":[{"Pool":"Indoor Games"},{"Pool":"Ball Games"},{"Pool":"Combative Games"},{"Pool":"Track/Throws"},{"Pool":"Gymnastics"}],"Curricular":[{"Pool":"JETS"},{"Pool":"Young Farmers Club"},{"Pool":"Literary & Debating"},{"Pool":"Home Maker"},{"Pool":"Drama/Culture/Music/Craft"},{"Pool":"Voluntary Service Org."},{"Pool":"Others"}],"Behaviour":[{"Pool":"Reliability"},{"Pool":"Neatness"},{"Pool":"Politeness"},{"Pool":"Honesty"},{"Pool":"Initiative/Creativity"},{"Pool":"Leadership Role"},{"Pool":"Level of Spiritual Dev.","Override":3},{"Pool":"Spirit of Co-operation"}],"ID":[{"Id":"DON'T CHANGE!!!","Start_Row":null},{"Id":"File ID","Start_Row":"Start Row"},{"Id":"Pool","Start_Row":1}]}],"logo":null,"images":["stunt toy car.jpg"],"errors":[]}
I tried your code with your data and it is -- as expected -- iterating over all 27 items. But because some condition isn't met, you are setting innError = true for the 22nd record and never setting it back to false.
So all items after that will be treated like they have an error too (which probably makes you believe they are not iterated). Just try adding a console.log(j) as first statement in your inner loop. And you will see, it will printout all values from 0 to 26 ...

Rust is skipping over for loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am fairly new to rust and am just trying to make a hangman game to help me learn the language. I have made a for loop that checks to see if the character I entered is in a vector of all the past characters I have guessed. But when running through it just keeps asking for the letter again, after going through the debugger it juts completely skips over the for loop completely.
I am using vscode with lldb to debug.
Can anyone lend a hand to either explain to me or help me work out why it isn't working.
use rand::random;
fn take_input(pre_guessed: &mut std::vec::Vec<char>) -> char{
let mut run = true;
print!("Enter letter: ");
let mut temp_guess = String::new();
let guess_char = match std::io::stdin().read_line(&mut temp_guess){
Ok(_) => temp_guess.chars().next().expect("Could not convert guess to char"),
Err(_) => '>'
};
println!();
for i in pre_guessed.iter(){ // THIS IS THE FOR LOOP THAT IS SKIPPED OVER
if *i == guess_char{
run = false;
}
}
if run == false{
pre_guessed.push(guess_char);
guess_char
} else {
take_input(pre_guessed)
}
}
fn get_word() -> String {
// goes to a text file and gets a word
}
fn check_correct(guessed_vec: &std::vec::Vec<char>) -> bool{
let mut complete = true;
for i in guessed_vec.iter(){
if *i == '-'{
complete = false;
}
}
complete
}
fn main() {
let word_to_guess = get_word();
println!("{}", word_to_guess);
let mut encoded_word = vec!['-'; word_to_guess.len()];
let mut guessed = false;
let mut guessed_letters: std::vec::Vec<char> = Vec::new();
let mut wrong_letters: std::vec::Vec<char> = Vec::new();
while guessed == false{
println!("Guessed letters: {:?}", wrong_letters);
for i in encoded_word.iter(){
print!("{}", i);
}
println!();
let guess = take_input(&mut guessed_letters);
let mut temp_count = 0;
let mut temp_match = false;
for i in word_to_guess.chars(){
if guess == i{
encoded_word[temp_count] = i;
temp_match = true
}
temp_count += 1;
}
if temp_match == false{
wrong_letters.push(guess);
}
guessed = check_correct(&guessed_letters)
}
}
guessed_letters starts empty.
The only thing that adds to it is pre_guessed.push(guess_char) when run == false.
run starts true.
The only thing that sets it to false is when *i == guess_char for any element i of pre_guessed (which is guessed_letters).
guessed_letters can only become nonempty when run is false, and run can only become false when guessed_letters is nonempty.
It looks like you meant:
if run { // no == false
pre_guessed.push(guess_char);
guess_char
} else {
take_input(pre_guessed)
}

Remove spaces between digits in a string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
original: "I have the M5 2 0 0 and I like it"
intended: "I have the M5200 and I like it"
How would you achieve this as an algoritm or give a code example?
I believe this question is valid in many programming languages so I won't ask it for a specific one.
C# sample (replacing with regular expression):
String original = "I have the M5 2 0 0 and I like it";
String result = Regex.Replace(original, #"\d( *\d*)*\d",
(MatchEvaluator) (match => {
return match.Value.Replace(" ", "");
}));
For languages that don't have regular expressions: iterate through the text. If the current letter is a space and the letters surrounding it are digits, then don't add it to the result.
Sample Python implementation:
text = "I have the M5 2 0 0 and I like it"
result = []
for i in range(len(text)):
if i > 0 and i < len(text)-1:
prev = text[i-1]
next = text[i+1]
if text[i] == ' ' and prev.isdigit() and next.isdigit():
continue
result.append(text[i])
print "".join(result)
Result:
I have the M5200 and I like it
For python you can use:
import re
line = 'I have the M5 2 0 0 and I like it'
line = re.sub(r'(\d+)\s+(?=\d)',r'\1', line)
print(line)
where \1 stands for the first group \d+ and the second group will not be replaced ?=\d because is only used for matching.
Result: I have the M5200 and I like it
A Java solution:
public static void main(String[] args) {
String input = "I have the M5 231 0 0 and I like it";
String output = "";
if ( input.length() > 0 ) {
output += input.charAt(0);
}
for ( int i = 1 ; i < input.length()-1 ; i++ ) {
if ( Character.isDigit(input.charAt(i-1)) &&
Character.isDigit(input.charAt(i+1)) &&
Character.isSpaceChar(input.charAt(i)) ) {
continue;
} else {
output += input.charAt(i);
}
}
if ( input.length() > 1 ) {
output += input.charAt(input.length() - 1);
}
System.out.println(output);
}

Making a game with 4 possible answer buttons

I am new to ActionScript-3 and I am attempting to make a game to learn more.
For every picture that is displayed I want there to be 4 choices (buttons) and only one of them to be the correct one. But how can I make it so that the text from the buttons will be random.
As you can see I've made it so the 4th button is always the correct answer. I don't want to make all this thing for every picture that is displayed...to much pointless code.
Can anybody help me? If you need extra information I will gladly provide it.
var k:int;
for(k=1;k<=3;k++)
{
GAME.variante.buttonMode=true;
GAME.variante.addEventListener(MouseEvent.MOUSE_OVER,mouse_over_variante);
GAME.variante.addEventListener(MouseEvent.MOUSE_OUT,mouse_out_variante);
GAME.variante.varianta_corecta.addEventListener(MouseEvent.CLICK,variante);
GAME.variante.varianta_gresita1.addEventListener(MouseEvent.CLICK,variante_gresiteunu);
GAME.variante.varianta_gresita2.addEventListener(MouseEvent.CLICK,variante_gresitedoi);
GAME.variante.varianta_gresita3.addEventListener(MouseEvent.CLICK,variante_gresitetrei);
GAME.varianta1.text = "Cameleon";
GAME.varianta2.text = "Snake";
GAME.varianta3.text = "Frog";
GAME.varianta4.text = "Snail";
function variante_gresiteunu(e:MouseEvent){
if (varianta_gresita_apasata1 == 1){
totalScore -= score_variante_gresite;
GAME.text1.text = totalScore;
varianta_gresita_apasata1 = 2;
}
}
function variante_gresitedoi(e:MouseEvent){
if (varianta_gresita_apasata2 == 1){
totalScore -= score_variante_gresite;
GAME.text1.text = totalScore;
varianta_gresita_apasata2 = 2;
}
}
function variante_gresitetrei(e:MouseEvent){
if (varianta_gresita_apasata3 == 1){
totalScore -= score_variante_gresite;
GAME.text1.text = totalScore;
varianta_gresita_apasata3 = 2;
}
}
}
GAME.extra_points.visible = false;
function variante (e:MouseEvent) {
if (GAME.stichere.sticker1.currentFrame == (1)){
GAME.extra_points.visible = true;
GAME.extra_points.plus_ten1.gotoAndPlay(1);
}
//go to great job screen
GAME.greatJob.stars.gotoAndPlay(1);
GAME.greatJob.visible = true;
}
function mouse_over_variante (e:MouseEvent) {
trace(e.target.name);
e.target.gotoAndPlay(1);
}
function mouse_out_variante (e:MouseEvent) {
e.target.gotoAndStop(1);
}
You like to have 4 images and they will be tested right?
The text below the images will be randomness. I saw your code and I
confess I was confused. I made a different one.
I undestand that this code is a little diferent of what you ask, but i think it will > give you some new ideas and help you on your app...
//start button added on the sceen named f3toc. I give a function name for him f3roll.
f3toc.addEventListener(MouseEvent.CLICK,f3roll);
function f3roll(e:MouseEvent):void{
//creating variables for the picture.
var bola:Number
var quadrado:Number
var pentagono:Number
//Here is just a randomization code, you can change it to the what you want to use after the =
bola = Math.ceil(Math.random() * 10);
pentagono = Math.ceil(Math.random() * 10);
f3res1_txt.text = String (bola + 8 + 8);
f3res2_txt.text = String(bola - 1 + bola);
f3res3_txt.text = String (pentagono + 10 - bola);
//converting number to string so we can put tem into the text fields.
var pentagonotring:String = pentagono.toString();
var bolastring:String = bola.toString();
//function to check wen the name is correct. each wrong do nothing and every correct add 1 to a variable, in the end wen this variable reach 3 it does something.
f3check_bnt.addEventListener (MouseEvent.CLICK, f3check);
function f3check (e:MouseEvent):void{
if (f3inp2_txt.text == pentagonotring){
f3ver_ext2.text = "Correct"
} else {f3ver_ext2.text = "Wrong";}
if (f3inp1_txt.text == bolastring){
f3ver_ext1.text = "Correct"
}else {f3ver_ext1.text = "Wrong";}
// function to check wen the variable pass reach 3
pass = 0;
if (f3ver_ext1.text == "Correct"){
pass++
}
if (f3ver_ext2.text == "Correct"){
pass++
if (pass == 3){
nextFrame();
}}}}

For loop construction and code complexity [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
My group is having some discussion and strong feelings about for loop construction.
I have favored loops like:
size_t x;
for (x = 0; x < LIMIT; ++x) {
if (something) {
break;
}
...
}
// If we found what we're looking for, process it.
if (x < LIMIT) {
...
}
But others seem to prefer a Boolean flag like:
size_t x;
bool found = false;
for (x = 0; x < LIMIT && !found; ++x) {
if (something) {
found = true;
}
else {
...
}
}
// If we found what we're looking for, process it.
if (found) {
...
}
(And, where the language allows, using "for (int x = 0; ...".)
The first style has one less variable to keep track of and a simpler loop header. Albeit at the cost of "overloading" the loop control variable and (some would complain), the use of break.
The second style has clearly defined roles for the variables but a more complex loop condition and loop body (either an else, or a continue after found is set, or a "if (!found)" in the balance of the loop).
I think that the first style wins on code complexity. I'm looking for opinions from a broader audience. Pointers to actual research on which is easier to read and maintain would be even better. "It doesn't matter, take it out of your standard" is a fine answer, too.
OTOH, this may be the wrong question. I'm beginning to think that the right rule is "if you have to break out of a for, it's really a while."
bool found = false;
x = 0;
while (!found && x < LIMIT) {
if (something) {
found = true;
...handle the thing...
}
else {
...
}
++x;
}
Does what the first two examples do but in fewer lines. It does divide the initialization, test, and increment of x across three lines, though.
I'd actually dare to suggest consideration of GOTO to break out of loops in such cases:
for (size_t x = 0; x < LIMIT && !found; ++x) {
if (something)
goto found;
else {
...
}
}
// not found
...
return;
found:
...
return;
I consider this form to be both succint and readable. It may do some good in many simple cases (say, when there is no common processing in this function, in both found/unfound cases).
And about the general frowning goto receives, I find it to be a common misinterpretation of Dijkstra's original claims: his arguments favoured structured loop clauses, as for or while, over a primitive loop-via-goto, that still had a lot of presence circa 1968. Even the almighty Knuth eventualy says -
The new morality that I propose may
perhaps be stated thus: "Certain go to
statements which arise in connection with
well-understood transformations are acceptable, provided that the program documentation explains what the transformation was."
Others here occasionaly think the same.
While I disagree that an extra else really makes the 2nd more complicated, I think it's primarily a matter of aesthetics and keeping to your standard.
Personally, I have a probably irrational dislike of breaks and continues, so I'm MUCH more likely to use the found variable.
Also, note that you CAN add the found variable to the 1st implementation and do
if(something)
{
found = true;
break;
}
if you want to avoid the variable overloading problem at the expense of the extra variable, but still want the simple loop terminator...
The former example duplicates the x < LIMIT condition, whereas the latter doesn't.
With the former, if you want to change that condition, you have to remember to do it in two places.
I would prefer a different one altogether:
for (int x = 0; x < LIMIT; ++x) {
if (something) {
// If we found what we're looking for, process it.
...
break;
}
...
}
It seems you have not any trouble you mention about one or the other... ;-)
no duplication of condition, or readability problem
no additional variable
I don't have any references to hand (-1! -1!), but I seem to recall that having multiple exit points (from a function, from a loop) has been shown to cause issues with maintainability (I used to know someone who wrote code for the UK military and it was Verboten to do so). But more importantly, as RichieHindle points out, having a duplicate condition is a Bad Thing, it cries out for introducing bugs by changing one and not the other.
If you weren't using the condition later, I wouldn't be bothered either way. Since you are, the second is the way to go.
This sort of argument has been fought out here before (probably many times) such as in this question.
There are those that will argue that purity of code is all-important and they'll complain bitterly that your first option doesn't have identical post-conditions for all cases.
What I would answer is "Twaddle!". I'm a pragmatist, not a purist. I'm as against too much spaghetti code as much as the next engineer but some of the hideous terminating conditions I've seen in for loops are far worse than using a couple of breaks within your loop.
I will always go for readability of code over "purity" simply because I have to maintain it.
This looks like a place for a while loop. For loops are Syntactic Sugar on top of a While loop anyway. The general rule is that if you have to break out of a For loop, then use a While loop instead.
package com.company;
import java.io.*;
import java.util.Scanner;
public class Main {
// "line.separator" is a system property that is a platform independent and it is one way
// of getting a newline from your environment.
private static String NEWLINE = System.getProperty("line.separator");
public static void main(String[] args) {
// write your code here
boolean itsdone = false;
String userInputFileName;
String FirstName = null;
String LastName = null;
String user_junk;
String userOutputFileName;
String outString;
int Age = -1;
int rint = 0;
int myMAX = 100;
int MyArr2[] = new int[myMAX];
int itemCount = 0;
double average = 0;
double total = 0;
boolean ageDone = false;
Scanner inScan = new Scanner(System.in);
System.out.println("Enter First Name");
FirstName = inScan.next();
System.out.println("Enter Last Name");
LastName = inScan.next();
ageDone = false;
while (!ageDone) {
System.out.println("Enter Your Age");
if (inScan.hasNextInt()) {
Age = inScan.nextInt();
System.out.println(FirstName + " " + LastName + " " + "is " + Age + " Years old");
ageDone = true;
} else {
System.out.println("Your Age Needs to Have an Integer Value... Enter an Integer Value");
user_junk = inScan.next();
ageDone = false;
}
}
try {
File outputFile = new File("firstOutFile.txt");
if (outputFile.createNewFile()){
System.out.println("firstOutFile.txt was created"); // if file was created
}
else {
System.out.println("firstOutFile.txt existed and is being overwritten."); // if file had already existed
}
// --------------------------------
// If the file creation of access permissions to write into it
// are incorrect the program throws an exception
//
if ((outputFile.isFile()|| outputFile.canWrite())){
BufferedWriter fileOut = new BufferedWriter(new FileWriter(outputFile));
fileOut.write("==================================================================");
fileOut.write(NEWLINE + NEWLINE +" You Information is..." + NEWLINE + NEWLINE);
fileOut.write(NEWLINE + FirstName + " " + LastName + " " + Age + NEWLINE);
fileOut.write("==================================================================");
fileOut.close();
}
else {
throw new IOException();
}
} // end of try
catch (IOException e) { // in case for some reason the output file could not be created
System.err.format("IOException: %s%n", e);
e.printStackTrace();
}
} // end main method
}

Resources