Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,156,317 members, 7,829,764 topics. Date: Thursday, 16 May 2024 at 11:28 AM

Please Have You Seen This Algorithm Question - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Please Have You Seen This Algorithm Question (692 Views)

Thread For Nairaland Algorithm Questions / I Need A Programmer To Develop This Algorithm Into App / This Algorithm Can Create 3D Animations From A Single Still Image (2) (3) (4)

(1) (Reply) (Go Down)

Please Have You Seen This Algorithm Question by cbrass(m): 4:06pm On Oct 02, 2021


Write a production-ready function in PHP that sums the numbers in a file and outputs details of the results. The function will receive as input the path to a single file. Each line of the file will contain either a number or a relative path to another file. For each file processed, output the file path and the sum of all of the numbers contained both directly in the file and in any of the sub files listed in the file (and their sub files, etc).



For example, if file A.txt contains:

3
19
B.txt
50


And file B.txt contains:

C.txt
27


And file C.txt contains:

10
2


Then the output of passing A.txt to the function might look something like this:

A.txt - 111
B.txt - 39
C.txt - 12


I have tried everything I can but it only shows result for the first file
Re: Please Have You Seen This Algorithm Question by stanliwise(m): 6:11pm On Oct 02, 2021
cbrass:


I have tried everything I can but it only shows result for the first file
Share your code.
It’s straight forward
Re: Please Have You Seen This Algorithm Question by Bigshoe2028: 6:35pm On Oct 02, 2021
While loop is ur friend here to save memory
Re: Please Have You Seen This Algorithm Question by fnep2smooth(m): 10:49pm On Oct 02, 2021
Are you looking for job in Google or Facebook. If na naija company expect to be pay 30k with a intern tag.
Re: Please Have You Seen This Algorithm Question by cbrass(m): 11:40pm On Oct 02, 2021
stanliwise:

Share your code.
It’s straight forward


function fileSum($file) {
return array_sum(array_map(function($val) {
$val = trim($val);
if (is_numeric($val)) {
return $val;
}
return fileSum($val);
}, file($file)));
}

echo fileSum('a.txt');

This code loops through all the files and sums them for just file A.
instead of breaking it by file just as the example given
Re: Please Have You Seen This Algorithm Question by cbrass(m): 11:41pm On Oct 02, 2021
fnep2smooth:
Are you looking for job in Google or Facebook. If na naija company expect to be pay 30k with a intern tag.

grin grin grin grin this made my day after serious coding to solve the problem
Re: Please Have You Seen This Algorithm Question by stanliwise(m): 8:11am On Oct 03, 2021
cbrass:




This code loops through all the files and sums them for just file A.
instead of breaking it by file just as the example given
I am not clear of your code and looking at it I don't see how it would solve your problems.

The only thing to consider now is that your questions should not have what we call circular-reference.

So no file now must link to another file that link back to it self. you need a code to do that checking. that been said a simple pseudocode should do.

Please flip your phone horizontally to see the codes properly.


#check for circular reference and ensure none exist

#this stack will be a global variable to track all opened file and ensure it was not opened twice.
$stack = [];

find_sum($file_path){
global $stack;
$sum = 0;
$values = []
fill $values with all the lines from $file_path

foreach($values as $a_value){

if (it is a number) {
$sum += $a_value;
}
elseif( it is a file_path) {
#check for circular references
if($file_path is in $stack){
die('Error: Circular Reference Encountered');
} else {
#add the file path to stack as already opened
$stack[] = $a_value;

#use the recursion concept
$sum += file_sum($a_value);
}
}
}

return $sum;
}
Re: Please Have You Seen This Algorithm Question by Iambro(m): 4:18pm On Oct 03, 2021
Create a recursive function that read the files or check if it is a directory then reads its files etc.
Re: Please Have You Seen This Algorithm Question by cbrass(m): 8:16pm On Oct 03, 2021
Iambro:
Create a recursive function that read the files or check if it is a directory then reads its files etc.

I have done that, it didn't give the desired answer..one thing is this question looks so easy but when you start to code then you will get hooked somewhere
Re: Please Have You Seen This Algorithm Question by cbrass(m): 8:20pm On Oct 03, 2021
stanliwise:

I am not clear of your code and looking at it I don't see how it would solve your problems.

The only thing to consider now is that your questions should not have what we call circular-reference.

So no file now must link to another file that link back to it self. you need a code to do that checking. that been said a simple pseudocode should do.

Please flip your phone horizontally to see the codes properly.


#check for circular reference and ensure none exist

#this stack will be a global variable to track all opened file and ensure it was not opened twice.
$stack = [];

