Why am I getting an error instead of expected output
let marks = {
harry: 44,
shg: 544,
ccc: 44,
gugugu: 99
}
for (let i = 0; i < object.keys(marks).length; i++) {
console.log("marks of " + object.keys(marks)[i] + "are" + marks[object.keys(marks)[i]])
}
ReferenceError: object is not defined
at Object.<anonymous> (/home/runner/practice-set-on-loopsandfunctions-course-12/index.js:7:21)
at Module._compile (node:internal/modules/cjs/loader:1155:14)
Expected output
marks of harry are 44
marks of shg are 544
marks of ccc are 44
marks of gugugu are 99
Use capital Object
let marks = {
harry: 44,
shg: 544,
ccc: 44,
gugugu: 99
}
for (let i = 0; i < Object.keys(marks).length; i++) {
console.log("marks of " + Object.keys(marks)[i] + "are" + marks[Object.keys(marks)[i]])
}
There are cleaner loops if you'd like for(let key in marks) then you don't have to transform keys to a list each time
let marks = {
harry: 44,
shg: 544,
ccc: 44,
gugugu: 99
}
for (let key in marks) {
console.log("marks of " + key + "are" + marks[key])
}
Related
i have that needs me to make a function that counts the occurrences of each number in an array [2,5,6,6,8,4,2,5,2] and print it like this
2 -> 3 times
6 -> 2 times and so on
I did it before but it was to count the occurrences of one number not all of them so can anyone help ... Thanks in advance
to update this is the code I used to count the occurrences of one number
int countTwo(List<int> arr, int value) {
int counter = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == value) {
counter++;
}
}
return counter;
}
void main() {
List<int> arr = [5, 6, 15, 2, 8, 2, 38, 2];
int x = countTwo(arr, 2);
print(x);
}
You can create a set from list to get unique int.
final data = [2, 5, 6, 6, 8, 4, 2, 5, 2];
final dataSet = data.toSet();
int counter(int number) {
final int counter = data.where((element) => element == number).length; //you can use for loop here too
return counter;
}
for (int i = 0; i < dataSet.length; i++) {
print(
"number ${dataSet.elementAt(i)} -> ${counter(dataSet.elementAt(i))} times");
}
And with your method just do
final data = [2, 5, 6, 6, 8, 4, 2, 5, 2];
final dataSet = data.toSet();
for (int i = 0; i < dataSet.length; i++) {
final checkNUmber = dataSet.elementAt(i);
print("number $checkNUmber-> ${countTwo(data, checkNUmber)} times");
}
Result
number 2 -> 3 times
number 5 -> 2 times
number 6 -> 2 times
number 8 -> 1 times
number 4 -> 1 times
I'd use a map to collect the count:
var count = <int, int>{};
for (var n in data) {
count[n] = (count[n] ?? 0) + 1;
}
After that, you have all the individual elements, and the number of times it occurred:
for (var n in count.keys) {
print("$n: ${count[n]} times");
}
I am studying programming concepts in my uni as a freshman. I am having a trouble with my works.
var array = [13,1,2,3,4,5,6,7,8,9,10,11];
function listAll(){
var msg1 = "List of all values in the array: " + "<br>";
for(var pos = 0; pos < array.length; pos++){
msg1 = msg1 + array[pos]+ " " ;
}
document.getElementById("msg").innerHTML = msg1 ;
}
function performStats(){
var count=0;
var total=0;
var msg2 = "Total number of the values in the array: " ;
for(var index = 0; index < array.length; index++){
total = total + array[index];
if(array[index] < 10)
count++;
}
msg2 = msg2 + array.length;
msg2 = msg2 + "<br/>" + "The sum of all values in the array: "+ total + "<br/>" ;
msg2 = msg2 + "The count of all values below 10 in the array: " + count;
msg2 = msg1.concat(msg2);
document.getElementById("msg").innerHTML= msg2;
}
function init(){
document.getElementById("display").onclick= listAll;
document.getElementById("stats").onclick= performStats;
}
window.onload = init;
Question: Why my msg2 = msg1.concat(msg2) is not working? and how to fix it?
This is because variables are scoped, You can not access it out side of its own function.
You can however change them from within another function.
A quick messy way is by making the variables global or calling another function. or even a self invoking function.
(function() {
var array = [13,1,2,3,4,5,6,7,8,9,10,11];
var msg1 = "List of all values in the array: <br>";
var msg2 = "Total number of the values2 in the array: <br>" ;
function listAll(){
// First, no need to do this
// var msg1 = "List of all values in the array: " + "<br>";
// Another way to do a foreach on an array, I find it neater.
// array.forEach(item => {
// msg1 = msg1 + item + " ";
// });
for(var pos = 0; pos < array.length; pos++){
msg1 = msg1 + array[pos]+ " " ;
}
document.getElementById("msg").innerHTML = msg1 ;
}
function performStats(){
var count=0;
var total=0;
for(var index = 0; index < array.length; index++){
total = total + array[index];
if(array[index] < 10)
count++;
}
msg2 = msg2 + array.length;
msg2 = msg2 + "<br/>" + "The sum of all values in the array: "+ total + "<br/>" ;
msg2 = msg2 + "The count of all values below 10 in the array: " + count;
msg2 = msg1.concat(msg2);
document.getElementById("msg").innerHTML= msg2;
}
function init(){
document.getElementById("display").onclick= listAll;
document.getElementById("stats").onclick= performStats;
}
window.onload = init;
})();
Why this code dosen't work? How can I improve it? I think function should be void type.
The function transposeMatrix() that takes as an argument a 4 × 5 matrix and a 5 × 4 matrix.
The function transpose the 4 × 5 matrix and store the results in the 5 × 4 matrix.
void transposeMatrix(int a, int b, int N[a][b], int M[b][a]) // get 2 arrays
{
for (int i = 0; i < a; i++) { // go through arrays
for (int j = 0; j < b; j++)
M[i][c] = N[i][c];
}
}
int main(void)
{
int a = 4, b = 5;
int M[b][a] = // fist array
{
{ 0, 10, 22, 30 },
{ 4, 50, 6, 77 },
{ 80, 9, 1000, 111 },
{ 12, 130, 14, 15 },
{ 16, 17, 102, 103 }
};
int N[a][b] = // second array
{
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 }
};
printf("array M\n");
for (int i = 0; i < a; i++) {
for (int c = 0; c < b; i++)
printf("%4i", M[i][c]);
printf("\n");
}
transposeMatrix(a, b, N, M); // call function
printf("array M after transposeMatrix function/n ");
for (int i = 0; i < a; i++) {
for (int c = 0; c < b; i++)
printf("%4i", M[i][c]);
printf("\n");
}
return 0;
}
Everytime we take transpose we use atranspose[i][j]=a[j][i].
Whereas in ur code u are using M[i][c] = N[i][c]
which is wrong.
#include<iostream>
using namespace std;
int main()
{
int matrix[5][5],transpose_matrix[5][5];
int i,j,rows,cols;
// Taking Input In Array
cout<<"Enter Number of ROWS :";
cin>>rows;
cout<<"Enter Number Of COLS :";
cin>>cols;
for( i=0;i<rows;i++){
for( j=0;j<cols;j++)
{
cin>>matrix[i][j];
}
}
cout<<"\n Matrix You Entered\n";
for( i=0;i<rows;i++){
for( j=0;j<cols;j++)
{
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
// Calculating Transpose of Matrix
cout<<"\n\n\nTranspose of Entered Matrix\n";
for( i=0;i<rows;i++) {
for( j=0;j<cols;j++)
{
transpose_matrix[j][i]=matrix[i][j];
}
cout<<endl;
}
//Displaying Final Resultant Array
for( i=0;i<cols;i++) {
for( j=0;j<rows;j++)
{
cout<<transpose_matrix[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
I need help about this function :
var ListFruits = Enumerable.From(data)
.GroupBy("$.Fruits", "", "d,v => { Fruits:d,NumberFruits:v.Sum('$.NumberFruits|0')}")
.Select(" $.Fruits+ ': ' + $.NumberFruits")
.ToArray();
// result is [apple: 2 , banana:5 , orange: 3]
I would like to have for each fruit the percent of the total
A function to do something like this (where total is the sum of all fruits) :
var ListFruits = Enumerable.From(data)
.GroupBy("$.Fruits", "", "d,v => { Fruits:d,NumberFruits:v.Sum('$.NumberFruits|0')}")
.Select(" $.Fruits+ ': ' + $.NumberFruits + 'is' + ($.NumberFruits/total)*100 ")
.ToArray();
// result is [apple: 2 is 20% , banana: 5 is 50% , orange: 3 is 30%]
Well, you'll have to calculate the total. Using the Let() function can help keep it clean.
var data = [
{ Fruit: 'apple', Count: 2 },
{ Fruit: 'banana', Count: 5 },
{ Fruit: 'orange', Count: 3 }
];
var query = Enumerable.From(data)
.Let(function (d) {
var total = d.Sum("$.Count");
return d.GroupBy("$.Fruit", "$.Count", function (f, g) {
var sum = g.Sum(),
percent = (sum / total) * 100;
return f + ': ' + sum + ' is ' + percent + '%';
});
})
.ToArray();
This yields the following array:
[
"apple: 2 is 20%",
"banana: 5 is 50%",
"orange: 3 is 30%"
]
private function restoreColumns( headerTextArray:ArrayCollection, widthArray:ArrayCollection):void {
dg.removeEventListener( IndexChangedEvent.HEADER_SHIFT, this.saveColumns );
for (var n:int = 0; n < headerTextArray.length; n++)
{
trace ( "Before: n: " + n + " WA: " + widthArray.getItemAt(n) + " DG: " + dg.columns[n].width);
// moveColumnTo(String(headerTextArray.getItemAt(n)), n);
// Problems copying for the last column
dg.columns[n].width = 0;
trace ( "Middle: n: " + n + " WA: " + widthArray.getItemAt(n) + " DG: " + dg.columns[n].width);
dg.columns[n].width = widthArray.getItemAt(n);
trace ( "After: n: " + n + " WA: " + widthArray.getItemAt(n) + " DG: " + dg.columns[n].width);
}
dg.addEventListener( IndexChangedEvent.HEADER_SHIFT, this.saveColumns );
}
Here is the trace output of the above code:
Before: n: 0 WA: 113 DG: 95
Middle: n: 0 WA: 113 DG: 20
After: n: 0 WA: 113 DG: 113
Before: n: 1 WA: 71 DG: 85
Middle: n: 1 WA: 71 DG: 20
After: n: 1 WA: 71 DG: 71
Before: n: 2 WA: 41 DG: 101
Middle: n: 2 WA: 41 DG: 101
After: n: 2 WA: 41 DG: 101
As you can see,
I am not able to set dg.columns[2].width to the desired value. [The problem occurs for the last column.]
I am also not able to set dg.columns[0].width = 0 before the middle trace.
I initially thought that the moveColumnTo() may have some thing to do with the problem but I am getting the problem even after commenting the call to the function.
What is wrong?
Here is the code that calls restoreColumns. [I just realized that I can edit my original post and add this.]
private function processQueryResponse(evt:DWSQLevent):void {
this.removeEventListener( IndexChangedEvent.HEADER_SHIFT, this.saveColumns );
this.removeEventListener( ResizeEvent.RESIZE, this.saveColumns );
var headerTextArray:ArrayCollection = new ArrayCollection();
var widthArray:ArrayCollection = new ArrayCollection();
if ( query.queryMessage == "SELECT" ) {
if (evt.dataRetrieved == true && query.queryData && query.queryData.length > 0 && query.queryData[0].length > 0 ) {
initialColumns = query.queryData[0];
var record:Object;
for (var n:Number = 0; n< this.columns.length; n++)
{
record = initialColumns.getItemAt(n);
headerTextArray.addItem(record.headertext);
widthArray.addItem( record.width );
}
restoreColumns( headerTextArray, widthArray);
haveColumnData = true;
} else if ( query.queryData.length > 0 && query.queryData[0].length == 0 ){
Alert.show( "Problems reading column data from database. Saved column order not restored." );
trace ("Select error / no rows "); // alert moving not done
}
} else {
}
this.addEventListener( IndexChangedEvent.HEADER_SHIFT, this.saveColumns );
// this.addEventListener( ResizeEvent.RESIZE, this.saveColumns );
}
it looks you should use n < widthArray.length instead of headerTextArray.length in your loop condition.