Assigning Values to an Array: Difference between revisions
(→[[Java]]: Use Java header instead) |
m (Changed over to headers.) |
||
Line 4: | Line 4: | ||
In this task, the goal is to assign a value to an element of an [[array]]. The value should only replace an existing value, and not insert a new key should the key not exist. If the key does not exist, an error should be returned. |
In this task, the goal is to assign a value to an element of an [[array]]. The value should only replace an existing value, and not insert a new key should the key not exist. If the key does not exist, an error should be returned. |
||
== |
=={{header|ActionScript}}== |
||
[[Category:ActionScript]] |
|||
arr[0] = 1; |
arr[0] = 1; |
||
arr[1] = 'a'; |
arr[1] = 'a'; |
||
arr[2] = 5.678; |
arr[2] = 5.678; |
||
== |
=={{header|Ada}}== |
||
[[Category:Ada]] |
|||
'''Compiler:''' [[GCC]] 4.1.2 |
'''Compiler:''' [[GCC]] 4.1.2 |
||
package Pkg is |
package Pkg is |
||
Line 25: | Line 23: | ||
end Pkg; |
end Pkg; |
||
== |
=={{header|AppleScript}}== |
||
[[Category:AppleScript]] |
|||
set item location of array to value |
set item location of array to value |
||
Line 32: | Line 29: | ||
set end of array to item |
set end of array to item |
||
== |
=={{header|Brainf***}}== |
||
[[Category:Brainf***]] |
|||
To assign values 5, 6, and 7 to array elements 1,2,3: |
To assign values 5, 6, and 7 to array elements 1,2,3: |
||
Line 43: | Line 39: | ||
>+++++++ move value 7 to element 3 |
>+++++++ move value 7 to element 3 |
||
== |
=={{header|C}}== |
||
[[Category:C]] |
|||
'''Compiler:''' [[GCC]] 4.1.1 |
'''Compiler:''' [[GCC]] 4.1.1 |
||
int writeToIntArray(int *array, size_t array_sz, int loc, int val) |
int writeToIntArray(int *array, size_t array_sz, int loc, int val) |
||
Line 55: | Line 50: | ||
} |
} |
||
== |
=={{header|C sharp|C #}}== |
||
[[Category:C sharp]] |
|||
'''Platform:''' [[.NET]] |
'''Platform:''' [[.NET]] |
||
'''Language Version:''' 1.0+ |
'''Language Version:''' 1.0+ |
||
Line 80: | Line 74: | ||
} |
} |
||
== |
=={{header|ColdFusion}}== |
||
[[Category:ColdFusion]] |
|||
<cffunction name="writeToArray"> |
<cffunction name="writeToArray"> |
||
<cfargument name="array"> |
<cfargument name="array"> |
||
Line 102: | Line 95: | ||
<cfset myArray[3] = 987654> |
<cfset myArray[3] = 987654> |
||
== |
=={{header|Common Lisp}}== |
||
[[Category:Common Lisp]] |
|||
(setf (aref array index) value) |
(setf (aref array index) value) |
||
== |
=={{header|Delphi}}== |
||
[[Category:Delphi]] |
|||
procedure WriteToIntArray(var Arr: array of Integer; Loc: Integer; Val: Integer); |
procedure WriteToIntArray(var Arr: array of Integer; Loc: Integer; Val: Integer); |
||
begin |
begin |
||
Line 114: | Line 105: | ||
end; |
end; |
||
== |
=={{header|Forth}}== |
||
[[Category:Forth]] |
|||
'''Interpreter:''' ANS Forth |
'''Interpreter:''' ANS Forth |
||
: ]! ( n addr ix -- ) cells + ! ; \ ex. 3 buffer[ 2 ]! |
: ]! ( n addr ix -- ) cells + ! ; \ ex. 3 buffer[ 2 ]! |
||
=={{header|Fortan}}== |
|||
==[[Fortran]]== |
|||
[[Category:Fortran]] |
|||
'''Compiler:''' Any ANSI F77 (e.g. GNU g77) |
'''Compiler:''' Any ANSI F77 (e.g. GNU g77) |
||
a(55) = 12 |
a(55) = 12 |
||
== |
=={{header|Haskell}}== |
||
'''Compiler:''' GHC 6.6 |
'''Compiler:''' GHC 6.6 |
||
===List=== |
===List=== |
||
Line 170: | Line 159: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
[[Category:Java]] |
|||
'''Platform:''' [[J2SE]] 1.2+ |
'''Platform:''' [[J2SE]] 1.2+ |
||
public void writeToIntArray(int[] array, int loc, int val){ array[loc]=val; } |
public void writeToIntArray(int[] array, int loc, int val){ array[loc]=val; } |
||
== |
=={{header|JavaScript}}== |
||
[[Category:JavaScript]] |
|||
function setElem(array, loc, val) { //returns 0 if out of bounds |
function setElem(array, loc, val) { //returns 0 if out of bounds |
||
if(typeof array[loc] == typeof undefined) { |
if(typeof array[loc] == typeof undefined) { |
||
Line 193: | Line 180: | ||
function writeToArray(array, loc, val) { array[loc] = val; } |
function writeToArray(array, loc, val) { array[loc] = val; } |
||
=={{header |
=={{header|LSE64}}== |
||
10 array :array |
10 array :array |
||
0 array 5 [] ! # store 0 at the sixth cell in the array |
0 array 5 [] ! # store 0 at the sixth cell in the array |
||
== |
=={{header|mIRC Scripting Language}}== |
||
[[Category:mIRC Scripting Language]] |
|||
'''Interpreter:''' [[mIRC]] |
'''Interpreter:''' [[mIRC]] |
||
'''Library:''' [[mArray Snippet]] |
'''Library:''' [[mArray Snippet]] |
||
Line 204: | Line 190: | ||
alias write2array { echo -a $array_write(MyArray, 2, 3, Rosetta) } |
alias write2array { echo -a $array_write(MyArray, 2, 3, Rosetta) } |
||
== |
=={{header|Objective-C}}== |
||
[[Category:Objective-C]] |
|||
'''Compiler:''' [[GCC]] 3.3+ |
'''Compiler:''' [[GCC]] 3.3+ |
||
Line 213: | Line 198: | ||
} |
} |
||
=={{header|Ocaml}}== |
|||
==[[OCaml]]== |
|||
[[Category:OCaml]] |
|||
'''Interpreter:''' [[OCaml]] |
'''Interpreter:''' [[OCaml]] |
||
let writeToArray arr loc val = arr.(loc) <- val;; |
let writeToArray arr loc val = arr.(loc) <- val;; |
||
Line 222: | Line 206: | ||
let writeToArray = Array.set |
let writeToArray = Array.set |
||
== |
=={{header|Perl}}== |
||
[[Category:Perl]] |
|||
'''Interpreter:''' [[Perl]] 5.8.8 |
'''Interpreter:''' [[Perl]] 5.8.8 |
||
Line 239: | Line 222: | ||
# will replace the 4th, 5th and 6th elements with the first 3 values in @values |
# will replace the 4th, 5th and 6th elements with the first 3 values in @values |
||
== |
=={{header|PHP}}== |
||
[[Category:PHP]] |
|||
<?php |
<?php |
||
Line 267: | Line 249: | ||
?> |
?> |
||
== |
=={{header|PL/SQL}}== |
||
[[Category:PL/SQL]] |
|||
'''Interpreter:''' Oracle compiler |
'''Interpreter:''' Oracle compiler |
||
set serveroutput on |
set serveroutput on |
||
Line 295: | Line 276: | ||
/ |
/ |
||
== |
=={{header|Pop11}}== |
||
[[Category:Pop11]] |
|||
value -> array(index); |
value -> array(index); |
||
Line 304: | Line 284: | ||
== |
=={{header|Python}}== |
||
[[Category:Python]] |
|||
To change existing item, (raise IndexError if the index does not exists): |
To change existing item, (raise IndexError if the index does not exists): |
||
Line 313: | Line 292: | ||
array.append(value) |
array.append(value) |
||
== |
=={{header|Ruby}}== |
||
[[Category:Ruby]] |
|||
'''Interpreter:''' [[Ruby]] 1.8.5 |
'''Interpreter:''' [[Ruby]] 1.8.5 |
||
# To specify a value for a known index |
# To specify a value for a known index |
||
Line 328: | Line 306: | ||
arr << 1 |
arr << 1 |
||
== |
=={{header|Scala}}== |
||
[[Category:Scala]] |
|||
val array = new Array[int](10) // create a 10 element array of integers |
val array = new Array[int](10) // create a 10 element array of integers |
||
array(3) = 44 |
array(3) = 44 |
||
Line 347: | Line 324: | ||
l(2) // 2 |
l(2) // 2 |
||
== |
=={{header|Tcl}}== |
||
[[Category:Tcl]] |
|||
proc setIfExist {theVariable value} { |
proc setIfExist {theVariable value} { |
||
upvar 1 $theVariable variable |
upvar 1 $theVariable variable |
||
Line 361: | Line 337: | ||
setIfExist x 10 ;# error if x doesn't exist |
setIfExist x 10 ;# error if x doesn't exist |
||
== |
=={{header|Toka}}== |
||
[[Category:Toka]] |
|||
100 cells is-array foo |
100 cells is-array foo |
||
1000 10 foo array.put ( Put value '1000' into array 'foo' at slot '10' ) |
1000 10 foo array.put ( Put value '1000' into array 'foo' at slot '10' ) |
||
Line 368: | Line 343: | ||
char: A 1 foo array.putChar ( Put value 'A' (ASCII code) into character array 'bar' at slot '1' ) |
char: A 1 foo array.putChar ( Put value 'A' (ASCII code) into character array 'bar' at slot '1' ) |
||
== |
=={{header|Visual Basic}}== |
||
[[Category:Visual Basic]] |
|||
'''Language Version:''' 5.0+ |
'''Language Version:''' 5.0+ |
||
Private Function writeToArray(intArray() As Integer, arraySize As Integer, loc As Integer, value As Integer) As Integer |
Private Function writeToArray(intArray() As Integer, arraySize As Integer, loc As Integer, value As Integer) As Integer |
||
Line 380: | Line 354: | ||
End Function |
End Function |
||
== |
=={{header|VBScript}}== |
||
[[Category:VBScript]] |
|||
===Simple Example=== |
===Simple Example=== |
Revision as of 17:11, 13 November 2007
You are encouraged to solve this task according to the task description, using any language you may know.
In this task, the goal is to assign a value to an element of an array. The value should only replace an existing value, and not insert a new key should the key not exist. If the key does not exist, an error should be returned.
ActionScript
arr[0] = 1; arr[1] = 'a'; arr[2] = 5.678;
Ada
Compiler: GCC 4.1.2
package Pkg is type Arr is array (Positive range <>) of Integer; procedure Assign (Value : Integer; To : in out Arr; Index : Positive); -- Raise exception Constraint_Error if Index > To'Last end Pkg; package body Pkg is procedure Assign (Value : Integer; To : in out Arr; Index : Positive) is begin To (Index) := Value; end Assign; end Pkg;
AppleScript
set item location of array to value
To put an item on the end of a list:
set end of array to item
Brainf***
To assign values 5, 6, and 7 to array elements 1,2,3:
[-]>[-]>[-] zero array elements <<< go back to index 1 +++++ move value 5 to element 1 >++++++ move value 6 to element 2 >+++++++ move value 7 to element 3
C
Compiler: GCC 4.1.1
int writeToIntArray(int *array, size_t array_sz, int loc, int val) { // Check bounds on array if (loc > array_sz || loc < 0) return -1; array[loc] = val; return 0; }
C#
Platform: .NET Language Version: 1.0+
public void WriteToIntArray(int[] array, int loc, int val){ array[loc]=val; }
C++
Compiler: GCC 4.1.2
template<class T> inline int writeToArray(T array[], size_t loc, const T& val) { if (loc > sizeof(array)) return -1; // Could throw an execption if so desired array[loc] = val; return 0; }
Compiler: Visual C++ 2005
template<class C> inline void writeToArray(C& container, typename C::size_type loc, const typename C::value_type& val) { std::fill_n(container.begin() + loc, 1, val); }
ColdFusion
<cffunction name="writeToArray"> <cfargument name="array"> <cfargument name="location"> <cfargument name="value"> <cfif arrayLen(arguments.array) GTE arguments.location> <cfset arguments.array[arguments.location] = arguments.value> <cfelse> <cfthrow message="Location does not exist"> </cfif> <cfreturn arguments.array> </cffunction> <cfset myArray = arrayNew(1)> <cfset myArray[1] = 1> <cfset myArray = writeToArray(myArray, 1, 123456)>
Note that throwing errors in ColdFusion doesn't give that "friendly" appearance. The standard way to change/add a value in an array would be simply:
<cfset myArray[3] = 987654>
Common Lisp
(setf (aref array index) value)
Delphi
procedure WriteToIntArray(var Arr: array of Integer; Loc: Integer; Val: Integer); begin Arr[Loc] := Val; end;
Forth
Interpreter: ANS Forth
: ]! ( n addr ix -- ) cells + ! ; \ ex. 3 buffer[ 2 ]!
Fortan
Compiler: Any ANSI F77 (e.g. GNU g77)
a(55) = 12
Haskell
Compiler: GHC 6.6
List
Most Haskell programs use lists instead of arrays. This is suitable for the general case.
Simple Version
setIndex :: [a] -- Original list -> Int -- Index to insert at -> a -- Value to insert -> [a] -- Resulting list setIndex xs ii v = let (h, (_ : ts)) = splitAt ii xs in h ++ (v : ts)
Efficient Version
setIndex xs ii v | ii < 0 = error "Bad index" | otherwise = _setIndex xs ii v where _setIndex [] _ _ = error "Bad index" _setIndex (_ : xs) 0 v = v : xs _setIndex (x : xs) ii v = x : (setIndex xs (ii - 1) v)
Array
Technically, this creates clones the original array, then updates the new array; the original array still exists. This applies a list of changes to the array.
import Data.Array -- Create the array of data a1 = array (0, 4) [(ii, ii * 2) | ii <- [0 .. 4]] -- Update 1 entry a2 = a1 // [(2, 12)] -- Update several entries a3 = a1 // [(ii, ii + 10) | ii <- [1 .. 3]]
Java
Platform: J2SE 1.2+
public void writeToIntArray(int[] array, int loc, int val){ array[loc]=val; }
JavaScript
function setElem(array, loc, val) { //returns 0 if out of bounds if(typeof array[loc] == typeof undefined) { return 0; //element doesn't already exist -- out of bounds } else { array[loc] = val return 1; //OK }//if }//setElem //use: var ary=[10,20,30] //0,1,2 defined var ok = setElem(ary,3,'three') if(!ok) alert('oops, error')
Simpler if you don't mind adding an element if it does not already exist:
function writeToArray(array, loc, val) { array[loc] = val; }
LSE64
10 array :array 0 array 5 [] ! # store 0 at the sixth cell in the array
mIRC Scripting Language
Interpreter: mIRC Library: mArray Snippet
alias write2array { echo -a $array_write(MyArray, 2, 3, Rosetta) }
Objective-C
Compiler: GCC 3.3+
- (void)addValue:(id)value toArray:(NSMutableArray *)array position:(unsigned)pos { [array insertObject:value atIndex:pos]; }
Ocaml
Interpreter: OCaml
let writeToArray arr loc val = arr.(loc) <- val;;
variant:
Interpreter: OCaml
let writeToArray = Array.set
Perl
Interpreter: Perl 5.8.8
For a single index/value assignment:
$array[$index] = $value;
To assign multiple values to multiple indices:
@array[@indexes] = @values;
To assign an array slice:
@array[3..5] = @values; # will replace the 4th, 5th and 6th elements with the first 3 values in @values
PHP
<?php function writeToArray(&$array, $index, $value) { $array[$index] = $value; } // Usage example writeToArray($array, 1, 6 ); ?>
Note that this is a "function" based example, and the relevant acting code is the following
$array[$index] = $value;
This does not conform to the (somewhat arbitrary) specific requirements of the task, in that it does not return an error if the key index) does not exist. To satisfy the task requirements:
<?php function writeToArray(&$array, $index, $value) { if(array_key_exists($index, $array)) $array[$index] = $value; else return false; } // Usage example writeToArray($array, 1, 6 ); ?>
PL/SQL
Interpreter: Oracle compiler
set serveroutput on declare type myarray is table of number index by binary_integer; x myarray; i pls_integer; begin -- populate array for i in 1..5 loop x(i) := i; end loop; i :=0; -- print array loop i := i + 1; begin dbms_output.put_line(x(i)); exception when no_data_found then exit; end; end loop; end; /
Pop11
value -> array(index);
Note that normal Pop11 array signal error when accesing non existing values (all values within index bounds exist).
Python
To change existing item, (raise IndexError if the index does not exists):
array[index] = value
To append to the end of the array:
array.append(value)
Ruby
Interpreter: Ruby 1.8.5
# To specify a value for a known index # Usage: arr[index] = value arr = 1,2,3,4,5 arr[0] = 10
# To push a value onto an array. This accepts single or multiple arguments: arr.push( 1 ) arr.push( 1, 2, 3 )
# You can also use the << operator with one argument: arr << 1
Scala
val array = new Array[int](10) // create a 10 element array of integers array(3) = 44 array(22) = 11 // java.lang.ArrayIndexOutOfBoundsException: 22
import scala.collection.mutable.ArrayBuffer val array2 = new ArrayBuffer[int] array2 += 1 array2 += 2 array2 += 3 array2(1) // 2 (zero based indexing) array2(1) = 33 array2.toString // ArrayBuffer(1,33,3)
var l = List(1,2,3) l = 44 :: l // List(44,1,2,3) l(2) // 2
Tcl
proc setIfExist {theVariable value} { upvar 1 $theVariable variable if {[info exists theVariable]} { set theVariable $value } else { error "$theVariable doesn't exist" } }
Note that setIfExist is general purpose and works on regular variables as well as arrays:
setIfExist foo(bar) 10 ;# error if foo(bar) doesn't exist setIfExist x 10 ;# error if x doesn't exist
Toka
100 cells is-array foo 1000 10 foo array.put ( Put value '1000' into array 'foo' at slot '10' ) 10 chars is-array bar char: A 1 foo array.putChar ( Put value 'A' (ASCII code) into character array 'bar' at slot '1' )
Visual Basic
Language Version: 5.0+
Private Function writeToArray(intArray() As Integer, arraySize As Integer, loc As Integer, value As Integer) As Integer If loc > arraySize Then writeToArray = -1 Else intArray(loc) = value writeToArray = 0 End If End Function
VBScript
Simple Example
Define our Array
Dim myArray (5)
Use a For Next loop to set the array data.
For i = 0 To 4 myArray(i) = i Next
Use a For Next loop and MsgBox to display the array data.
MsgBox("Print array values") For i = 0 To 4 msgbox("myArray element " & i & " = " & myArray(i)) Next
Variable Array Length
Example where we don't know the required array size at the start and where we need to increase the array size as we go
Define an array - but we don't know how big yet.
Dim myArray2 ()
OK, now we know how big an array we need.
ReDim myArray2(3)
Load the array
For i = 0 To 2 myArray2(i) = i Next
Print the array
MsgBox("We've set the new array size and set the data") For i = 0 To 2 MsgBox "myArray2 element " & i & " = " & myArray2(i) Next
Now we need to make the array bigger. Note the Preserve keyword so that the existing data in the array is not lost when we resize it.
ReDim Preserve myArray2(5)
Load the array
For i = 3 To 4 myArray2(i) = i Next
Print the array
MsgBox ("We've increased the array size and loaded more data") For i = 0 To 4 MsgBox "myArray2 element " & i & " = " & myArray2(i) Next