## Interview Question

Interview*(Student Candidate)* Palo Alto, CA

Answer## Generate a new array from an array of numbers. Start from

the beginning. Put the number of some number first, and then that number. For example, from array 1, 1, 2, 3, 3, 1 You should get 2, 1, 1, 2, 2, 3, 1, 1 Write a program to solve this problem.

## Interview Answer

7 Answers

function numberArray( $arr ){ $a = array(); $number = null; $c = -1; foreach( $arr as $v ){ if( $v != $number ){ if( $number ){ $a[] = $c; $a[] = $number; } $number = $v; $c = 1; } else { ++$c; } } if( $c > 0 ){ $a[] = $c; $a[] = $number; } return $a; } var_export( numberArray( array( 1,1,2,3,3,1 ) ) );

<?php function foo($input) { $len = count($input); $toRet = array(); $idx = 0; $current = null; while ($idx < $len) { $current = $input[$idx]; $currentCount = 0; while ($current == $input[$idx]) { $currentCount++; $idx++; } $toRet[] = $currentCount; $toRet[] = $current; } return $toRet; } $input = array(1); for ($index = 0; $index < 10; $index++) { $input = foo($input); foreach ($input as $key=>$val) { echo $val . "\t"; } echo " \n"; } ?>

working in php: <? $list = array(1,1,2,3,3,1); $result = numberArray($list); print_r($result); function numberArray($list){ $result = array(); $count = 1; for($i=0;$i<sizeof($list)-1;$i++){ if(($i>sizeof($list)-2) || ($list[$i]!=$list[$i+1])){ $result[]=$count; for($j=0;$j<$count;$j++) $result[]=$list[$i]; $count=1; }else{ $count++; } } return $result; } ?>

vector<int> reformat(int arr[], int size) { vector<int> res; int j, count = 0; for(int i = 0; i < size; ) { cout << i << endl; count = 0; for(j = i; j < size; j++) { if(arr[j] != arr[i]) break; count++; } res.push_back(count); res.push_back(arr[i]); i = j; } return res; }

int i=0; int j=1; ArrayList

@Anonymous: Your inner while loop will cause an out-of-bounds exception to be thrown when your scanning hits the end of the array. Your while loop will try to access givenArr[i+j] even when j increments to the point that surpasses the length of the array. You need while((i+j) != givenArr.length ... )

## Add Answers or Comments

To comment on this, Sign In or Sign Up.

int[] Reformat(int[] original, int length) { LinkedList<int> list = new LinkedList<int>(); int currentCount; for(int i=0;i<length-1;i++) { if (original[i] != original[i+1]) { list.Insert(original[i]); list.Insert(currentCount); currentCount = 0; } else { currentCount++; } } int[] formattedList = new int[list.length]; for(int i=0;i<list.length;i++) { formattedList[i] = list.Remove; } return formattedList; }