I am trying to add elements in an Array in Typescrypt with the push method, but it does not seem to work. the array remains empty. This is my code:
list: Array<int> = Array(10)
for(let x = 0; x <= 10; x++) {
list.push(x)
}
someone got the same problem?
in your case you can do :
list: Array<number> = [];
for(let x = 0; x <= 10; x++) {
list.push(x)
}
or
list: Array<number> = Array(10)
for(let x = 0; x <= 10; x++) {
list[x];
}
Explanation on your error :
Array(10) already creates an array with 10 "empty" elements.
if you use push on it, you will actually get your elements pushed, but in the 11th to the 20th position.
The 1st to the 10th ranks stay empty (and will return undefined if you try to get their value them)
So a few things to note:
There's no int type in TypeScript, since JavaScript has only one number type, the corresponding TypeScript type is called number.
You shouldn't use Array(n) (or the array constructor in general) to create an array, there's a lot of information about why that is (primarily, it creates what's called a sparse array, with a length property but no elements), but you should generally use [] to create a new array. All arrays in JavaScript are dynamic anyway, so the 10 you pass has no meaning.
You should never define variables without declaring them with const, let or var.
Combining the points above, here's how your code should look like for this case
const list: number[] /* or Array<number> */ = []
for(let x = 0; x <= 10; x++) {
list.push(x)
}
int type is not available in typescript use number instead of int
let list: Array<number> = Array(10);
for (let x = 0; x <= 10; x++) {
list.push(x)
}
above code is pushing the value to array but this will return
[undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
to fix this please change code to
let list: Array<number> = Array();
for (let x = 0; x <= 10; x++) {
list[x] = x;
}
this will return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Related
I have not been able to find examples that initialize two-dimension array at run-time.
This is code in perl; can anyone "translate" this code into C?
my #grid; # grid = 2D array
my $gr=0; # rows in grid
my $gc=0; # cols in grid
my #ct;
if( $ARGV[0] eq '5x5' ) {
$gr=5; $gc=5; # grid is all zeroes
#ct=(2,2,2,2,0);
}
if( $ARGV[0] eq '9x9' ) {
$gr=9; $gc=9; # grid is all zeroes
#ct=(2,3,4,2,3,5,3,5,3);
}
if( $ARGV[0] eq '6x10' ) {
$gr=6; $gc=10;
#grid = (
[0,8,0,0,0,9,3,5,6,7],
[6,0,0,5,0,7,0,0,1,0],
[5,0,2,0,4,1,0,0,0,0],
[0,0,0,0,2,0,0,0,0,1],
[0,0,0,1,0,0,0,0,0,0],
[1,5,0,4,2,6,8,0,0,0],
);
#ct=(14,41,15,29,26,33,32,27,32,21);
}
“Initialization” is just giving initial values to an object. To do this at run-time, you can do any of the following, among other possibilities:
Initialize in the definition, as shown in the question:
int myPoints[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9} };
Initialize with individual assignments:
myPoints[0][0] = 1;
myPoints[0][1] = 2;
myPoints[0][2] = 3;
myPoints[1][0] = 4;
myPoints[1][1] = 5;
myPoints[1][2] = 6;
myPoints[2][0] = 7;
myPoints[2][1] = 8;
myPoints[2][2] = 9;
Initialize with code that computes values:
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
myPoints[i][j] = 3*i + j + 1;
Copy from a compound literal:
memcpy(myPoints, (const int [3][3]) { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9} }, sizeof myPoints);
In the first case (initializing with the definition), if myPoints is a static object, the compiler is likely to store the values in the object file, to be loaded as part of program loading. If myPoints is an automatic object, it is likely to generate instructions to store values for the array. Technically, the C standard permits the compiler to do either of these for any of the examples above. Which is used is a matter of optimization and compiler implementation. So the distinction of initializing at “run-time” is largely irrelevant unless performance issues are important.
I can't change elements of array using anonymous function:
var collection=[0, 1, 2];
collection.forEach((c)=> c+=1);
print(collection);
This variant doesn't work eithter:
var collection = [0, 1, 2];
for (var x in collection) {
x=x+1;
}
print(collection);
If you wish to replace/update all items in a list (List<int> items = [1, 2, 3]):
items = items.map((x) => x + 1).toList();
for (int i = 0; i < items.length; i++) items[i] += 1;
items = List<int>.generate(items.length, (i) => items[i] + 1);
List<int> tempItems = [];
items.forEach((x) => tempItems.add(x + 1));
items = tempItems;
You can't change the arguments to a function or var-in loop. You can call methods on them, which might have the side effect of mutating them, but assigning directly to them will not alter the value from which they are effectively copied.
collection.forEach((c)=> c+=1);
In above line you are incrementing parameter by 1 and that will not affect to the list.
It's equavalent to:
collection.forEach((int c) {// in this case int because list contains int's
c = c + 1;
});
As you can see, no point of changing the value of a parameter(local variable).
Since it's 0,1,2, you can do like this: collection.forEach((c)=> collection[c] = c+1);. That is stupid way because whenever you change any value, you will get an error(out of range).
So, here are some ways that you can change list values:
The easy way:
void main() {
var collection=[0, 1, 2];
for(int i = 0; i < collection.length; i++) {
collection[i] += 1;
}
print(collection);
}
Using replaceRange:
void main() {
var collection=[0, 1, 2];
var temp = collection.map((c) => c+1).toList();
collection.replaceRange(0, collection.length, temp);
print(collection);
}
developers, i am new in Kotlin I am trying to take input in Array by using loop and after that, i print the all values of array by using loop but t get only input and not show the other chunk and through the error which is shiwn on attach image
fun main(args: Array<String>) {
var arrayint = Array<Int>(5){0}
var x = 1
val abc:Int = arrayint.size
while( x <= abc)
{
arrayint[x] = readLine()!!.toInt()
x++
}
for(index in 0..4)
{
println(arrayint[index])
}
}
The following is a little more succinct
var arrayint = Array<Int>(5) { readLine()!!.toInt() }
for(x in arrayint)
println(x)
On the first line, instead of using the initializer lambda { 0 }, I use a lambda that call readLine.
On line 2, instead of having to know my range (0..4), I let the language do it for me (an Array is iterable).
Try this:
fun main (args:Array<String>){
var arrayint = Array<Int>(5){0}
var x:Int = 0
val abc:Int = arrayint.size
while( x < abc)
{
arrayint[x] = readLine()!!.toInt()
x++
}
for(index in 0..4)
{
println(arrayint[index])
}
}
You should change x <= abc to x < abc and x = 1 to x = 0. It doesn't work now because if abc = 5 and you loop 4 times then x = 5 but arrays in Kotlin (and Java) start at index 0 which means that array of size 5 has the following indexes: 0, 1, 2, 3, 4 which means that arrayint[5] doesn't exist as 5 is out of bounds (> 4)
One of the shorthand for taking n data elements of data input in an array of predefined size is as follow.
Here the user is going to input a integer
n = number of elements then then the array elements
import java.util.*
fun main(){
val read = Scanner(System.`in`)
val n = read.nextInt()
var arr = Array(n) {i-> read.nextInt()} // taking input
arr.forEach{
println(it) // this loop prints the array
}
}
Following code is taking input in array using loop
import java.util.*
fun main(args: Array<String>) {
var num = arrayOfNulls<Int>(5)
var read= Scanner(System.`in`)
println("Enter array values")
for(i in 0..4)
{
num[i] = read.nextInt()
}
println("The array is")
for(x in num){
println(x)}
}
Following code is taking input of array size and then it's elements
fun main() {
print("Enter Array size: ")
val arraySize = readLine()!!.toInt()
println("Enter Array Elements")
val arr = Array<Int>(arraySize) { readLine()!!.toInt() }
for (x in arr)
println(x)
}
public class I5Exc1a {
public static int[] reverse(int[] array)
{
int[] local = array;
int i = local.length;
int j = 0;
int[] arrayR = new int[i];
for (;i>-1; i--)
{
arrayR[j] = array[i];
j++;
}
return arrayR;
}
}
It is supposed to receive an array and reverse it. but it gives me outofboundexeption when im testing it. I tried fixing it by making an extra array. I think the problem lies in the fact that the length of the array is not passed on correctly to i. Does anyone know how i can solve this?
You are starting from i = local.length and that's already out of bounds.
Look at this array:
[0, 1, 2] - 3 items so length = 3, but if you do array[3] there is no such element, element 2 is at index number 2, starting from 0. Do i-- before your for loop.
private var hitArray:Array = new Array [ 10, 20, 30, 40, 50, 60];
Hello.
I have stored multiple numbers in an array and it appears flash does not like this, I am guessing that I am telling the array that it will either have 10 spaces, 20 spaces, etc...or the array needs to understand what variable it is datatyped to.
so my next idea was to store a hundred numbers into the array by using this
private var hitArray:Array = new Array;
public function Main()
{
for (var i:int = 0; 0 < 100; i++)
{
hitArray.push(i);
}
//iniaite health
hitCounter = 0;
resetPos = new Point(x, y);
//iniation players
_character = new player();
timmy = new SirTimmy();
caroline = new princess();
goblinCanMove = true;
stage.addEventListener(Event.ENTER_FRAME, mainGameLoop)
}
By doing this, I would be able to achieve a greater method of hitTestPoint!
private function enemyCollisionGoblin():void
{
//trace(aKnifeArray.length);
//knive proccess
for (var o:int = 0; o < aKnifeArray.length; o++)
{
var currentKnife:Knife= aKnifeArray[o];
if (currentKnife.x < 0)
{
//trace ('backmissile gone lol');
aKnifeArray.splice(o, 1);
currentKnife.removeKnife();
}
//if (_character.x < redGoblin.x && _character.x > redGoblin.x - 600)
for (var p:int = 0; p < hitArray.length; p++)
{
var number:Number = hitArray[p];
if (currentKnife.hitTestPoint(_character.x + number, _character.y - number, true)) //|| currentKnife.hitTestPoint(_character.x - 50, _character.y - 60, true))
{
trace("hit");
}
}
}
}
The problem I am facing is that flash does not like the for loop in the main constructor, despite it being initiated one.
It should break out of the for Loop if variable i is more than 100, but does not.
My question it, how can I store numbers in an array, so I can use that array in my hit Test Point.
Sorry, I know this is simple, but I'm currently developing and learning!
Advice will be appreciate very much!
You're getting an infinite loop because your loop condition is 0 < 100 instead of i < 100.
for (var i:int = 0; 0 < 100; i++)
Your first method of initializing an array is incorrect. It should instead be
private var hitArray:Array = new Array (10, 20, 30, 40, 50, 60);
You got the brackets wrong. You have to be careful when creating arrays using the Array constructor because:
var awd:Array = new Array (10);
The above will create an empty array with a capacity of 10.
var awd:Array = [10];
The above will create an array with a single element of the number 10. This is usually the way to create an array because it's quick and easy.
var awd:Array = [10, 1, 2, 3, 4, 5];