find_sum($file_path){
global $stack;
$sum = 0;
$values = []
fill $values with all the lines from $file_path

foreach($values as $a_value){

if (it is a number) {
$sum += $a_value;
}
elseif( it is a file_path) {
#check for circular references
if($file_path is in $stack){
die('Error: Circular Reference Encountered');
} else {
#add the file path to stack as already opened
$stack[] = $a_value;

#use the recursion concept
$sum += file_sum($a_value);
}
}
}

return $sum;
}

I did something similar to this before, when i get home i will try yours. Thanks a lot i really appreciate it
Re: Please Have You Seen This Algorithm Question by cbrass(m): 9:06pm On Oct 03, 2021
stanliwise:

I am not clear of your code and looking at it I don't see how it would solve your problems.

The only thing to consider now is that your questions should not have what we call circular-reference.

So no file now must link to another file that link back to it self. you need a code to do that checking. that been said a simple pseudocode should do.

Please flip your phone horizontally to see the codes properly.


#check for circular reference and ensure none exist

it gives thesame answer as this code I posted before

#this stack will be a global variable to track all opened file and ensure it was not opened twice.
$stack = [];

find_sum($file_path){
global $stack;
$sum = 0;
$values = []
fill $values with all the lines from $file_path

foreach($values as $a_value){

if (it is a number) {
$sum += $a_value;
}
elseif( it is a file_path) {
#check for circular references
if($file_path is in $stack){
die('Error: Circular Reference Encountered');
} else {
#add the file path to stack as already opened
$stack[] = $a_value;

#use the recursion concept
$sum += file_sum($a_value);
}
}
}

return $sum;
}
Re: Please Have You Seen This Algorithm Question by stanliwise(m): 10:18pm On Oct 03, 2021
[quote author=cbrass post=106417200][/quote]
You’re not checking for circular references and I didn’t see where you read the files line by line, you were returning simple recursion without reading the lines
Re: Please Have You Seen This Algorithm Question by SapphireYj: 1:30pm On Oct 04, 2021
Implemented in nodejs. Tested and its working fine as long as A.txt, B.txt, and C.txt are in same directory with this file. If you know javascript, its just converting this code to php.

const fs = require('fs')

const printRecursively = (path)=>{
let result = 0
try {
const data = fs.readFileSync(path)
let newfilePath
let dt = data.toString().split('\r\n')

dt.forEach(str=>{
let dtNum = +str

if(!isNaN(dtNum)){
result+=dtNum
}
else{
newfilePath = str
}
})


if(newfilePath){
result = result + printRecursively(newfilePath)
console.log(`${path} - ${result}`)

}
else{
console.log(`${path} - ${result}`)

}
return result
} catch (err) {
return console.log(err.message)
}
}

printRecursively('A.txt')
Re: Please Have You Seen This Algorithm Question by cbrass(m): 3:27pm On Oct 04, 2021
[quote author=SapphireYj post=106435278]Implemented in nodejs. Tested and its working fine as long as A.txt, B.txt, and C.txt are in same directory with this file. If you know javascript, its just converting this code to php.

const fs = require('fs')

const printRecursively = (path)=>{
let result = 0
try {
const data = fs.readFileSync(path)
let newfilePath
let dt = data.toString().split('\r\n')

dt.forEach(str=>{
let dtNum = +str

if(!isNaN(dtNum)){
result+=dtNum
}
else{
newfilePath = str
}
})


if(newfilePath){
result = result + printRecursively(newfilePath)
console.log(`${path} - ${result}`)

}
else{
console.log(`${path} - ${result}`)

}
return result
} catch (err) {
return console.log(err.message)
}
}

printRecursively('A.txt')[/quote

I think i have seen something similar before. my javascript skill is not strong. so converting to PHP is really hard
Re: Please Have You Seen This Algorithm Question by cbrass(m): 3:31pm On Oct 04, 2021
SapphireYj:
Implemented in nodejs. Tested and its working fine as long as A.txt, B.txt, and C.txt are in same directory with this file. If you know javascript, its just converting this code to php.

const fs = require('fs')

const printRecursively = (path)=>{
let result = 0
try {
const data = fs.readFileSync(path)
let newfilePath
let dt = data.toString().split('\r\n')

dt.forEach(str=>{
let dtNum = +str

if(!isNaN(dtNum)){
result+=dtNum
}
else{
newfilePath = str
}
})


if(newfilePath){
result = result + printRecursively(newfilePath)
console.log(`${path} - ${result}`)

}
else{
console.log(`${path} - ${result}`)

}
return result
} catch (err) {
return console.log(err.message)
}
}

printRecursively('A.txt')

I will compare your solution with mine ,i can sum the files independently though .
i sent you a DM SapphireYj

(1) (Reply)

Social Chat App, Dating App, Dating Website, Livestreaming App Developed / Cyber Security Full Course And Certification / Why Will NL Take The Food Cooked By Chefs To Front Page, But Never Tech Projects

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 31
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.